-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathIdsModeResolver.php
49 lines (44 loc) · 1.63 KB
/
IdsModeResolver.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php
namespace Optimus\Architect\ModeResolver;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Optimus\Architect\ModeResolver\ModeResolverInterface;
use Optimus\Architect\Utility;
class IdsModeResolver implements ModeResolverInterface
{
/**
* 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;
}
}
}