-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Labels
Description
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)
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
- Is this useful?
- Does this solves the
we-can-do-anything-with-strings? - Should the Str component have any formatters by default?
- Should we create a
phpol/str-formatterspackage?