Completed
Push — master ( 209945...41a4bc )
by Matthew
07:41 queued 03:34
created

DocumentGridSource::remove()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 9
nc 2
nop 4
dl 0
loc 15
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Dtc\GridBundle\Grid\Source;
4
5
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
6
use Doctrine\ODM\MongoDB\DocumentManager;
7
use Dtc\GridBundle\Grid\Column\GridColumn;
8
9
class DocumentGridSource extends AbstractGridSource
10
{
11
    use ColumnExtractionTrait;
12
13
    protected $documentManager;
14
    protected $repository;
15
    protected $findCache;
16
    protected $documentName;
17
18
    public function __construct(DocumentManager $documentManager, $documentName)
19
    {
20
        $this->documentManager = $documentManager;
21
        $this->repository = $documentManager->getRepository($documentName);
22
        $this->documentName = $documentName;
23
    }
24
25
    /**
26
     * @return \Doctrine\ODM\MongoDB\Query\Builder
27
     */
28
    protected function getQueryBuilder()
29
    {
30
        $qb = $this->documentManager->createQueryBuilder($this->documentName);
31
32
        /** @var ClassMetadata $classMetaData */
33
        $classMetaData = $this->getClassMetadata();
34
        $classFields = $classMetaData->fieldMappings;
35
36
        $columns = $this->getColumns();
37
        $fieldList = [];
38 View Code Duplication
        foreach ($columns as $column) {
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...
39
            if ($column instanceof GridColumn && $column->isSearchable()) {
40
                $fieldList[$column->getField()] = true;
41
            }
42
        }
43
        if ($this->filter) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->filter of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
44
            $validFilters = array_intersect_key($this->filter, $classFields);
45
46
            $query = array();
47
            foreach ($validFilters as $key => $value) {
48
                if (isset($fieldList[$key])) {
49
                    if (is_array($value)) {
50
                        $qb->field($key)->in($value);
51
                    } else {
52
                        $qb->field($key)->equals($value);
53
                    }
54
                }
55
            }
56
            if (!$query) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $query of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
57
                $starFilter = array_intersect_key($this->filter, ['*' => null]);
58
                if ($starFilter) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $starFilter of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
59
                    $value = current($starFilter);
60
                    foreach ($classFields as $key => $info) {
61
                        if (isset($fieldList[$key])) {
62
                            $expr = $qb->expr()->field($key);
63
                            switch ($info['type']) {
64
                                case 'integer':
65
                                    $expr = $expr->equals(intval($value));
66
                                    break;
67
                                default:
68
                                    $expr = $expr->equals($value);
69
                            }
70
                            $qb->addOr($expr);
71
                        }
72
                        // @TODO - maybe allow pattern searches some day: new \MongoRegex('/.*'.$value.'.*/')
73
                    }
74
                }
75
            }
76
        }
77
        if ($this->orderBy) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->orderBy of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
78
            foreach ($this->orderBy as $key => $direction) {
79
                $qb->sort($key, $direction);
80
            }
81
        }
82
83
        $qb->limit($this->limit);
84
        $qb->skip($this->offset);
85
86
        return $qb;
87
    }
88
89
    /**
90
     * @return mixed
91
     */
92
    public function getClassMetadata()
93
    {
94
        $metaFactory = $this->documentManager->getMetadataFactory();
95
        $classInfo = $metaFactory->getMetadataFor($this->documentName);
96
97
        return $classInfo;
98
    }
99
100
    public function getCount()
101
    {
102
        $result = $this->getQueryBuilder()->limit(0)->skip(0)->count()->getQuery()->execute();
103
104
        return $result;
105
    }
106
107
    public function getRecords()
108
    {
109
        return $this->getQueryBuilder()->getQuery()->execute()->toArray(false);
0 ignored issues
show
Unused Code introduced by
The call to Doctrine\MongoDB\EagerCursor::toArray() has too many arguments starting with false. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

109
        return /** @scrutinizer ignore-call */ $this->getQueryBuilder()->getQuery()->execute()->toArray(false);

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. Please note the @ignore annotation hint above.

Loading history...
110
    }
111
112
    public function find($id)
113
    {
114
        if (!$this->hasIdColumn()) {
115
            throw new \Exception('No id column found for '.$this->documentName);
116
        }
117
        $qb = $this->documentManager->createQueryBuilder($this->documentName);
118
        $idColumn = $this->getIdColumn();
119
        $qb->field($idColumn)->equals($id);
120
        $result = $qb->getQuery()->execute()->toArray(false);
0 ignored issues
show
Unused Code introduced by
The call to Doctrine\MongoDB\EagerCursor::toArray() has too many arguments starting with false. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

120
        $result = /** @scrutinizer ignore-call */ $qb->getQuery()->execute()->toArray(false);

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. Please note the @ignore annotation hint above.

Loading history...
121
        if (isset($result[0])) {
122
            return $result[0];
123
        }
124
    }
125
126
    public function remove($id, $soft = false, $softColumn = 'deletedAt', $softColumnType = 'datetime')
127
    {
128
        if (!$this->hasIdColumn()) {
129
            throw new \Exception('No id column found for '.$this->documentName);
130
        }
131
        $repository = $this->documentManager->getRepository($this->documentName);
132
        $document = $repository->find($id);
133
        if ($document) {
134
            $this->documentManager->remove($document);
135
            $this->documentManager->flush();
136
137
            return true;
138
        }
139
140
        return false;
141
    }
142
}
143