Passed
Pull Request — master (#2934)
by Han Hui
08:24 queued 03:57
created

ResourceClassInfoTrait::isResourceClass()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 9
nc 4
nop 1
dl 0
loc 18
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace ApiPlatform\Core\Util;
15
16
use ApiPlatform\Core\Api\ResourceClassResolverInterface;
17
use ApiPlatform\Core\Exception\ResourceClassNotFoundException;
18
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
19
20
/**
21
 * Retrieves information about a resource class.
22
 *
23
 * @internal
24
 */
25
trait ResourceClassInfoTrait
26
{
27
    use ClassInfoTrait;
28
29
    /**
30
     * @var ResourceClassResolverInterface|null
31
     */
32
    private $resourceClassResolver;
33
34
    /**
35
     * @var ResourceMetadataFactoryInterface|null
36
     */
37
    private $resourceMetadataFactory;
38
39
    /**
40
     * Gets the resource class of the given object.
41
     *
42
     * @param object $object
43
     * @param bool   $strict If true, object class is expected to be a resource class
44
     *
45
     * @return string|null The resource class, or null if object class is not a resource class
46
     */
47
    private function getResourceClass($object, bool $strict = false): ?string
48
    {
49
        $objectClass = $this->getObjectClass($object);
50
51
        if (null === $this->resourceClassResolver) {
52
            return $objectClass;
53
        }
54
55
        if (!$strict && !$this->resourceClassResolver->isResourceClass($objectClass)) {
56
            return null;
57
        }
58
59
        return $this->resourceClassResolver->getResourceClass($object);
60
    }
61
62
    private function isResourceClass(string $class): bool
63
    {
64
        if ($this->resourceClassResolver instanceof ResourceClassResolverInterface) {
65
            return $this->resourceClassResolver->isResourceClass($class);
66
        }
67
68
        if (!$this->resourceMetadataFactory instanceof ResourceMetadataFactoryInterface) {
69
            // assume that it's a resource class
70
            return true;
71
        }
72
73
        try {
74
            $this->resourceMetadataFactory->create($class);
75
        } catch (ResourceClassNotFoundException $e) {
76
            return false;
77
        }
78
79
        return true;
80
    }
81
}
82