1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Drupal\graphql\GraphQL\Buffers; |
4
|
|
|
|
5
|
|
|
use Drupal\Core\Entity\EntityTypeManagerInterface; |
6
|
|
|
|
7
|
|
|
class EntityBuffer extends BufferBase { |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* The entity type manager service. |
11
|
|
|
* |
12
|
|
|
* @var \Drupal\Core\Entity\EntityTypeManagerInterface |
13
|
|
|
*/ |
14
|
|
|
protected $entityTypeManager; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* EntityBuffer constructor. |
18
|
|
|
* |
19
|
|
|
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager |
20
|
|
|
* The entity type manager service. |
21
|
|
|
*/ |
22
|
|
|
public function __construct(EntityTypeManagerInterface $entityTypeManager) { |
23
|
|
|
$this->entityTypeManager = $entityTypeManager; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* Add an item to the buffer. |
28
|
|
|
* |
29
|
|
|
* @param string $type |
30
|
|
|
* The entity type of the given entity ids. |
31
|
|
|
* @param array|int $id |
32
|
|
|
* The entity id(s) to load. |
33
|
|
|
* |
34
|
|
|
* @return \Closure |
35
|
|
|
* The callback to invoke to load the result for this buffer item. |
36
|
|
|
*/ |
37
|
|
|
public function add($type, $id) { |
38
|
|
|
$item = new \ArrayObject([ |
39
|
|
|
'type' => $type, |
40
|
|
|
'id' => $id, |
41
|
|
|
]); |
42
|
|
|
|
43
|
|
|
return $this->createBufferResolver($item); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* {@inheritdoc} |
48
|
|
|
*/ |
49
|
|
|
protected function getBufferId($item) { |
50
|
|
|
return $item['type']; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* {@inheritdoc} |
55
|
|
|
*/ |
56
|
|
|
public function resolveBufferArray(array $buffer) { |
57
|
|
|
$type = reset($buffer)['type']; |
58
|
|
|
$ids = array_map(function (\ArrayObject $item) { |
59
|
|
|
return (array) $item['id']; |
60
|
|
|
}, $buffer); |
61
|
|
|
|
62
|
|
|
$ids = call_user_func_array('array_merge', $ids); |
63
|
|
|
$ids = array_values(array_unique($ids)); |
64
|
|
|
|
65
|
|
|
// Load the buffered entities. |
66
|
|
|
$entities = $this->entityTypeManager |
67
|
|
|
->getStorage($type) |
68
|
|
|
->loadMultiple($ids); |
69
|
|
|
|
70
|
|
|
return array_map(function ($item) use ($entities) { |
71
|
|
|
if (is_array($item['id'])) { |
72
|
|
|
return array_intersect_key($entities, array_flip($item['id'])); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
return isset($entities[$item['id']]) ? $entities[$item['id']] : NULL; |
76
|
|
|
}, $buffer); |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
} |