Completed
Pull Request — 8.x-3.x (#478)
by Sebastian
05:04
created

EntityBuffer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
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
}