Completed
Pull Request — develop (#261)
by Wachter
27:08 queued 12:01
created

ArticleIndexer::getTypeTranslation()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2.5

Importance

Changes 0
Metric Value
dl 0
loc 10
c 0
b 0
f 0
ccs 2
cts 4
cp 0.5
rs 9.4285
cc 2
eloc 5
nc 2
nop 1
crap 2.5
1
<?php
2
3
/*
4
 * This file is part of Sulu.
5
 *
6
 * (c) MASSIVE ART WebServices GmbH
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace Sulu\Bundle\ArticleBundle\Document\Index;
13
14
use ONGR\ElasticsearchBundle\Collection\Collection;
15
use ONGR\ElasticsearchBundle\Service\Manager;
16
use ONGR\ElasticsearchDSL\Query\MatchAllQuery;
17
use ONGR\ElasticsearchDSL\Query\TermLevel\TermQuery;
18
use Sulu\Bundle\ArticleBundle\Content\PageTreeRouteContentType;
19
use Sulu\Bundle\ArticleBundle\Document\ArticleDocument;
20
use Sulu\Bundle\ArticleBundle\Document\ArticlePageDocument;
21
use Sulu\Bundle\ArticleBundle\Document\ArticlePageViewObject;
22
use Sulu\Bundle\ArticleBundle\Document\ArticleViewDocumentInterface;
23
use Sulu\Bundle\ArticleBundle\Document\Index\Factory\ExcerptFactory;
24
use Sulu\Bundle\ArticleBundle\Document\Index\Factory\SeoFactory;
25
use Sulu\Bundle\ArticleBundle\Document\LocalizationStateViewObject;
26
use Sulu\Bundle\ArticleBundle\Document\Subscriber\RoutableSubscriber;
27
use Sulu\Bundle\ArticleBundle\Event\Events;
28
use Sulu\Bundle\ArticleBundle\Event\IndexEvent;
29
use Sulu\Bundle\ArticleBundle\Metadata\ArticleViewDocumentIdTrait;
30
use Sulu\Bundle\ArticleBundle\Metadata\StructureTagTrait;
31
use Sulu\Bundle\ContactBundle\Entity\ContactRepository;
32
use Sulu\Bundle\SecurityBundle\UserManager\UserManager;
33
use Sulu\Component\Content\Document\LocalizationState;
34
use Sulu\Component\Content\Document\WorkflowStage;
35
use Sulu\Component\Content\Metadata\Factory\StructureMetadataFactoryInterface;
36
use Sulu\Component\Content\Metadata\PropertyMetadata;
37
use Sulu\Component\Content\Metadata\StructureMetadata;
38
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
39
use Symfony\Component\Translation\TranslatorInterface;
40
41
/**
42
 * Provides methods to index articles.
43
 */
44
class ArticleIndexer implements IndexerInterface
45
{
46
    use StructureTagTrait;
47
    use ArticleViewDocumentIdTrait;
48
49
    /**
50
     * @var StructureMetadataFactoryInterface
51
     */
52
    protected $structureMetadataFactory;
53
54
    /**
55
     * @var UserManager
56
     */
57
    protected $userManager;
58
59
    /**
60
     * @var ContactRepository
61
     */
62
    protected $contactRepository;
63
64
    /**
65
     * @var DocumentFactoryInterface
66
     */
67
    protected $documentFactory;
68
69
    /**
70
     * @var Manager
71
     */
72
    protected $manager;
73
74
    /**
75
     * @var ExcerptFactory
76
     */
77
    protected $excerptFactory;
78
79
    /**
80
     * @var SeoFactory
81
     */
82
    protected $seoFactory;
83
84
    /**
85
     * @var EventDispatcherInterface
86
     */
87
    protected $eventDispatcher;
88
89
    /**
90
     * @var TranslatorInterface
91
     */
92
    protected $translator;
93
94
    /**
95
     * @var array
96
     */
97
    protected $typeConfiguration;
98
99
    /**
100
     * @param StructureMetadataFactoryInterface $structureMetadataFactory
101
     * @param UserManager $userManager
102
     * @param ContactRepository $contactRepository
103
     * @param DocumentFactoryInterface $documentFactory
104
     * @param Manager $manager
105
     * @param ExcerptFactory $excerptFactory
106
     * @param SeoFactory $seoFactory
107
     * @param EventDispatcherInterface $eventDispatcher
108
     * @param TranslatorInterface $translator
109 53
     * @param array $typeConfiguration
110
     */
111
    public function __construct(
112
        StructureMetadataFactoryInterface $structureMetadataFactory,
113
        UserManager $userManager,
114
        ContactRepository $contactRepository,
115
        DocumentFactoryInterface $documentFactory,
116
        Manager $manager,
117
        ExcerptFactory $excerptFactory,
118
        SeoFactory $seoFactory,
119
        EventDispatcherInterface $eventDispatcher,
120
        TranslatorInterface $translator,
121 53
        array $typeConfiguration
122 53
    ) {
123 53
        $this->structureMetadataFactory = $structureMetadataFactory;
124 53
        $this->userManager = $userManager;
125 53
        $this->contactRepository = $contactRepository;
126 53
        $this->documentFactory = $documentFactory;
127 53
        $this->manager = $manager;
128 53
        $this->excerptFactory = $excerptFactory;
129 53
        $this->seoFactory = $seoFactory;
130 53
        $this->eventDispatcher = $eventDispatcher;
131 53
        $this->translator = $translator;
132
        $this->typeConfiguration = $typeConfiguration;
133
    }
134
135
    /**
136
     * Returns translation for given article type.
137
     *
138
     * @param string $type
139
     *
140 52
     * @return string
141
     */
142 52
    private function getTypeTranslation($type)
143 52
    {
144
        if (!array_key_exists($type, $this->typeConfiguration)) {
145
            return ucfirst($type);
146
        }
147
148
        $typeTranslationKey = $this->typeConfiguration[$type]['translation_key'];
149
150
        return $this->translator->trans($typeTranslationKey, [], 'backend');
151
    }
152
153
    /**
154
     * @param ArticleDocument $document
155 52
     * @param ArticleViewDocumentInterface $article
156
     */
157 52
    protected function dispatchIndexEvent(ArticleDocument $document, ArticleViewDocumentInterface $article)
158 52
    {
159
        $this->eventDispatcher->dispatch(Events::INDEX_EVENT, new IndexEvent($document, $article));
160
    }
161
162
    /**
163
     * @param ArticleDocument $document
164
     * @param string $locale
165
     * @param string $localizationState
166
     *
167 52
     * @return ArticleViewDocumentInterface
168
     */
169
    protected function createOrUpdateArticle(
170
        ArticleDocument $document,
171
        $locale,
172 52
        $localizationState = LocalizationState::LOCALIZED
173 52
    ) {
174 5
        $article = $this->findOrCreateViewDocument($document, $locale, $localizationState);
175
        if (!$article) {
176
            return;
177 52
        }
178 52
179 52
        $structureMetadata = $this->structureMetadataFactory->getStructureMetadata(
180
            'article',
181
            $document->getStructureType()
182 52
        );
183 52
184 52
        $article->setTitle($document->getTitle());
185 52
        $article->setRoutePath($document->getRoutePath());
186 52
        $this->setParentPageUuid($structureMetadata, $document, $article);
0 ignored issues
show
Bug introduced by
It seems like $structureMetadata defined by $this->structureMetadata...nt->getStructureType()) on line 179 can be null; however, Sulu\Bundle\ArticleBundl...er::setParentPageUuid() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
187 52
        $article->setChanged($document->getChanged());
188 52
        $article->setCreated($document->getCreated());
189 52
        $article->setAuthored($document->getAuthored());
190 52
        if ($document->getAuthor() && $author = $this->contactRepository->find($document->getAuthor())) {
191
            $article->setAuthorFullName($author->getFullName());
192 52
            $article->setAuthorId($author->getId());
193 52
        }
194 52
        if ($document->getChanger() && $changer = $this->userManager->getUserById($document->getChanger())) {
195
            $article->setChangerFullName($changer->getFullName());
196 52
            $article->setChangerContactId($changer->getContact()->getId());
197 52
        }
198 52
        if ($document->getCreator() && $creator = $this->userManager->getUserById($document->getCreator())) {
199
            $article->setCreatorFullName($creator->getFullName());
200 52
            $article->setCreatorContactId($creator->getContact()->getId());
201 52
        }
202 52
        $article->setType($this->getType($structureMetadata));
0 ignored issues
show
Bug introduced by
It seems like $structureMetadata defined by $this->structureMetadata...nt->getStructureType()) on line 179 can be null; however, Sulu\Bundle\ArticleBundl...tureTagTrait::getType() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
203 52
        $article->setStructureType($document->getStructureType());
204 52
        $article->setPublished($document->getPublished());
0 ignored issues
show
Documentation introduced by
$document->getPublished() is of type boolean, but the function expects a null|object<DateTime>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
205 52
        $article->setPublishedState($document->getWorkflowStage() === WorkflowStage::PUBLISHED);
206 52
        $article->setTypeTranslation($this->getTypeTranslation($this->getType($structureMetadata)));
0 ignored issues
show
Bug introduced by
It seems like $structureMetadata defined by $this->structureMetadata...nt->getStructureType()) on line 179 can be null; however, Sulu\Bundle\ArticleBundl...tureTagTrait::getType() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
207 52
        $article->setLocalizationState(
208 52
            new LocalizationStateViewObject(
209
                $localizationState,
210
                (LocalizationState::LOCALIZED === $localizationState) ? null : $document->getLocale()
211
            )
212 52
        );
213 52
214 52
        $extensions = $document->getExtensionsData()->toArray();
215
        if (array_key_exists('excerpt', $extensions)) {
216 52
            $article->setExcerpt($this->excerptFactory->create($extensions['excerpt'], $document->getLocale()));
217 52
        }
218
        if (array_key_exists('seo', $extensions)) {
219 52
            $article->setSeo($this->seoFactory->create($extensions['seo']));
220 1
        }
221 1
        if ($structureMetadata->hasPropertyWithTagName('sulu.teaser.description')) {
222 1
            $descriptionProperty = $structureMetadata->getPropertyByTagName('sulu.teaser.description');
223
            $article->setTeaserDescription(
224
                $document->getStructure()->getProperty($descriptionProperty->getName())->getValue()
0 ignored issues
show
Documentation introduced by
$document->getStructure(...>getName())->getValue() is of type array<integer|string,*>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
225 52
            );
226 1
        }
227 1
        if ($structureMetadata->hasPropertyWithTagName('sulu.teaser.media')) {
228 1
            $mediaProperty = $structureMetadata->getPropertyByTagName('sulu.teaser.media');
229 1
            $mediaData = $document->getStructure()->getProperty($mediaProperty->getName())->getValue();
230
            if (null !== $mediaData && array_key_exists('ids', $mediaData)) {
231
                $article->setTeaserMediaId(reset($mediaData['ids']) ?: null);
232
            }
233 52
        }
234
235 52
        $article->setContentData(json_encode($document->getStructure()->toArray()));
236
237
        $this->mapPages($document, $article);
238
239
        return $article;
240
    }
241
242
    /**
243
     * Returns view-document from index or create a new one.
244
     *
245
     * @param ArticleDocument $document
246
     * @param string $locale
247 52
     * @param string $localizationState
248
     *
249 52
     * @return ArticleViewDocumentInterface
250
     */
251 52
    protected function findOrCreateViewDocument(ArticleDocument $document, $locale, $localizationState)
252
    {
253 52
        $articleId = $this->getViewDocumentId($document->getUuid(), $locale);
254
        /** @var ArticleViewDocumentInterface $article */
255 19
        $article = $this->manager->find($this->documentFactory->getClass('article'), $articleId);
256 19
257
        if ($article) {
258 5
            // Only index ghosts when the article isn't a ghost himself.
259
            if (LocalizationState::GHOST === $localizationState
260
                && LocalizationState::GHOST !== $article->getLocalizationState()->state
261 19
            ) {
262
                return null;
263
            }
264 52
265 52
            return $article;
266 52
        }
267 52
268
        $article = $this->documentFactory->create('article');
269 52
        $article->setId($articleId);
270
        $article->setUuid($document->getUuid());
271
        $article->setLocale($locale);
272
273
        return $article;
274
    }
275
276
    /**
277
     * Maps pages from document to view-document.
278 52
     *
279
     * @param ArticleDocument $document
280 52
     * @param ArticleViewDocumentInterface $article
281 52
     */
282 8
    private function mapPages(ArticleDocument $document, ArticleViewDocumentInterface $article)
283 8
    {
284 8
        $pages = [];
285 8
        /** @var ArticlePageDocument $child */
286 8
        foreach ($document->getChildren() as $child) {
287
            /** @var ArticlePageViewObject $page */
288
            $pages[] = $page = $this->documentFactory->create('article_page');
289 52
            $page->uuid = $child->getUuid();
0 ignored issues
show
Bug introduced by
Accessing uuid on the interface Sulu\Bundle\ArticleBundl...leViewDocumentInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
290 52
            $page->pageNumber = $child->getPageNumber();
0 ignored issues
show
Bug introduced by
Accessing pageNumber on the interface Sulu\Bundle\ArticleBundl...leViewDocumentInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
291
            $page->title = $child->getPageTitle();
0 ignored issues
show
Bug introduced by
Accessing title on the interface Sulu\Bundle\ArticleBundl...leViewDocumentInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
292
            $page->routePath = $child->getRoutePath();
0 ignored issues
show
Bug introduced by
Accessing routePath on the interface Sulu\Bundle\ArticleBundl...leViewDocumentInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
293
            $page->contentData = json_encode($child->getStructure()->toArray());
0 ignored issues
show
Bug introduced by
Accessing contentData on the interface Sulu\Bundle\ArticleBundl...leViewDocumentInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
294
        }
295
296
        $article->setPages(new Collection($pages));
297
    }
298
299 52
    /**
300
     * Set parent-page-uuid to view-document.
301
     *
302
     * @param StructureMetadata $metadata
303
     * @param ArticleDocument $document
304 52
     * @param ArticleViewDocumentInterface $article
305 52
     */
306 38
    private function setParentPageUuid(
307
        StructureMetadata $metadata,
308
        ArticleDocument $document,
309 14
        ArticleViewDocumentInterface $article
310 14
    ) {
311 7
        $propertyMetadata = $this->getRoutePathProperty($metadata);
312
        if (!$propertyMetadata) {
313
            return;
314 7
        }
315 7
316
        $property = $document->getStructure()->getProperty($propertyMetadata->getName());
317
        if (!$property || $propertyMetadata->getType() !== PageTreeRouteContentType::NAME || !$property->getValue()) {
318
            return;
319 7
        }
320 7
321
        $value = $property->getValue();
322
        if (!$value || !isset($value['page']) || !isset($value['page']['uuid'])) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $value 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...
323
            return;
324
        }
325
326
        $article->setParentPageUuid($value['page']['uuid']);
327
    }
328
329 52
    /**
330
     * Returns property-metadata for route-path property.
331 52
     *
332
     * @param StructureMetadata $metadata
333
     *
334
     * @return PropertyMetadata
335 52
     */
336 38 View Code Duplication
    private function getRoutePathProperty(StructureMetadata $metadata)
0 ignored issues
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...
337
    {
338
        if ($metadata->hasTag(RoutableSubscriber::TAG_NAME)) {
339 14
            return $metadata->getPropertyByTagName(RoutableSubscriber::TAG_NAME);
340
        }
341
342
        if (!$metadata->hasProperty(RoutableSubscriber::ROUTE_FIELD)) {
343
            return;
344
        }
345
346
        return $metadata->getProperty(RoutableSubscriber::ROUTE_FIELD);
347
    }
348
349
    /**
350
     * @param string $id
351
     */
352
    protected function removeArticle($id)
353
    {
354
        $article = $this->manager->find(
355
            $this->documentFactory->getClass('article'),
356
            $id
357
        );
358
        if (null === $article) {
359
            return;
360
        }
361 2
362
        $this->manager->remove($article);
363 2
    }
364 2
365 2
    /**
366 2
     * {@inheritdoc}
367 2
     */
368 2
    public function remove($document)
369
    {
370 2
        $repository = $this->manager->getRepository($this->documentFactory->getClass('article'));
371
        $search = $repository->createSearch()
372
            ->addQuery(new TermQuery('uuid', $document->getUuid()))
373
            ->setSize(1000);
374
        foreach ($repository->findDocuments($search) as $viewDocument) {
375 52
            $this->manager->remove($viewDocument);
0 ignored issues
show
Bug introduced by
It seems like $viewDocument defined by $viewDocument on line 374 can also be of type array or null; however, ONGR\ElasticsearchBundle\Service\Manager::remove() does only seem to accept object, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
376
        }
377 52
    }
378 52
379
    /**
380
     * {@inheritdoc}
381
     */
382
    public function flush()
383 18
    {
384
        $this->manager->commit();
385 18
    }
386 18
387 18
    /**
388 18
     * {@inheritdoc}
389 18
     */
390
    public function clear()
391
    {
392 18
        $pageSize = 500;
393 18
        $repository = $this->manager->getRepository($this->documentFactory->getClass('article'));
394 16
        $search = $repository->createSearch()
395
            ->addQuery(new MatchAllQuery())
396
            ->setSize($pageSize);
397 18
398 18
        do {
399
            $result = $repository->findDocuments($search);
400 18
            foreach ($result as $document) {
401 18
                $this->manager->remove($document);
0 ignored issues
show
Bug introduced by
It seems like $document defined by $document on line 400 can also be of type array or null; however, ONGR\ElasticsearchBundle\Service\Manager::remove() does only seem to accept object, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
402 18
            }
403
404
            $this->manager->commit();
405
        } while ($result->count() !== 0);
406
407
        $this->manager->clearCache();
408
        $this->manager->flush();
409
    }
410
411
    /**
412
     * {@inheritdoc}
413
     */
414
    public function setUnpublished($uuid, $locale)
415
    {
416
        $articleId = $this->getViewDocumentId($uuid, $locale);
417
        $article = $this->manager->find($this->documentFactory->getClass('article'), $articleId);
418
        if (!$article) {
419
            return;
420
        }
421
422
        $article->setPublished(null);
423
        $article->setPublishedState(false);
424 19
425
        $this->manager->persist($article);
426 19
427 19
        return $article;
428 19
    }
429 19
430
    /**
431
     * {@inheritdoc}
432
     */
433
    public function index(ArticleDocument $document)
434
    {
435
        $article = $this->createOrUpdateArticle($document, $document->getLocale());
436
        $this->dispatchIndexEvent($document, $article);
0 ignored issues
show
Bug introduced by
It seems like $article defined by $this->createOrUpdateArt...$document->getLocale()) on line 435 can be null; however, Sulu\Bundle\ArticleBundl...r::dispatchIndexEvent() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
437
        $this->manager->persist($article);
0 ignored issues
show
Bug introduced by
It seems like $article defined by $this->createOrUpdateArt...$document->getLocale()) on line 435 can be null; however, ONGR\ElasticsearchBundle...vice\Manager::persist() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
438
    }
439
440
    /**
441
     * {@inheritdoc}
442
     */
443
    public function dropIndex()
444
    {
445
        $this->manager->dropIndex();
446
    }
447
448
    /**
449
     * {@inheritdoc}
450
     */
451
    public function createIndex()
452
    {
453
        if ($this->manager->indexExists()) {
454
            return;
455
        }
456
457
        $this->manager->createIndex();
458
    }
459
}
460