graze / formatter
Convert objects into arrays of data by applying processors, filters, and sorters.
Installs: 23 224
Dependents: 0
Suggesters: 0
Security: 0
Stars: 6
Watchers: 13
Forks: 1
Open Issues: 0
Requires
- php: ^5.5 || ^5.6 || ^7.0
- graze/sort: ^2.0.1
Requires (Dev)
- graze/hamcrest-test-listener: ^1.0
- hamcrest/hamcrest-php: ^1.2
- phpunit/phpunit: ^4.8 || ^5.0
This package is auto-updated.
Last update: 2024-10-29 03:40:13 UTC
README
Convert objects into arrays of data by applying processors, filters, and sorters.
Read more about why we made this library in our blog post.
Installation
We recommend installing this library with Composer.
~$ composer require graze/formatter
Usage
// 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);
The above example will output:
Array
(
[count] => 1
[square] => 1
)
Array
(
[0] => Array
(
[count] => 4
[square] => 16
)
[1] => Array
(
[count] => 2
[square] => 4
)
)
Find more documentation under docs/
.