CustomEntityRepository::addSortOrder()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 7
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
3
namespace Pim\Bundle\CustomEntityBundle\Entity\Repository;
4
5
use Doctrine\Common\Collections\ArrayCollection;
6
use Doctrine\ORM\QueryBuilder;
7
use Pim\Bundle\ReferenceDataBundle\Doctrine\ORM\Repository\ReferenceDataRepository;
8
9
/**
10
 * Repository for the custom entity
11
 *
12
 * @author    Antoine Guigan <[email protected]>
13
 * @copyright 2013 Akeneo SAS (http://www.akeneo.com)
14
 * @license   http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
15
 */
16
class CustomEntityRepository extends ReferenceDataRepository
17
{
18
    /**
19
     * Create a query builder used for the datagrid
20
     *
21
     * @return QueryBuilder
22
     */
23
    public function createDatagridQueryBuilder()
24
    {
25
        return $this->createQueryBuilder(
26
            $this->getAlias()
27
        );
28
    }
29
30
    /**
31
     * Applies mass action parameters on the query builder
32
     *
33
     * @param QueryBuilder $qb
34
     * @param bool         $inset
35
     * @param array        $values
36
     */
37
    public function applyMassActionParameters($qb, $inset, $values)
38
    {
39
        if (!empty($values)) {
40
            $valueWhereCondition =
41
                $inset
42
                    ? $qb->expr()->in($this->getAlias(), $values)
43
                    : $qb->expr()->notIn($this->getAlias(), $values);
44
            $qb->andWhere($valueWhereCondition);
45
        }
46
47
        if (null !== $qb->getDQLPart('where')) {
48
            $whereParts = $qb->getDQLPart('where')->getParts();
49
            $qb->resetDQLPart('where');
50
51
            foreach ($whereParts as $part) {
52
                if (!is_string($part) || !strpos($part, 'entityIds')) {
53
                    $qb->andWhere($part);
54
                }
55
            }
56
        }
57
58
        $qb->setParameters(
59
            $qb->getParameters()->filter(
60
                function ($parameter) {
61
                    return $parameter->getName() !== 'entityIds';
62
                }
63
            )
64
        );
65
66
        // remove limit of the query
67
        $qb->setMaxResults(null);
68
    }
69
70
    /**
71
     * Used to mass delete reference datas from their ids
72
     *
73
     * @param int[] $ids
74
     *
75
     * @return int
76
     * @throws \LogicException
77
     */
78
    public function deleteFromIds(array $ids)
79
    {
80
        if (empty($ids)) {
81
            throw new \LogicException('Nothing to remove');
82
        }
83
84
        $qb = $this->_em->createQueryBuilder();
85
        $qb
86
            ->delete($this->getEntityName(), $this->getAlias())
87
            ->where(
88
                $qb->expr()->in(
89
                    sprintf('%s.id', $this->getAlias()),
90
                    $ids
91
                )
92
            );
93
94
        return $qb->getQuery()->execute();
95
    }
96
97
    /**
98
     * Hydrates reference data from ids for quick export or mass edit features
99
     *
100
     * @param array $referenceDataIds
101
     *
102
     * @return ArrayCollection
103
     *
104
     * @throws \InvalidArgumentException array of ids should not be empty
105
     */
106
    public function findByIds(array $referenceDataIds)
107
    {
108
        if (empty($referenceDataIds)) {
109
            throw new \InvalidArgumentException('Array must contain at least one reference data id');
110
        }
111
112
        $qb = $this->createQueryBuilder($this->getAlias());
113
        $qb->where(
114
            $qb->expr()->in(
115
                sprintf('%s.id', $this->getAlias()),
116
                $referenceDataIds
117
            )
118
        );
119
120
        return new ArrayCollection($qb->getQuery()->getResult());
121
    }
122
123
    /**
124
     * {@inheritdoc}
125
     */
126
    public function findBySearch($search = null, array $options = [])
127
    {
128
        $qb = $this->findBySearchQB($search, $options);
129
130
        return $qb->getQuery()->getArrayResult();
131
    }
132
133
    /**
134
     * @param string $search
135
     * @param array  $options
136
     *
137
     * @return QueryBuilder
138
     */
139
    protected function findBySearchQB($search, array $options)
140
    {
141
        $qb = $this->createQueryBuilder($this->getAlias());
142
143
        $this->selectFields($qb, $options);
144
        $this->addSortOrder($qb);
145
146
        if (null !== $search) {
147
            $this->addSearchFilter($qb, $search);
148
        }
149
150
        if (isset($options['limit'])) {
151
            $qb->setMaxResults((int) $options['limit']);
152
            if (isset($options['page'])) {
153
                $qb->setFirstResult((int) $options['limit'] * ((int) $options['page'] - 1));
154
            }
155
        }
156
157
        return $qb;
158
    }
159
160
    /**
161
     * Adds select in the findBySearch method
162
     * Used in products datagrid filtering and product edit form
163
     * This method is used by findBySearch method and it's not recommended to call it from elsewhere
164
     *
165
     * @param QueryBuilder $qb
166
     * @param array        $options
167
     */
168
    protected function selectFields(QueryBuilder $qb, array $options)
169
    {
170
        $labelProperty = $this->getReferenceDataLabelProperty();
171
        $identifierField = isset($options['type']) && 'code' === $options['type'] ? 'code' : 'id';
172
173
        $qb
174
            ->select(
175
                sprintf('%s.%s AS id', $this->getAlias(), $identifierField)
176
            )
177
            ->addSelect(
178
                sprintf(
179
                    'CASE WHEN %s.%s IS NULL OR %s.%s = \'\' THEN CONCAT(\'[\', %s.code, \']\') ELSE %s.%s END AS text',
180
                    $this->getAlias(),
181
                    $labelProperty,
182
                    $this->getAlias(),
183
                    $labelProperty,
184
                    $this->getAlias(),
185
                    $this->getAlias(),
186
                    $labelProperty
187
                )
188
            );
189
    }
190
191
    /**
192
     * Adds search on label or code in the findBySearch method
193
     * Used in products datagrid filtering and product edit form
194
     * This method is used by findBySearch method and it's not recommended to call it from elsewhere
195
     *
196
     * @param QueryBuilder $qb
197
     * @param string       $search
198
     */
199
    protected function addSearchFilter(QueryBuilder $qb, $search)
200
    {
201
        $labelProperty = $this->getReferenceDataLabelProperty();
202
203
        $searchDql = sprintf('%s.code LIKE :search', $this->getAlias());
204
        if ('code' !== $labelProperty) {
205
            $searchDql .= sprintf(' OR %s.%s LIKE :search', $this->getAlias(), $labelProperty);
206
        }
207
        $qb->andWhere($searchDql)->setParameter('search', "%$search%");
208
    }
209
210
    /**
211
     * Duplicate code due to method visibility
212
     *
213
     * {@inheritdoc}
214
     */
215
    protected function getReferenceDataLabelProperty()
216
    {
217
        $referenceDataClass = $this->getEntityName();
218
219
        return $referenceDataClass::getLabelProperty();
220
    }
221
222
    /**
223
     * Adds sort order in the findBySearch method
224
     * Used in products datagrid filtering and product edit form
225
     * This method is used by findBySearch method and it's not recommended to call it from elsewhere
226
     *
227
     * @param QueryBuilder $qb
228
     */
229
    protected function addSortOrder(QueryBuilder $qb)
230
    {
231
        $sortOrder = $this->getSortOrderColumn();
232
233
        $qb->orderBy(sprintf('%s.%s', $this->getAlias(), $sortOrder));
234
        $qb->addOrderBy(sprintf('%s.code', $this->getAlias()));
235
    }
236
237
    /**
238
     * @return string
239
     */
240
    protected function getSortOrderColumn()
241
    {
242
        $referenceDataClass = $this->getEntityName();
243
244
        return $referenceDataClass::getSortOrderColumn();
245
    }
246
}
247