Open filhocodes opened 7 years ago
I was going to create a PR for this, but #1 is still open.
@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();
@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()
;
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:
SlugFormatter
: In order to get a slug from a string, first you must remove every punctuation and unknown chars, then you reduce multiples spaces into one, and after that you replace the spaces by dashes or underscores.WordWrapFormatter
: If you want to create a multi line string from another, by adding EOL chars after some fixed length, without breaking words and messing up existing line breaks, you probably want to standardize newlines first, and then check the length of each line.CamelCaseFormatter
: If you want to obtain the camel case format from a string, first you gonna applyucwords
, after that you remove all spaces, and finally you put the first character in lower case.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)
Usage example
Formatter
contractAll 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.:Discussion points
we-can-do-anything-with-strings
?phpol/str-formatters
package?