/
ItemDataProvider.php
88 lines (75 loc) · 2.79 KB
/
ItemDataProvider.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace ApiPlatform\Core\Bridge\Elasticsearch\DataProvider;
use ApiPlatform\Core\Bridge\Elasticsearch\Exception\IndexNotFoundException;
use ApiPlatform\Core\Bridge\Elasticsearch\Metadata\Document\Factory\DocumentMetadataFactoryInterface;
use ApiPlatform\Core\Bridge\Elasticsearch\Serializer\ItemNormalizer;
use ApiPlatform\Core\DataProvider\ItemDataProviderInterface;
use ApiPlatform\Core\DataProvider\RestrictedDataProviderInterface;
use ApiPlatform\Core\Exception\InvalidArgumentException;
use Elasticsearch\Client;
use Elasticsearch\Common\Exceptions\Missing404Exception;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
/**
* Item data provider for Elasticsearch.
*
* @experimental
*
* @author Baptiste Meyer <baptiste.meyer@gmail.com>
*/
final class ItemDataProvider implements ItemDataProviderInterface, RestrictedDataProviderInterface
{
private $client;
private $documentMetadataFactory;
private $denormalizer;
public function __construct(Client $client, DocumentMetadataFactoryInterface $documentMetadataFactory, DenormalizerInterface $denormalizer)
{
$this->client = $client;
$this->documentMetadataFactory = $documentMetadataFactory;
$this->denormalizer = $denormalizer;
}
/**
* {@inheritdoc}
*/
public function supports(string $resourceClass, ?string $operationName = null, array $context = []): bool
{
try {
$this->documentMetadataFactory->create($resourceClass);
} catch (IndexNotFoundException $e) {
return false;
}
return true;
}
/**
* {@inheritdoc}
*/
public function getItem(string $resourceClass, $id, ?string $operationName = null, array $context = [])
{
if (\is_array($id)) {
if (1 !== \count($id)) {
throw new InvalidArgumentException('Composite identifiers not supported.');
}
$id = reset($id);
}
$documentMetadata = $this->documentMetadataFactory->create($resourceClass);
try {
$document = $this->client->get([
'index' => $documentMetadata->getIndex(),
'type' => $documentMetadata->getType(),
'id' => (string) $id,
]);
} catch (Missing404Exception $e) {
return null;
}
return $this->denormalizer->denormalize($document, $resourceClass, ItemNormalizer::FORMAT, [AbstractNormalizer::ALLOW_EXTRA_ATTRIBUTES => true]);
}
}