/
ResourceClassResolver.php
76 lines (64 loc) · 2.26 KB
/
ResourceClassResolver.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
<?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.
*/
namespace ApiPlatform\Core\Api;
use ApiPlatform\Core\DataProvider\PaginatorInterface;
use ApiPlatform\Core\Exception\InvalidArgumentException;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
use ApiPlatform\Core\Util\ClassInfoTrait;
/**
* {@inheritdoc}
*
* @author Kévin Dunglas <dunglas@gmail.com>
* @author Samuel ROZE <samuel.roze@gmail.com>
*/
final class ResourceClassResolver implements ResourceClassResolverInterface
{
use ClassInfoTrait;
private $resourceNameCollectionFactory;
public function __construct(ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory)
{
$this->resourceNameCollectionFactory = $resourceNameCollectionFactory;
}
/**
* {@inheritdoc}
*/
public function getResourceClass($value, string $resourceClass = null, bool $strict = false) : string
{
if (is_object($value) && !$value instanceof PaginatorInterface) {
$typeToFind = $type = $this->getObjectClass($value);
if (null === $resourceClass) {
$resourceClass = $typeToFind;
}
} elseif (null === $resourceClass) {
throw new InvalidArgumentException(sprintf('No resource class found.'));
} else {
$typeToFind = $type = $resourceClass;
}
if (($strict && isset($type) && $resourceClass !== $type) || !$this->isResourceClass($typeToFind)) {
if (is_subclass_of($type, $resourceClass) && $this->isResourceClass($resourceClass)) {
return $type;
}
throw new InvalidArgumentException(sprintf('No resource class found for object of type "%s"', $typeToFind));
}
return $resourceClass;
}
/**
* {@inheritdoc}
*/
public function isResourceClass(string $type) : bool
{
foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) {
if ($type === $resourceClass) {
return true;
}
}
return false;
}
}