EntityBuffer.php in GraphQL 8.3
File
src/GraphQL/Buffers/EntityBuffer.php
View source
<?php
namespace Drupal\graphql\GraphQL\Buffers;
use Drupal\Core\Entity\EntityTypeManagerInterface;
class EntityBuffer extends BufferBase {
protected $entityTypeManager;
public function __construct(EntityTypeManagerInterface $entityTypeManager) {
$this->entityTypeManager = $entityTypeManager;
}
public function add($type, $id) {
$item = new \ArrayObject([
'type' => $type,
'id' => $id,
]);
return $this
->createBufferResolver($item);
}
protected function getBufferId($item) {
return $item['type'];
}
public function resolveBufferArray(array $buffer) {
$type = reset($buffer)['type'];
$ids = array_map(function (\ArrayObject $item) {
return (array) $item['id'];
}, $buffer);
$ids = call_user_func_array('array_merge', $ids);
$ids = array_values(array_unique($ids));
$entities = $this->entityTypeManager
->getStorage($type)
->loadMultiple($ids);
return array_map(function ($item) use ($entities) {
if (is_array($item['id'])) {
return array_reduce($item['id'], function ($carry, $current) use ($entities) {
if (!empty($entities[$current])) {
return $carry + [
$current => $entities[$current],
];
}
return $carry;
}, []);
}
return isset($entities[$item['id']]) ? $entities[$item['id']] : NULL;
}, $buffer);
}
}