Completed
Push — master ( c34cac...3c68a7 )
by Pieter
04:47
created

ApiResourceMetadataFactory   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 18
c 0
b 0
f 0
dl 0
loc 39
rs 10
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getMetadata() 0 21 4
A __construct() 0 4 1
1
<?php
2
3
namespace W2w\Lib\Apie\Core;
4
5
use Doctrine\Common\Annotations\Reader;
6
use ReflectionClass;
7
use W2w\Lib\Apie\Annotations\ApiResource;
8
use W2w\Lib\Apie\Core\Models\ApiResourceClassMetadata;
9
use W2w\Lib\Apie\Exceptions\ApiResourceAnnotationNotFoundException;
10
use W2w\Lib\Apie\Interfaces\ApiResourceFactoryInterface;
11
12
/**
13
 * Creates Api Resource metadata using annotations on the class.
14
 */
15
class ApiResourceMetadataFactory
16
{
17
    /**
18
     * @var Reader
19
     */
20
    private $reader;
21
22
    /**
23
     * @var ApiResourceFactoryInterface
24
     */
25
    private $retrieverFactory;
26
27
    public function __construct(Reader $reader, ApiResourceFactoryInterface $retrieverFactory)
28
    {
29
        $this->reader = $reader;
30
        $this->retrieverFactory = $retrieverFactory;
31
    }
32
33
    public function getMetadata($classNameOrInstance): ApiResourceClassMetadata
34
    {
35
        $reflClass = new ReflectionClass($classNameOrInstance);
36
        $annotation = $this->reader->getClassAnnotation(
37
            $reflClass,
38
            ApiResource::class
39
        );
40
        if (!$annotation) {
41
            throw new ApiResourceAnnotationNotFoundException($classNameOrInstance);
42
        }
43
        /** @var ApiResource $annotation */
44
        $retriever = null;
45
        $persister = null;
46
        if ($annotation->retrieveClass) {
47
            $retriever = $this->retrieverFactory->getApiResourceRetrieverInstance($annotation->retrieveClass);
48
        }
49
        if ($annotation->persistClass) {
50
            $persister = $this->retrieverFactory->getApiResourcePersisterInstance($annotation->persistClass);
51
        }
52
53
        return new ApiResourceClassMetadata($classNameOrInstance, $annotation, $retriever, $persister);
54
    }
55
}
56