| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Metricool\Traits; |
| 6 |
|
| 7 |
use Metricool\Support\Helpers\Collection; |
| 8 |
|
| 9 |
/** |
| 10 |
* Trait to hydrate results from an Entity into an array of object |
| 11 |
* {@see \Metricool\Http\Metricool\Entities\TimelineStatistics} |
| 12 |
*/ |
| 13 |
trait IsHydratable |
| 14 |
{ |
| 15 |
/** |
| 16 |
* Hydrate raw data into objects. |
| 17 |
* Use this trait on any Entity that pulls data from an API to hydrate the |
| 18 |
* results into objects. |
| 19 |
*/ |
| 20 |
public function hydrateResults(array $results): Collection |
| 21 |
{ |
| 22 |
$hydrated = []; |
| 23 |
foreach ($results as $key => $item) { |
| 24 |
$hydrated[] = $this->hydrateItem($key, $item); |
| 25 |
} |
| 26 |
return new Collection($hydrated); |
| 27 |
} |
| 28 |
|
| 29 |
/** |
| 30 |
* Hydrate a single item - override in classes using this trait |
| 31 |
* Should return the object that represents the result |
| 32 |
* @param mixed $key The key of the item in the raw array |
| 33 |
* @param mixed $item The item to be hydrated into an object |
| 34 |
*/ |
| 35 |
abstract protected function hydrateItem($key, $item); |
| 36 |
} |
| 37 |
|