Skip to content
Jarek Tkaczyk edited this page May 28, 2015 · 3 revisions

Mutator

Mutator is a simple service that provides easy way to mutate any value through one or more callables in a pipeline-like manner.

A callable might be any of the following:

  • php internal function - eg. strtolower
  • user defined function - eg. str_slug
  • public static method - eg. Illuminate\Support\Str@slug
  • public method on instantiable class - eg. My\Class@someMethod
  • macro on the Mutator

The first 3 are self-explanatory, so let's talk about the last 2:

Public method on instantiable class - it's as simple as being able to do new My\Class, so there are no required constructor params without default values on the My\Class.

Macro on the Mutator - the service uses Macroable trait, so in order to extend it, simply do this:

// place it for example in your AppServiceProvider:

    public function boot()
    {
        $this->app['eloquence.mutator']->macro('nullifyEmpty', function ($value) {
            if (is_array($value)) {
                return array_map([$this, 'nullifyEmpty'], $value);
            }

            return (strlen($value)) ? $value : null;
        });
    }

Btw. the above example can be used in a middleware to, as the name says, nullify empty input, so eg. you don't pass '' values when creating new db entries.

Example usage:

  • Above nullify empty middleware example

  • Basic call with pipe separated callables:

    $mutator = app('eloquence.mutator');
    
    $mutator->mutate($value = ' john doe ', $callables = ' trim | ucwords'); // 'John Doe'
  • Callables passed as array & with additional params

    function teaser($string, $length)
    {
        if (strlen($string) > $length-3) {
            $string = substr($string, 0, $length-3);
        }
    
        return $string . '...';
    }
    
    $lorem = 'lorem ipsum dolor sit amet, consectetur adipisicing elit. Earum perferendis explicabo laudantium eaque totam, ipsam delectus eveniet nostrum dolores reprehenderit doloremque facilis itaque tempora quod beatae numquam inventore temporibus sapiente.';
    
    $mutator->mutate($lorem, ['teaser:15', 'ucfirst']); // 'Lorem ipsum ...'
Clone this wiki locally