GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Push — master ( e9c651...e1baf6 )
by Christian
02:19
created

SortableListener::uniquePosition()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 10
rs 9.6111
c 0
b 0
f 0
cc 5
nc 4
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * (c) Christian Gripp <[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 Core23\Doctrine\EventListener\ORM;
13
14
use Core23\Doctrine\Model\PositionAwareInterface;
15
use Core23\Doctrine\Model\Traits\SortableTrait;
16
use Doctrine\ORM\EntityManager;
17
use Doctrine\ORM\Event\LifecycleEventArgs;
18
use Doctrine\ORM\Event\LoadClassMetadataEventArgs;
19
use Doctrine\ORM\Event\PreUpdateEventArgs;
20
use Doctrine\ORM\Events;
21
use Doctrine\ORM\Mapping\ClassMetadata;
22
use Doctrine\ORM\Mapping\MappingException;
23
use Doctrine\ORM\NonUniqueResultException;
24
use Symfony\Component\PropertyAccess\PropertyAccess;
25
26
final class SortableListener extends AbstractListener
27
{
28
    /**
29
     * {@inheritdoc}
30
     */
31
    public function getSubscribedEvents()
32
    {
33
        return [
34
            Events::prePersist,
35
            Events::preUpdate,
36
            Events::preRemove,
37
            Events::loadClassMetadata,
38
        ];
39
    }
40
41
    /**
42
     * @param LifecycleEventArgs $args
43
     */
44
    public function prePersist(LifecycleEventArgs $args): void
45
    {
46
        if ($args->getEntity() instanceof PositionAwareInterface) {
47
            $this->uniquePosition($args);
48
        }
49
    }
50
51
    /**
52
     * @param PreUpdateEventArgs $args
53
     */
54
    public function preUpdate(PreUpdateEventArgs $args): void
55
    {
56
        if ($args->getEntity() instanceof PositionAwareInterface) {
57
            $position = $args->getEntity()->getPosition();
58
59
            if ($args->hasChangedField('position')) {
60
                $position = $args->getOldValue('position');
61
            }
62
63
            $this->uniquePosition($args, $position);
64
        }
65
    }
66
67
    /**
68
     * @param LifecycleEventArgs $args
69
     */
70
    public function preRemove(LifecycleEventArgs $args): void
71
    {
72
        $entity = $args->getEntity();
73
74
        if ($entity instanceof PositionAwareInterface) {
75
            $this->movePosition($args->getEntityManager(), $entity, -1);
76
        }
77
    }
78
79
    /**
80
     * @param LoadClassMetadataEventArgs $eventArgs
81
     *
82
     * @throws MappingException
83
     */
84
    public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs): void
85
    {
86
        $meta = $eventArgs->getClassMetadata();
87
88
        if (!$meta instanceof ClassMetadata) {
0 ignored issues
show
introduced by
$meta is always a sub-type of Doctrine\ORM\Mapping\ClassMetadata.
Loading history...
89
            throw new \LogicException(sprintf('Class metadata was no ORM but %s', \get_class($meta)));
90
        }
91
92
        $reflClass = $meta->getReflectionClass();
93
94
        if (null === $reflClass || !$this->containsTrait($reflClass, SortableTrait::class)) {
95
            return;
96
        }
97
98
        if (!$meta->hasField('position')) {
99
            $meta->mapField([
100
                'type'      => 'integer',
101
                'fieldName' => 'position',
102
            ]);
103
        }
104
    }
105
106
    /**
107
     * @param LifecycleEventArgs $args
108
     * @param int|null           $oldPosition
109
     */
110
    private function uniquePosition(LifecycleEventArgs $args, ?int $oldPosition = null): void
111
    {
112
        $entity = $args->getEntity();
113
114
        if ($entity instanceof PositionAwareInterface) {
115
            if (null === $entity->getPosition()) {
116
                $position = $this->getNextPosition($args->getEntityManager(), $entity);
117
                $entity->setPosition($position);
118
            } elseif ($oldPosition && $oldPosition !== $entity->getPosition()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $oldPosition of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
119
                $this->movePosition($args->getEntityManager(), $entity);
120
            }
121
        }
122
    }
123
124
    /**
125
     * @param EntityManager          $em
126
     * @param PositionAwareInterface $entity
127
     * @param int                    $direction
128
     */
129
    private function movePosition(EntityManager $em, PositionAwareInterface $entity, int $direction = 1): void
130
    {
131
        $uow  = $em->getUnitOfWork();
132
        $meta = $em->getClassMetadata(\get_class($entity));
133
134
        $qb = $em->createQueryBuilder()
135
            ->update($meta->getName(), 'e')
136
            ->set('e.position', 'e.position + '.$direction);
137
138
        if ($direction > 0) {
139
            $qb->andWhere('e.position <= :position')->setParameter('position', $entity->getPosition());
140
        } elseif ($direction < 0) {
141
            $qb->andWhere('e.position >= :position')->setParameter('position', $entity->getPosition());
142
        } else {
143
            return;
144
        }
145
146
        $propertyAccessor = PropertyAccess::createPropertyAccessor();
147
148
        foreach ($entity->getPositionGroup() as $field) {
149
            $value = $propertyAccessor->getValue($entity, $field);
150
151
            if (\is_object($value) && null === $uow->getSingleIdentifierValue($value)) {
152
                continue;
153
            }
154
155
            $qb->andWhere('e.'.$field.' = :'.$field)->setParameter($field, $value);
156
        }
157
158
        $qb->getQuery()->execute();
159
    }
160
161
    /**
162
     * @param EntityManager          $em
163
     * @param PositionAwareInterface $entity
164
     *
165
     * @return int
166
     */
167
    private function getNextPosition(EntityManager $em, PositionAwareInterface $entity): int
168
    {
169
        $meta = $em->getClassMetadata(\get_class($entity));
170
171
        $qb = $em->createQueryBuilder()
172
            ->select('e')
173
            ->from($meta->getName(), 'e')
174
            ->addOrderBy('e.position', 'DESC')
175
            ->setMaxResults(1);
176
177
        $propertyAccessor = PropertyAccess::createPropertyAccessor();
178
179
        foreach ($entity->getPositionGroup() as $field) {
180
            $value = $propertyAccessor->getValue($entity, $field);
181
            $qb->andWhere('e.'.$field.' = :'.$field)->setParameter($field, $value);
182
        }
183
184
        /* @var PositionAwareInterface $result */
185
        try {
186
            $result = $qb->getQuery()->getOneOrNullResult();
187
188
            return ($result ? $result->getPosition() : 0) + 1;
189
        } catch (NonUniqueResultException $ignored) {
190
            return 0;
191
        }
192
    }
193
}
194