PHP code example of graze / formatter

1. Go to this page and download the library: Download graze/formatter library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

graze / formatter example snippets


// Create a formatter ...
class CountableFormatter extends \Graze\Formatter\AbstractFormatter
{
    protected function convert($object)
    {
        if (! $object instanceof Countable) {
            throw new \InvalidArgumentException(sprintf('`$object` must be an instance of %s.', Countable::class));
        }

        return [
            'count' => $object->count(),
        ];
    }
}

// ... processor ...
$processor = function (array $data, Countable $object) {
    // Let's add the square of count.
    $data['square'] = $data['count'] ** 2;

    return $data;
};

// ... filter ...
$filter = function (array $data) {
    // Remove elements with a square of 9.
    return $data['square'] !== 9;
};

// ... sorter ...
$sorter = function (array $data) {
    // Sort by count in descending order.
    return $data['count'] * -1;
};

// ... and something we can format.
class ExampleCountable implements Countable
{
    private $count = 0;

    public function count()
    {
        return $this->count += 1;
    }
}

$countable = new ExampleCountable();

// Create a new instance of the formatter, and register all the callables.
$formatter = new CountableFormatter();
$formatter->addProcessor($processor);
$formatter->addFilter($filter);
$formatter->addSorter($sorter);

// Format a single object.
$result = $formatter->format($countable);

print_r($result);

// Format several objects.
$result = $formatter->formatMany([$countable, $countable, $countable]);

print_r($result);