Completed
Pull Request — master (#374)
by Leny
06:25
created

ViewRepository::findOneByHomepage()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 27
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 27
rs 8.8571
c 1
b 0
f 0
cc 1
eloc 16
nc 1
nop 1
1
<?php
2
3
namespace Victoire\Bundle\CoreBundle\Repository;
4
5
use Doctrine\ORM\Query;
6
use Gedmo\Tree\Entity\Repository\NestedTreeRepository;
7
use Victoire\Bundle\CoreBundle\Entity\View;
8
use Victoire\Bundle\PageBundle\Entity\Page;
9
use Victoire\Bundle\PageBundle\Entity\PageStatus;
10
use Victoire\Bundle\ViewReferenceBundle\ViewReference\BusinessPageReference;
11
use Victoire\Bundle\ViewReferenceBundle\ViewReference\ViewReference;
12
13
/**
14
 * The View repository.
15
 */
16
class ViewRepository extends NestedTreeRepository
17
{
18
    private $queryBuilder;
19
20
    /**
21
     * Get query builder instance.
22
     */
23
    public function getInstance()
24
    {
25
        return $this->queryBuilder ? $this->queryBuilder : $this->createQueryBuilder('page');
26
    }
27
28
    /**
29
     * Get the query builder for a view  by url.
30
     *
31
     * @param string $url The url
32
     *
33
     * @return \Doctrine\ORM\QueryBuilder The query builder
34
     */
35
    public function getOneByUrl($url)
36
    {
37
        return $this->createQueryBuilder('page')
38
            ->where('page.url = (:url)')
39
            ->setMaxResults(1)
40
            ->setParameter('url', $url);
41
    }
42
43
    /**
44
     * Filter the query by the sitemap index (=visibility).
45
     *
46
     * @param bool $indexed
47
     *
48
     * @return ViewRepository
49
     */
50
    public function filterBySitemapIndexed($indexed = true)
51
    {
52
        $qb = $this->getInstance();
53
        $qb->innerJoin('page.seo', 'seo')->addSelect('seo')
54
            ->andWhere('seo.sitemapIndexed = :sitemapIndexed')
55
            ->setParameter('sitemapIndexed', $indexed);
56
57
        return $this;
58
    }
59
60
    /**
61
     * Get all rentals in the repository.
62
     *
63
     * @param bool $excludeUnpublished Should we get only the published Views ?
64
     *
65
     * @return ViewRepository
66
     */
67
    public function getAll($excludeUnpublished = false)
68
    {
69
        $this->queryBuilder = $this->getInstance();
70
71
        //If $excludeUnpublished === true, we exclude the non published results
72 View Code Duplication
        if ($excludeUnpublished) {
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...
73
            $this->queryBuilder
74
                ->andWhere('page.status = :status')
75
                ->orWhere('page.status = :scheduled_status AND page.publishedAt > :publicationDate')
76
                ->setParameter('status', PageStatus::PUBLISHED)
77
                ->setParameter('scheduled_status', PageStatus::SCHEDULED)
78
                ->setParameter('publicationDate', new \DateTime());
79
        }
80
81
        return $this;
82
    }
83
84
    /**
85
     * Run instance.
86
     *
87
     * @param string $method
88
     * @param string $hydrationMode
89
     *
90
     * @return array
91
     */
92
    public function run($method = 'getResult', $hydrationMode = Query::HYDRATE_OBJECT)
93
    {
94
        return $this->getInstance()->getQuery()->$method($hydrationMode);
95
    }
96
97
    /**
98
     * Find a large amount of views by ViewReferences and optimizing queries with translation walker.
99
     *
100
     * @param ViewReference[] $viewReferences
101
     *
102
     * @return View[]|null The entity instance or NULL if the entities cannot be found.
103
     */
104
    public function findByViewReferences(array $viewReferences)
105
    {
106
        $views = [];
107
        $localizedViewReferences = [];
108
        foreach ($viewReferences as $viewReference) {
109
            if (array_key_exists($viewReference->getLocale(), $localizedViewReferences)) {
110
                $localizedViewReferences[$viewReference->getLocale()] = [];
111
            }
112
            $localizedViewReferences[$viewReference->getLocale()][] = $viewReference;
113
        }
114
115
        foreach ($localizedViewReferences as $locale => $_viewReferences) {
116
            //the query builder
117
            $queryBuilder = $this->createQueryBuilder('page');
118
119
            $pageIds = [];
120
            foreach ($_viewReferences as $viewReference) {
121
                if ($viewReference instanceof BusinessPageReference) {
122
                    $pageIds[] = $viewReference->getTemplateId();
123
                } else {
124
                    $pageIds[] = $viewReference->getViewId();
125
                }
126
            }
127
128
            $queryBuilder->andWhere('page.id IN (:pageIds)')
129
                ->setParameter('pageIds', $pageIds);
130
131
            // Use Translation Walker
132
            $query = $queryBuilder->getQuery();
133
            $query->setHint(
134
                \Doctrine\ORM\Query::HINT_CUSTOM_OUTPUT_WALKER,
135
                'Gedmo\\Translatable\\Query\\TreeWalker\\TranslationWalker'
136
            );
137
138
            // Force the locale
139
            $query->setHint(
140
                \Gedmo\Translatable\TranslatableListener::HINT_TRANSLATABLE_LOCALE,
141
                $locale
142
            );
143
144
            /* @var View[] $query */
145
            $_views = $query->getResult();
0 ignored issues
show
Bug introduced by
The method getResult cannot be called on $query (of type array<integer,object<Vic...oreBundle\Entity\View>>).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
146
            //Parse views to set locale and reference
147
            $views = array_merge($views, $_views);
148
        }
149
150
        return $views;
151
    }
152
153
    /**
154
     * Finds a single entity by a set of criteria.
155
     *
156
     * @param array      $criteria
157
     * @param array|null $orderBy
158
     *
159
     * @return object|null The entity instance or NULL if the entity can not be found.
160
     */
161
    public function findOneBy(array $criteria, array $orderBy = null)
162
    {
163
        $persister = $this->_em->getUnitOfWork()->getEntityPersister($this->_entityName);
164
165
        $hints = [];
166
        if (isset($criteria['locale'])) {
167
            $hints = [
168
                \Doctrine\ORM\Query::HINT_CUSTOM_OUTPUT_WALKER                     => 'Gedmo\\Translatable\\Query\\TreeWalker\\TranslationWalker',
169
                \Gedmo\Translatable\TranslatableListener::HINT_TRANSLATABLE_LOCALE => $criteria['locale'],
170
            ];
171
            unset($criteria['locale']);
172
        }
173
174
        return $persister->load($criteria, null, null, $hints, null, 1, $orderBy);
175
    }
176
177
    /**
178
     * Get the the view that is a homepage and a published one.
179
     *
180
     * @param string $locale
181
     *
182
     * @return Page
183
     */
184
    public function findOneByHomepage($locale = 'fr')
185
    {
186
        //the query builder
187
        $queryBuilder = $this->createQueryBuilder('page');
188
189
        $queryBuilder
190
            ->where('page.homepage = true')
191
            ->andWhere('page.status = :status')
192
            ->setMaxResults(1)
193
            ->setParameter('status', PageStatus::PUBLISHED);
194
195
        // Use Translation Walker
196
        $query = $queryBuilder->getQuery();
197
        $query->setHint(
198
            \Doctrine\ORM\Query::HINT_CUSTOM_OUTPUT_WALKER,
199
            'Gedmo\\Translatable\\Query\\TreeWalker\\TranslationWalker'
200
        );
201
        // Force the locale
202
        $query->setHint(
203
            \Gedmo\Translatable\TranslatableListener::HINT_TRANSLATABLE_LOCALE,
204
            $locale
205
        );
206
207
        $view = $query->getOneOrNullResult();
208
209
        return $view;
210
    }
211
212
    /**
213
     * Get PageSeo.
214
     *
215
     * @param string $method leftJoin|innerJoin
216
     *
217
     * @return ViewRepository
218
     */
219
    public function joinSeo($method = 'leftJoin')
220
    {
221
        $this->getInstance()->$method('page.seo', 'seo')->addSelect('seo');
222
223
        return $this;
224
    }
225
226
    /**
227
     * Filter the query by the sitemap index (=visibility).
228
     *
229
     * @param array $ids
230
     *
231
     * @return ViewRepository
232
     */
233
    public function filterByIds($ids)
234
    {
235
        $this->getInstance()->andWhere('page.id IN (:ids)')->setParameter('ids', $ids);
236
237
        return $this;
238
    }
239
}
240