/** * Map through the collection and convert it to a collection * of ids * @param string $property * @param object $object * @param array $root * @param string $fullPropertyPath * @return mixed */ public function resolve($property, &$object, &$root, $fullPropertyPath) { if (is_array($object)) { // We need to determine if this is a singular relationship or // a collection of models $arrayCopy = $object; $firstElement = array_shift($arrayCopy); // The object was not a collection, and was rather a single // model, because the first item returned was a property // We therefore just return the single ID if (Utility::isPrimitive($firstElement)) { return (int) Utility::getProperty($object, 'id'); } return array_map(function ($entry) { return (int) Utility::getProperty($entry, 'id'); }, $object); } elseif ($object instanceof Collection) { return $object->map(function ($entry) { return (int) Utility::getProperty($entry, 'id'); }); // The relation is not a collection, but rather // a singular relation } elseif ($object instanceof Model) { return $object->id; } }
/** * Check if the resource already exists in the root collection by id * TODO: https://github.com/esbenp/laravel-controller/issues/2 * @param mixed $collection * @param mixed $resource */ private function addResourceToRootCollectionIfNonExistant(&$collection, $resource) { $identifier = Utility::getProperty($resource, 'id'); $exists = false; $copy = $collection instanceof Collection ? $collection->toArray() : $collection; foreach ($copy as $rootResource) { if ((int) Utility::getProperty($rootResource, 'id') === (int) $identifier) { $exists = true; break; } } if ($exists === false) { if (is_array($collection)) { $collection[] = $resource; } elseif ($collection instanceof Collection) { $collection->push($resource); } } }