phpol / string

PHP Object Library :: String manipulation library
4 stars 0 forks source link

String Formatters #2

Open filhocodes opened 7 years ago

filhocodes commented 7 years ago

The following proposal is based in PR #1 and the discussion at phpol/phpol#4. (Also, I can move this to phpol/phpol if you guys want).

Formatters

Formatters are a way to generate strings from other strings by having a series of functions executed on the first one. Examples:

They're not part of the PHP core functions, some frameworks create helpers to give the developer an easy way to format strings. Also, by having an open interface, developers can create their own formatters.

Project (suggestion)

src/
  Contracts/
    Str
    Formatter
  Formatters/
    SlugFormatter
    HtmlFormatter (package may suggest some package to escape strings and prevent XSS)
    CamelCaseFormatter
    YouGuysGotTheDrillFormatter
  Str

Usage example

$title = new Str('I love writing blog posts!');
$slug = $title->format(new SlugFormatter));

Formatter contract

All formatters must implement a public function format(Str $string) : Str. Any others methods may be implemented if the developer wants the formatter to have options. E.g.:

new SlugFormatter($separator = '-', $allowedChars = '[a-zA-Z0-9\-]');
// or
$slugFormatter->setSeparator('_');

Discussion points

filhocodes commented 7 years ago

I was going to create a PR for this, but #1 is still open.

joubertredrat commented 7 years ago

@marcossffilho I think that is better to support one or more formatters, as example below:

$title = new Str('I love writing blog posts!');
$title->addFormatter(new SlugFormatter);
$title->addFormatter(new UpcaseFormatter);
$text = $title->output();

$title = new Str('I love writing blog posts!');
$title->addFormatter(
    new SlugFormatter,
    new UpcaseFormatter
);
$text = $title->output();
filhocodes commented 7 years ago

@joubertredrat I think that is too much:

First: I can't picture a scenario where you format a formatted string. Second: since format returns a Str object, you can always execute $string->format()->format();