Completed
Pull Request — master (#461)
by Sam
04:05 queued 13s
created

ItemDataProvider::getItem()   C

Complexity

Conditions 12
Paths 35

Size

Total Lines 56
Code Lines 30

Duplication

Lines 15
Ratio 26.79 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 15
loc 56
rs 6.7092
cc 12
eloc 30
nc 35
nop 4

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Bridge\Doctrine\MongoDB;
13
14
use ApiPlatform\Core\Api\ItemDataProviderInterface;
15
use ApiPlatform\Core\Exception\InvalidArgumentException;
16
use ApiPlatform\Core\Exception\ResourceClassNotSupportedException;
17
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
18
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
19
use Doctrine\Common\Persistence\ManagerRegistry;
20
use Doctrine\ODM\MongoDB\DocumentManager;
21
use Doctrine\ODM\MongoDB\DocumentRepository;
22
use ApiPlatform\Core\Bridge\Doctrine\MongoDB\Extension\QueryItemExtensionInterface;
23
24
/**
25
 * Item data provider for the Doctrine MongoDB ODM.
26
 */
27
class ItemDataProvider implements ItemDataProviderInterface
28
{
29
    private $managerRegistry;
30
    private $propertyNameCollectionFactory;
31
    private $propertyMetadataFactory;
32
    private $itemExtensions;
33
    private $decorated;
34
35
    /**
36
     * @param ManagerRegistry                        $managerRegistry
37
     * @param PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory
38
     * @param PropertyMetadataFactoryInterface       $propertyMetadataFactory
39
     * @param QueryItemExtensionInterface[]          $itemExtensions
40
     * @param ItemDataProviderInterface|null         $decorated
41
     */
42 View Code Duplication
    public function __construct(ManagerRegistry $managerRegistry, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, array $itemExtensions = [], ItemDataProviderInterface $decorated = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
43
    {
44
        $this->managerRegistry = $managerRegistry;
45
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
46
        $this->propertyMetadataFactory = $propertyMetadataFactory;
47
        $this->itemExtensions = $itemExtensions;
48
        $this->decorated = $decorated;
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54
    public function getItem(string $resourceClass, $id, string $operationName = null, bool $fetchData = false)
55
    {
56
        if ($this->decorated) {
57
            try {
58
                return $this->decorated->getItem($resourceClass, $id, $operationName, $fetchData);
59
            } catch (ResourceClassNotSupportedException $resourceClassNotSupportedException) {
60
                // Ignore it
61
            }
62
        }
63
64
        $manager = $this->managerRegistry->getManagerForClass($resourceClass);
65
        if (null === $manager) {
66
            throw new ResourceClassNotSupportedException();
67
        }
68
69
        $identifierValues = explode('-', $id);
70
        $identifiers = [];
71
        $i = 0;
72
73 View Code Duplication
        foreach ($this->propertyNameCollectionFactory->create($resourceClass) as $propertyName) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
74
            $itemMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName);
75
76
            $identifier = $itemMetadata->isIdentifier();
77
            if (null === $identifier || false === $identifier) {
78
                continue;
79
            }
80
81
            if (!isset($identifierValues[$i])) {
82
                throw new InvalidArgumentException(sprintf('Invalid identifier "%s".', $id));
83
            }
84
85
            $identifiers[$propertyName] = $identifierValues[$i];
86
            ++$i;
87
        }
88
89
        if (!$fetchData || $manager instanceof DocumentManager) {
0 ignored issues
show
Bug introduced by
The class Doctrine\ODM\MongoDB\DocumentManager does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
90
            return $manager->getReference($resourceClass, reset($identifiers));
91
        }
92
93
        /** @var DocumentRepository $repository */
94
        $repository = $manager->getRepository($resourceClass);
95
        $queryBuilder = $repository->createQueryBuilder();
96
97
        foreach ($identifiers as $propertyName => $value) {
98
99
            $queryBuilder
100
                ->field($propertyName)->equals($value)
101
            ;
102
        }
103
104
        foreach ($this->itemExtensions as $extension) {
105
            $extension->applyToItem($queryBuilder, $resourceClass, $identifiers, $operationName);
106
        }
107
108
        return $queryBuilder->getQuery()->getSingleResult();
109
    }
110
}
111