A Laravel formatting utility package.
We often find ourselves converting request input to meet certain formats. We do it before validation, maybe after validation, or we do it in our mutators. This package was designed to ease that process and to keep our controller/model code cleaner. This package mostly uses laravel's helper methods on top of its own custom methods, there is also some formatting using the Carbon date library.
composer require collab-corp/formatter
You can new up a formatter
new Formatter('yourValue')->{someMethod}()->get();
In addition to calling get, it is also possible to get the results by casting the formatter to a string
(string)Formatter::create('something')->{method}();
or call the static method create Formatter::create('yourValue')->{someMethod}()->get();
Here are a few examples using laravel's mutators :
<?php
use CollabCorp\Formatter\Formatter;
//etc.
class SomeModel extends Model{
public function getProductPriceAttribute(){
//format our number to 2 decimal places or however many places you want
return new Formatter($this->attributes['price'])->decimals(2)->get();
//or can call static create
return Formatter::create($this->attributes['price'])->decimals(2)->get();
}
public function getPhoneNumberFormattedAttribute(){
//format a 10 or 11 digit number to be in parenthesis x(xxx)xxx-xxxx
return new Formatter($this->attributes['phone_number'])->phone()->get();
}
}
These above examples are nothing special, you could do the same with a simple method/function call yourself. The real usefulness of this package is the ability to method chain and process many conversions on a input:
<?php
//convert our phone number to a parenthesis format but first make sure to strip any non numeric characters off first
$result = new Formatter($request->phone_number)
->onlyNumbers()
->phone()
->get();
//another example
$result = new Formatter(2)
->add(2)
->multiply(3)
->finish("%")
->get(); // 12%
This makes it convienient to run multiple conversions/formatting for our value. It also makes it easier to keep code clean and having to combine multiple methods yourself. Take the above second example. Doing the method calls manually would look something like this:
Str::finish(bcmul(bcadd(2, 2), 3), "%");
Yuck! right? Although this was a rather small example and not bad, imagine if you had to do 3 other conversions? Keep your code cleaner and more readable with method chaining :D
Another useful feature of this package is processing request input to run multiple formatting methods on the request input.The workflow for this is very similiar to laravel validation, so it should feel very natural to you. Here's an example of having middleware automatically format/convert input before the request hits the controller:
<?php
public function handle($request, Closure $next, $guard = null)
{
$formatters=[
//convert to parenthesis phone format after stripping all non numeric characters
'phone'=>'onlyNumbers|phone',
//format to 2 decimal places
'price'=>'decimals:2',
// trim off % signs,convert to decimal percent with 2 decimal places.
'tax'=>'trim:%|percentage:2',
// make this input slug friendly
'page'=>'slug'
];
$convertedInput = Formatter::convert($formatters, $request->all());
//replace existing request data with new converted data,
$request->replace($convertedInput);
return $next($request);
}
Very similiar to laravel validation right? When defining the formatters,use the name of the input in the request as the key and the value being the formatter(s) you want to run on that input. Seperate each method with a pipe character |
.
If the formatter method you want to call needs parameters then specify paramter input with a colon :
then pass the parameters in a comma delimited list in the order that the method accepts them, refer to the methods section to see what methods require/accept parameters.
ex: add:2,2
Note: If the request value is a single dimensional array, the formatter method will be applied to every value on the array element. More complex arrays not tested/supported.
The above example is being explicit in its request keys, but you could also specify pattern input keys using asterisk to match input keys and process them if they match the pattern:
<?php
$formatters=[
'*phone'=>'onlyNumbers|phone', //run methods on any input thats name ends with phone
'phone*'=>'onlyNumbers|phone', //run methods on any input thats name starts with phone
'*phone*'=>'onlyNumbers|phone', //run methods on any input thats name has the word phone in it.
];
$convertedInput = Formatter::convert($formatters, $request->all());
The formatter class simply uses PHP's magic method __call
to call methods on other various formatter classes included in the package. If your application only needed to do certain type of conversions, then you could import only the needed class and use that. For example say you only needed to do some Math conversions, you could import the MathFormatter only:
Heres another middleware example:
<?php
//Available formatters: DateFormatter,StringFormatter,MathFormatter
public function handle($request, Closure $next, $guard = null)
{
$formatters=[
'someNumber'=>'add:20|multiply:2',
//etc.
];
$convertedInput = MathFormatter::convert($formatters, $request->all());
//replace existing request data with new converted data,
$request->replace($convertedInput);
return $next($request);
}
- ssn
- phone
- truncate
- finish
- start
- prefix
- suffix
- camelCase
- snakeCase
- titleCase
- kebabCase
- studlyCase
- slug
- plural
- limit
- encrypt
- decrypt
- bcrypt
- replace
- onlyNumbers
- onlyLetters
- divide
- power
- percentage
Note: These simply are methods called using the Carbon Library. These are the only available methods on the Formatter:
- toCarbon
- format
- setTimezone
- addYears
- addMonths
- addWeeks
- addDays
- addHours
- addMinutes
- addSeconds
- subYears
- subMonths
- subWeeks
- subDays
- subHours
- subMinutes
- subSeconds
-
convert a 9 numeric value to a social security format:
//'123-45-6789' Formatter::create('123456789')->ssn()->get();
-
convert a 10 or 11 numeric value to a parenthesis format:
//'(123)456-7890' Formatter::create('1234567890')->phone()->get(); //'1(123)456-7890' Formatter::create('11234567890')->phone()->get();
-
truncate off the specified number of characters of the value:
//'foo' Formatter::create('foobar')->truncate(3)->get();
-
add the specified character to the end of the string if it doesnt already contain it:
//'foobar' Formatter::create('foo')->finish('bar')->get(); //'foobar' Formatter::create('foobar')->finish('bar')->get();
-
add the specified character to the start of the string if it doesnt already contain it:
//'foobar' Formatter::create('foobar')->start('foo')->get(); //'foobar' Formatter::create('bar')->start('foo')->get();
-
add the specified character to the start of the string:
//'foofoobar' Formatter::create('foobar')->prefix('foo')->get();
-
add the specified character to the end of the string:
// 'foobarfoo' Formatter::create('foobar')->suffix('foo')->get();
-
convert value to camel case:
//'fooBar' Formatter::create('foo bar')->camelCase()->get();
-
convert value to snake case:
//'foo_bar' Formatter::create('foo bar')->snakeCase()->get();
-
convert value to snake case:
//'Foo Bar' Formatter::create('foo bar')->titleCase()->get();
-
convert value to kebab case:
// 'foo-bar' Formatter::create('foo bar')->kebabCase()->get();
-
convert value to kebab case:
//'FooBar' Formatter::create('foo bar')->studlyCase()->get();
-
convert value to a slug friendly string:
//'foo-bar' Formatter::create('foo bar')->slug()->get();
-
convert value to its plural form:
//'children' Formatter::create('child')->plural()->get();
-
limit the string the first n of characters:
//'child' Formatter::create('children')->limit(5)->get();
-
encrypt the value:
//'{some encrypted string}' Formatter::create('someString')->encrypt()->get();
-
decrypt the value:
//the original string Formatter::create('{some encrypted string}')->decrypt()->get();
-
hash the value with bcrypt:
//'{some hashed string result}' Formatter::create('secret1')->bcrypt()->get();
-
replace the given character with the given replacement character, defaults to empty string for replacement:
//'bar' Formatter::create('foobar')->replace('foo')->get(); //'poobar' Formatter::create('foobar')->replace('foo', 'poo')->get();
-
removes all characters that are not numbers from the value:
//'123' Formatter::create('sfsdfs123')->onlyNumbers()->get();
-
removes all characters that are not letters from the value:
//'test' Formatter::create('#(@)!@test123')->onlyLetters()->get();
-
format a number to have the speficied number of decimal places:
//20.00 Formatter::create(20)->decimals(2)->get();
-
add a given number to the current numeric value.Automatically scales 0 decimal places unless specified as 2nd param:
//22 Formatter::create(20)->add(2)->get(); //22.00 Formatter::create(20)->add(2,2)->get();
-
subtract a given number from the current numeric value. Automatically scales 0 decimal places unless specified as 2nd param:
//18 Formatter::create(20)->subtract(2)->get(); //18.00 Formatter::create(20)->subtract(2,2)->get();
-
divide a the current numerica value by a given number. Automatically scales 0 decimal places unless specified as 2nd param:
//18 Formatter::create(20)->divide(2)->get(); //18.00 Formatter::create(20)->divide(2,2)->get();
-
raise the current value by a given power. Automatically scales 0 decimal places unless specified as 2nd param:
//400 Formatter::create(20)->power(2)->get(); //400.00 Formatter::create(20)->power(2,2)->get();
-
convert the value to a decimal percentage. Automatically scales 2 decimal places unless specified as 2nd param:
//0.20 Formatter::create(20)->percentage()->get(); //0.200 Formatter::create(20)->percentage(2,2)->get();
-
convert the value to a Carbon\Carbon instance:
//Carbon instance "2030-12-22 00:00:00" Formatter::create("12/22/2030")->toCarbon()->get();
-
convert the Carbon\Carbon instance to a specified date/time string:
$formatter = Formatter::create("12/22/2030")->toCarbon(); //"December 22, 2030 00:00:00" $formatter->format('F d, Y')->get();
-
set the specified timezone on the Carbon instance:
$formatter = Formatter::create("12/22/2030")->toCarbon(); //Carbon instance with given timezone set "2030-12-22 00:00:00". $formatter->setTimezone('America/Toronto')->get();
-
add the given number of years to the Carbon instance:
$formatter = Formatter::create("12/22/2030")->toCarbon(); //Carbon instance "2032-12-22 00:00:00". $formatter->addYears(2)->get();
-
add the given number of months to the Carbon instance:
$formatter = Formatter::create("12/22/2030")->toCarbon(); //Carbon instance "2031-02-22 00:00:00". $formatter->addMonths(2)->get();
-
add the given number of weeks to the Carbon instance:
$formatter = Formatter::create("12/22/2030")->toCarbon(); //Carbon instance "2031-01-04 00:00:00". $formatter->addWeeks(2)->get();
-
add the given number of days to the Carbon instance:
$formatter = Formatter::create("12/22/2030")->toCarbon(); //Carbon instance "2030-12-24 00:00:00". $formatter->addDays(2)->get();
-
add the given number of hours to the Carbon instance:
$formatter = Formatter::create("2030-12-22 02:02:02")->toCarbon(); //Carbon instance "2030-12-22 04:02:02". $formatter->addHours(2)->get();
-
add the given number of minutes to the Carbon instance:
$formatter = Formatter::create("2030-12-22 02:02:02")->toCarbon(); //Carbon instance "2030-12-22 02:04:02". $formatter->addMinutes(2)->get();
-
add the given number of seconds to the Carbon instance:
$formatter = Formatter::create("2030-12-22 02:02:02")->toCarbon(); //Carbon instance "2030-12-22 02:02:04". $formatter->addSeconds(2)->get();
-
sub the given number of years to the Carbon instance:
$formatter = Formatter::create("12/22/2030")->toCarbon(); //Carbon instance "2028-12-22 00:00:00". $formatter->subYears(2)->get();
-
subtract the given number of months to the Carbon instance:
$formatter = Formatter::create("12/22/2030")->toCarbon(); //Carbon instance "2030-10-22 00:00:00". $formatter->subMonths(2)->get();
-
subtract the given number of weeks to the Carbon instance:
$formatter = Formatter::create("12/22/2030")->toCarbon(); //Carbon instance "2030-12-08 00:00:00". $formatter->subWeeks(2)->get();
-
subtract the given number of days to the Carbon instance:
$formatter = Formatter::create("12/22/2030")->toCarbon(); //Carbon instance "2030-12-20 00:00:00". $formatter->subDays(2)->get();
-
subtract the given number of hours to the Carbon instance:
$formatter = Formatter::create("2030-12-22 02:02:02")->toCarbon(); //Carbon instance "2030-12-22 00:02:02". $formatter->subHours(2)->get();
-
subtract the given number of minutes to the Carbon instance:
$formatter = Formatter::create("2030-12-22 02:02:02")->toCarbon(); //Carbon instance "2030-12-22 02:00:02". $formatter->subMinutes(2)->get();
-
subtract the given number of seconds to the Carbon instance:
$formatter = Formatter::create("2030-12-22 02:02:02")->toCarbon(); //Carbon instance "2030-12-22 02:02:00". $formatter->subSeconds(2)->get();
Contributions are always welcome in the following matter.
- Issue Tracker
- Pull Requests
- Collab Corp Slack(Will send invite)
The project is licensed under the MIT license.