Completed
Push — master ( 6dd7fd...f4371c )
by Eric
15:39 queued 08:32
created

Repository::createQueryBuilderForCollection()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 1
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
     * @param DocumentManager   $dm
37
     * @param UnitOfWork        $uow
38
     * @param ClassMetadata     $class
39
     * @param ResourceInterface $resource
40
     */
41 16
    public function __construct(
42
        DocumentManager $dm,
43
        UnitOfWork $uow,
44
        ClassMetadata $class,
45
        ResourceInterface $resource
46
    ) {
47 16
        parent::__construct($dm, $uow, $class);
48
49 16
        $this->resource = $resource;
50 16
    }
51
52
    /**
53
     * {@inheritdoc}
54
     */
55 1
    public function findForIndex(array $criteria, array $orderBy = [])
56
    {
57 1
        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 1
    public function findForShow(array $criteria, array $orderBy = [])
64
    {
65 1
        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 1
    public function findForUpdate(array $criteria, array $orderBy = [])
72
    {
73 1
        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 1
    public function findForDelete(array $criteria, array $orderBy = [])
80
    {
81 1
        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 6
    public function findOneBy(array $criteria, array $orderBy = [])
88
    {
89 6
        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 1 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 1
        $queryBuilder = $this->buildQueryBuilder($criteria, $orderBy);
98
99 1
        if ($limit !== null) {
100 1
            $queryBuilder->limit($limit);
101 1
        }
102
103 1
        if ($offset !== null) {
104 1
            $queryBuilder->skip($offset);
105 1
        }
106
107 1
        return $queryBuilder->getQuery()->getIterator()->toArray();
108
    }
109
110
    /**
111
     * {@inheritdoc}
112
     */
113 4
    public function createQueryBuilderForCollection()
114
    {
115 4
        return $this->createQueryBuilder();
116
    }
117
118
    /**
119
     * {@inheritdoc}
120
     */
121 1
    public function createDataSourceBuilder(array $options = [])
122
    {
123 1
        return new DataSourceBuilder($this, $options);
124
    }
125
126
    /**
127
     * {@inheritdoc}
128
     */
129 9
    public function getProperty($property, $root = null)
130
    {
131 9
        if (is_string($root) && !empty($root)) {
132 1
            return $root.'.'.$property;
133
        }
134
135 8
        return $property;
136
    }
137
138
    /**
139
     * @param mixed[]  $criteria
140
     * @param string[] $orderBy
141
     * @param bool     $collection
142
     *
143
     * @return Builder
144
     */
145 8 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 8
        $queryBuilder = $collection ? $this->createQueryBuilderForCollection() : $this->createQueryBuilder();
148
149 8
        $this->applyCriteria($queryBuilder, $criteria);
150 8
        $this->applySorting($queryBuilder, $orderBy);
151
152 8
        return $queryBuilder;
153
    }
154
155
    /**
156
     * @param Builder $queryBuilder
157
     * @param mixed[] $criteria
158
     */
159 8
    private function applyCriteria(Builder $queryBuilder, array $criteria = null)
160
    {
161 8
        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 8
            if ($value === null) {
163 1
                $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 8
            } elseif (is_array($value)) {
165 1
                $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 7
            } elseif ($value !== null) {
167 6
                $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 6
            }
169 8
        }
170 8
    }
171
172
    /**
173
     * @param Builder  $queryBuilder
174
     * @param string[] $orderBy
175
     */
176 8 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 8
        foreach ($orderBy as $property => $order) {
179 8
            if (!empty($order)) {
180 8
                $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 8
            }
182 8
        }
183 8
    }
184
}
185