Completed
Pull Request — master (#608)
by Amrouche
05:29 queued 02:26
created

ContextBuilder   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 116
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 0
Metric Value
wmc 13
lcom 1
cbo 8
dl 0
loc 116
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 1
A getBaseContext() 0 7 1
A getHalContext() 0 13 1
A getEntrypointContext() 0 17 2
C getResourceContext() 0 31 7
A getResourceContextUri() 0 6 1
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
namespace ApiPlatform\Core\Hypermedia;
13
14
use ApiPlatform\Core\Api\UrlGeneratorInterface;
15
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
16
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
17
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
18
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
19
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
20
21
/**
22
 * {@inheritdoc}
23
 *
24
 * @author Kévin Dunglas <[email protected]>
25
 */
26
final class ContextBuilder implements ContextBuilderInterface
27
{
28
    private $resourceNameCollectionFactory;
29
    private $resourceMetadataFactory;
30
    private $propertyNameCollectionFactory;
31
    private $propertyMetadataFactory;
32
    private $urlGenerator;
33
    private $docUri;
34
35
    /**
36
     * @var NameConverterInterface
37
     */
38
    private $nameConverter;
39
40
    public function __construct(ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, ResourceMetadataFactoryInterface $resourceMetadataFactory, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, UrlGeneratorInterface $urlGenerator, string $docUri = '', NameConverterInterface $nameConverter = null)
41
    {
42
        $this->resourceNameCollectionFactory = $resourceNameCollectionFactory;
43
        $this->resourceMetadataFactory = $resourceMetadataFactory;
44
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
45
        $this->propertyMetadataFactory = $propertyMetadataFactory;
46
        $this->urlGenerator = $urlGenerator;
47
        $this->nameConverter = $nameConverter;
48
        $this->docUri = $docUri;
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54
    public function getBaseContext(int $referenceType = UrlGeneratorInterface::ABS_URL) : array
55
    {
56
        return [
57
            '@vocab' => $this->urlGenerator->generate('api_hydra_doc', [], $referenceType).'#',
58
            'hydra' => self::HYDRA_NS,
59
        ];
60
    }
61
62
    /**
63
     * {@inheritdoc}
64
     */
65
    public function getHalContext(string $selfLink) : array
66
    {
67
        return [
68
            '_links' => ['self' => ['href' => $selfLink],
69
                 'curies' => [
70
                     ['name' => 'ap',
71
                      'href' => $this->urlGenerator->generate('api_hal_entrypoint').$this->docUri.'#section-{rel}',
72
                      'templated' => true,
73
                     ],
74
                 ],
75
                ],
76
        ];
77
    }
78
79
    /**
80
     * {@inheritdoc}
81
     */
82
    public function getEntrypointContext(int $referenceType = UrlGeneratorInterface::ABS_PATH) : array
83
    {
84
        $context = $this->getBaseContext($referenceType);
85
86
        foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) {
87
            $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
88
89
            $resourceName = lcfirst($resourceMetadata->getShortName());
90
91
            $context[$resourceName] = [
92
                '@id' => 'Entrypoint/'.$resourceName,
93
                '@type' => '@id',
94
            ];
95
        }
96
97
        return $context;
98
    }
99
100
    /**
101
     * {@inheritdoc}
102
     */
103
    public function getResourceContext(string $resourceClass, int $referenceType = UrlGeneratorInterface::ABS_PATH) : array
104
    {
105
        $context = $this->getBaseContext($referenceType, $referenceType);
0 ignored issues
show
Unused Code introduced by
The call to ContextBuilder::getBaseContext() has too many arguments starting with $referenceType.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
106
        $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
107
        $prefixedShortName = sprintf('#%s', $resourceMetadata->getShortName());
108
109
        foreach ($this->propertyNameCollectionFactory->create($resourceClass) as $propertyName) {
110
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName);
111
112
            if ($propertyMetadata->isIdentifier() && !$propertyMetadata->isWritable()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $propertyMetadata->isWritable() of type null|boolean is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
113
                continue;
114
            }
115
116
            $convertedName = $this->nameConverter ? $this->nameConverter->normalize($propertyName) : $propertyName;
117
118
            if (!$id = $propertyMetadata->getIri()) {
119
                $id = sprintf('%s/%s', $prefixedShortName, $convertedName);
120
            }
121
122
            if (!$propertyMetadata->isReadableLink()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $propertyMetadata->isReadableLink() of type null|boolean is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
123
                $context[$convertedName] = [
124
                    '@id' => $id,
125
                    '@type' => '@id',
126
                ];
127
            } else {
128
                $context[$convertedName] = $id;
129
            }
130
        }
131
132
        return $context;
133
    }
134
135
    public function getResourceContextUri(string $resourceClass, int $referenceType = UrlGeneratorInterface::ABS_PATH) : string
136
    {
137
        $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
138
139
        return $this->urlGenerator->generate('api_jsonld_context', ['shortName' => $resourceMetadata->getShortName()]);
140
    }
141
}
142