1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Drupal\graphql\GraphQL\Batching\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
|
|
|
* The results are ordered in the same way as the given publications. |
30
|
|
|
* |
31
|
|
|
* @param string $type |
32
|
|
|
* The entity type of the given entity ids. |
33
|
|
|
* @param array|int $id |
34
|
|
|
* The entity id(s) to load. |
35
|
|
|
* |
36
|
|
|
* @return \Closure |
37
|
|
|
* The callback to invoke to load the result for this buffer item. |
38
|
|
|
*/ |
39
|
|
|
public function add($type, $id) { |
40
|
|
|
$item = new \ArrayObject([ |
41
|
|
|
'type' => $type, |
42
|
|
|
'id' => $id, |
43
|
|
|
]); |
44
|
|
|
|
45
|
|
|
return $this->createBufferResolver($item); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* {@inheritdoc} |
50
|
|
|
*/ |
51
|
|
|
protected function getBufferId($item) { |
52
|
|
|
return $item['type']; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* {@inheritdoc} |
57
|
|
|
*/ |
58
|
|
|
public function resolveBufferArray(array $buffer) { |
59
|
|
|
$type = reset($buffer)['type']; |
60
|
|
|
$ids = array_map(function (\ArrayObject $item) { |
61
|
|
|
return (array) $item['id']; |
62
|
|
|
}, $buffer); |
63
|
|
|
|
64
|
|
|
$ids = call_user_func_array('array_merge', $ids); |
65
|
|
|
$ids = array_values(array_unique($ids)); |
66
|
|
|
|
67
|
|
|
// Load the buffered entities. |
68
|
|
|
$entities = $this->entityTypeManager |
69
|
|
|
->getStorage($type) |
70
|
|
|
->loadMultiple($ids); |
71
|
|
|
|
72
|
|
|
return array_map(function ($item) use ($entities) { |
73
|
|
|
if (is_array($item['id'])) { |
74
|
|
|
return array_intersect_key($entities, array_flip($item['id'])); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
return isset($entities[$item['id']]) ? $entities[$item['id']] : NULL; |
78
|
|
|
}, $buffer); |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
} |