Completed
Pull Request — master (#62)
by Eric
34:08
created

Repository::getProperty()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 8
ccs 0
cts 0
cp 0
rs 9.4285
cc 3
eloc 4
nc 2
nop 2
crap 12
1
<?php
2
3
/*
4
 * This file is part of the Lug package.
5
 *
6
 * (c) Eric GELOEN <[email protected]>
7
 *
8
 * For the full copyright and license information, please read the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Lug\Component\Resource\Repository\Doctrine\MongoDB;
13
14
use Doctrine\ODM\MongoDB\DocumentManager;
15
use Doctrine\ODM\MongoDB\DocumentRepository;
16
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
17
use Doctrine\ODM\MongoDB\Query\Builder;
18
use Doctrine\ODM\MongoDB\UnitOfWork;
19
use Lug\Component\Grid\DataSource\Doctrine\MongoDB\DataSourceBuilder;
20
use Lug\Component\Resource\Model\ResourceInterface;
21
use Lug\Component\Resource\Repository\RepositoryInterface;
22
use Pagerfanta\Adapter\DoctrineODMMongoDBAdapter;
23
use Pagerfanta\Pagerfanta;
24
25
/**
26
 * @author GeLo <[email protected]>
27
 */
28
class Repository extends DocumentRepository implements RepositoryInterface
29
{
30
    /**
31
     * @var ResourceInterface
32
     */
33
    private $resource;
34
35
    /**
36 16
     * @param DocumentManager   $dm
37
     * @param UnitOfWork        $uow
38
     * @param ClassMetadata     $class
39
     * @param ResourceInterface $resource
40
     */
41
    public function __construct(
42 16
        DocumentManager $dm,
43 16
        UnitOfWork $uow,
44
        ClassMetadata $class,
45
        ResourceInterface $resource
46
    ) {
47
        parent::__construct($dm, $uow, $class);
48
49
        $this->resource = $resource;
50
    }
51
52
    /**
53
     * {@inheritdoc}
54
     */
55
    public function findForIndex(array $criteria, array $orderBy = [])
56
    {
57
        return new Pagerfanta(new DoctrineODMMongoDBAdapter($this->buildQueryBuilder($criteria, $orderBy, true)));
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \Pagerfanta\P...ria, $orderBy, true))); (Pagerfanta\Pagerfanta) is incompatible with the return type declared by the interface Lug\Component\Resource\R...Interface::findForIndex of type object[].

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
58
    }
59
60
    /**
61
     * {@inheritdoc}
62
     */
63
    public function findForShow(array $criteria, array $orderBy = [])
64
    {
65
        return $this->findOneBy($criteria, $orderBy);
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->findOneBy($criteria, $orderBy); of type array|object|null adds the type array to the return on line 65 which is incompatible with the return type declared by the interface Lug\Component\Resource\R...yInterface::findForShow of type object|null.
Loading history...
66
    }
67
68
    /**
69
     * {@inheritdoc}
70
     */
71
    public function findForUpdate(array $criteria, array $orderBy = [])
72
    {
73
        return $this->findOneBy($criteria, $orderBy);
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->findOneBy($criteria, $orderBy); of type array|object|null adds the type array to the return on line 73 which is incompatible with the return type declared by the interface Lug\Component\Resource\R...nterface::findForUpdate of type object|null.
Loading history...
74
    }
75
76
    /**
77
     * {@inheritdoc}
78
     */
79
    public function findForDelete(array $criteria, array $orderBy = [])
80
    {
81
        return $this->findOneBy($criteria, $orderBy);
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->findOneBy($criteria, $orderBy); of type array|object|null adds the type array to the return on line 81 which is incompatible with the return type declared by the interface Lug\Component\Resource\R...nterface::findForDelete of type object|null.
Loading history...
82
    }
83
84
    /**
85
     * {@inheritdoc}
86
     */
87
    public function findOneBy(array $criteria, array $orderBy = [])
88
    {
89
        return $this->buildQueryBuilder($criteria, $orderBy)->getQuery()->getSingleResult();
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->buildQueryBuilder...y()->getSingleResult(); of type array|object|null adds the type array to the return on line 89 which is incompatible with the return type declared by the interface Doctrine\Common\Persiste...ctRepository::findOneBy of type object.
Loading history...
90
    }
91
92
    /**
93
     * {@inheritdoc}
94
     */
95 View Code Duplication
    public function findBy(array $criteria, array $orderBy = [], $limit = null, $offset = 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...
96
    {
97
        $queryBuilder = $this->buildQueryBuilder($criteria, $orderBy);
98
99
        if ($limit !== null) {
100
            $queryBuilder->limit($limit);
101
        }
102
103
        if ($offset !== null) {
104
            $queryBuilder->skip($offset);
105
        }
106
107
        return $queryBuilder->getQuery()->getIterator()->toArray();
108
    }
109
110
    /**
111
     * {@inheritdoc}
112
     */
113
    public function createQueryBuilderForCollection()
114
    {
115
        return $this->createQueryBuilder();
116
    }
117
118
    /**
119
     * {@inheritdoc}
120
     */
121
    public function createDataSourceBuilder(array $options = [])
122
    {
123
        return new DataSourceBuilder($this, $options);
124
    }
125
126
    /**
127
     * {@inheritdoc}
128
     */
129
    public function getProperty($property, $root = null)
130
    {
131
        if (is_string($root) && !empty($root)) {
132
            return $root.'.'.$property;
133
        }
134
135
        return $property;
136
    }
137
138
    /**
139
     * @param mixed[]  $criteria
140
     * @param string[] $orderBy
141
     * @param bool     $collection
142
     *
143
     * @return Builder
144
     */
145 View Code Duplication
    protected function buildQueryBuilder(array $criteria, array $orderBy, $collection = false)
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...
146
    {
147
        $queryBuilder = $collection ? $this->createQueryBuilderForCollection() : $this->createQueryBuilder();
148
149
        $this->applyCriteria($queryBuilder, $criteria);
150
        $this->applySorting($queryBuilder, $orderBy);
151
152
        return $queryBuilder;
153
    }
154
155
    /**
156
     * @param Builder $queryBuilder
157
     * @param mixed[] $criteria
158
     */
159
    private function applyCriteria(Builder $queryBuilder, array $criteria = null)
160
    {
161
        foreach ($criteria as $property => $value) {
0 ignored issues
show
Bug introduced by
The expression $criteria of type null|array<integer,*> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
162
            if ($value === null) {
163
                $queryBuilder->field($this->getProperty($property, $queryBuilder))->equals(null);
0 ignored issues
show
Documentation introduced by
$queryBuilder is of type object<Doctrine\ODM\MongoDB\Query\Builder>, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
164
            } elseif (is_array($value)) {
165
                $queryBuilder->field($this->getProperty($property, $queryBuilder))->in($value);
0 ignored issues
show
Documentation introduced by
$queryBuilder is of type object<Doctrine\ODM\MongoDB\Query\Builder>, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
166
            } elseif ($value !== null) {
167
                $queryBuilder->field($this->getProperty($property, $queryBuilder))->equals($value);
0 ignored issues
show
Documentation introduced by
$queryBuilder is of type object<Doctrine\ODM\MongoDB\Query\Builder>, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
168
            }
169
        }
170
    }
171
172
    /**
173
     * @param Builder  $queryBuilder
174
     * @param string[] $orderBy
175
     */
176 View Code Duplication
    private function applySorting(Builder $queryBuilder, array $orderBy = [])
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...
177
    {
178
        foreach ($orderBy as $property => $order) {
179
            if (!empty($order)) {
180
                $queryBuilder->sort($this->getProperty($property, $queryBuilder), $order);
0 ignored issues
show
Documentation introduced by
$queryBuilder is of type object<Doctrine\ODM\MongoDB\Query\Builder>, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
181
            }
182
        }
183
    }
184
}
185