Completed
Push — master ( e428dc...30fa97 )
by Paweł
13s
created

ArticleRepository::getPaginatedByCriteria()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 11
Ratio 100 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
dl 11
loc 11
ccs 7
cts 7
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 3
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Superdesk Web Publisher Content Bundle.
7
 *
8
 * Copyright 2016 Sourcefabric z.ú. and contributors.
9
 *
10
 * For the full copyright and license information, please see the
11
 * AUTHORS and LICENSE files distributed with this source code.
12
 *
13
 * @copyright 2016 Sourcefabric z.ú
14
 * @license http://www.superdesk.org/license
15
 */
16
17
namespace SWP\Bundle\ContentBundle\Doctrine\ORM;
18
19
use Doctrine\ORM\QueryBuilder;
20
use Doctrine\ORM\Tools\Pagination\Paginator;
21
use SWP\Component\Common\Criteria\Criteria;
22
use SWP\Bundle\ContentBundle\Doctrine\ArticleRepositoryInterface;
23
use SWP\Bundle\ContentBundle\Model\ArticleInterface;
24
use SWP\Bundle\StorageBundle\Doctrine\ORM\EntityRepository;
25
use SWP\Component\Common\Pagination\PaginationData;
26
27
class ArticleRepository extends EntityRepository implements ArticleRepositoryInterface
28
{
29
    /**
30 9
     * {@inheritdoc}
31
     */
32 9
    public function findOneBySlug($slug)
33 9
    {
34
        return $this->findOneBy([
35
            'slug' => $slug,
36
        ]);
37
    }
38
39
    /**
40
     * {@inheritdoc}
41
     */
42
    public function findAllArticles()
43
    {
44
        return $this->getQueryByCriteria(new Criteria(), [], 'a')->getQuery()->getResult();
45
    }
46
47
    /**
48 12
     * {@inheritdoc}
49
     */
50 12
    public function getByCriteria(Criteria $criteria, array $sorting): QueryBuilder
51 12
    {
52 12
        $qb = $this->getQueryByCriteria($criteria, $sorting, 'a');
53
        $qb->andWhere('a.status = :status')
54 12
            ->setParameter('status', $criteria->get('status', ArticleInterface::STATUS_PUBLISHED))
55
            ->leftJoin('a.media', 'm')
56
            ->addSelect('m');
57
58
        $this->applyCustomFiltering($qb, $criteria);
59
60 2
        return $qb;
61
    }
62 2
63 2
    /**
64 2
     * {@inheritdoc}
65 2
     */
66
    public function countByCriteria(Criteria $criteria): int
67 2
    {
68
        $queryBuilder = $this->createQueryBuilder('a')
69 2
            ->select('COUNT(a.id)')
70
            ->where('a.status = :status')
71
            ->setParameter('status', $criteria->get('status', ArticleInterface::STATUS_PUBLISHED));
72
73
        $this->applyCustomFiltering($queryBuilder, $criteria);
74
        $this->applyCriteria($queryBuilder, $criteria, 'a');
75 7
76
        return (int) $queryBuilder->getQuery()->getSingleScalarResult();
77 7
    }
78 7
79 7
    /**
80
     * {@inheritdoc}
81 7
     */
82 2
    public function findArticlesByCriteria(Criteria $criteria, array $sorting = []): array
83 2
    {
84 2
        $queryBuilder = $this->createQueryBuilder('a')
85
            ->where('a.status = :status')
86
            ->setParameter('status', $criteria->get('status', ArticleInterface::STATUS_PUBLISHED))
87 2
            ->leftJoin('a.media', 'm')
88
            ->addSelect('m');
89
90 7
        $this->applyCustomFiltering($queryBuilder, $criteria);
91
        $this->applyCriteria($queryBuilder, $criteria, 'a');
92
        $this->applySorting($queryBuilder, $sorting, 'a');
93
        $this->applyLimiting($queryBuilder, $criteria);
94
95
        $paginator = new Paginator($queryBuilder->getQuery(), true);
96 7
97
        return $paginator->getIterator()->getArrayCopy();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Traversable as the method getArrayCopy() does only exist in the following implementations of said interface: ArrayIterator, ArrayObject, DoctrineTest\Instantiato...tAsset\ArrayObjectAsset, DoctrineTest\Instantiato...lizableArrayObjectAsset, DoctrineTest\Instantiato...ceptionArrayObjectAsset, DoctrineTest\Instantiato...sset\WakeUpNoticesAsset, Hoa\Iterator\Map, Hoa\Iterator\Recursive\Map, Issue523, Pixers\DoctrineProfilerB...attenTraceGraphIterator, QueryPathIterator, RecursiveArrayIterator, Symfony\Component\Finder...rator\InnerNameIterator, Symfony\Component\Finder...rator\InnerSizeIterator, Symfony\Component\Finder...rator\InnerTypeIterator, Symfony\Component\Finder...or\MockFileListIterator, Symfony\Component\Form\E...r\ViolationPathIterator, Symfony\Component\Proper...ss\PropertyPathIterator, Zend\Code\Annotation\AnnotationCollection, Zend\Code\Scanner\AnnotationScanner, Zend\Stdlib\ArrayObject, Zend\Stdlib\ArrayStack, Zend\Stdlib\Parameters.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
98
    }
99
100
    /**
101
     * {@inheritdoc}
102 7
     */
103 3 View Code Duplication
    public function getPaginatedByCriteria(Criteria $criteria, array $sorting = [], PaginationData $paginationData = null)
1 ignored issue
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...
104 3
    {
105 3
        $queryBuilder = $this->getQueryByCriteria($criteria, $sorting, 'a');
106
        $this->applyCustomFiltering($queryBuilder, $criteria);
107
108 3
        if (null === $paginationData) {
109
            $paginationData = new PaginationData();
110
        }
111 7
112 7
        return $this->getPaginator($queryBuilder, $paginationData);
113 7
    }
114
115 7
    /**
116
     * {@inheritdoc}
117
     */
118
    public function getQueryForRouteArticles(string $identifier, array $order = [])
119
    {
120
        throw new \Exception('Not implemented');
121
    }
122
123
    private function applyCustomFiltering(QueryBuilder $queryBuilder, Criteria $criteria)
124
    {
125
        foreach (['metadata', 'author'] as $name) {
126
            if (!$criteria->has($name)) {
127
                continue;
128
            }
129
130
            if (!is_array($criteria->get($name))) {
131
                $criteria->remove($name);
132
                continue;
133
            }
134
135
            $orX = $queryBuilder->expr()->orX();
136
            foreach ($criteria->get($name) as $value) {
137
                $valueExpression = $queryBuilder->expr()->literal('%'.$value.'%');
138
                if ('author' === $name) {
139
                    $valueExpression = $queryBuilder->expr()->literal('%"byline":"'.$value.'"%');
140
                }
141
                $orX->add($queryBuilder->expr()->like('a.metadata', $valueExpression));
142
            }
143
144
            $queryBuilder->andWhere($orX);
145
            $criteria->remove($name);
146
        }
147
148 View Code Duplication
        if ($criteria->has('publishedBefore') && $criteria->get('publishedBefore') instanceof \DateTime) {
1 ignored issue
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...
149
            $queryBuilder->andWhere('a.publishedAt < :before')
150
                ->setParameter('before', $criteria->get('publishedBefore'));
151
            $criteria->remove('publishedBefore');
152
        }
153
154 View Code Duplication
        if ($criteria->has('publishedAfter') && $criteria->get('publishedAfter') instanceof \DateTime) {
1 ignored issue
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...
155
            $queryBuilder->andWhere('a.publishedAt > :after')
156
                ->setParameter('after', $criteria->get('publishedAfter'));
157
            $criteria->remove('publishedAfter');
158
        }
159
160
        if ($criteria->has('query') && strlen($query = trim($criteria->get('query'))) > 0) {
161
            $like = $queryBuilder->expr()->like('a.title', $queryBuilder->expr()->literal('%'.$query.'%'));
162
163
            $queryBuilder->andWhere($like);
164
            $criteria->remove('query');
165
        }
166
    }
167
}
168