ElasticsearchActivityStorage::execute()   B
last analyzed

Complexity

Conditions 5
Paths 16

Size

Total Lines 31
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 31
rs 8.439
c 0
b 0
f 0
cc 5
eloc 19
nc 16
nop 1
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\ElasticsearchActivityLogBundle\Storage;
13
14
use ONGR\ElasticsearchBundle\Service\Manager;
15
use ONGR\ElasticsearchBundle\Service\Repository;
16
use ONGR\ElasticsearchDSL\Aggregation\Bucketing\TermsAggregation;
17
use ONGR\ElasticsearchDSL\Query\Compound\BoolQuery;
18
use ONGR\ElasticsearchDSL\Query\MatchAllQuery;
19
use ONGR\ElasticsearchDSL\Query\TermLevel\TermQuery;
20
use ONGR\ElasticsearchDSL\Query\TermLevel\WildcardQuery;
21
use ONGR\ElasticsearchDSL\Search;
22
use ONGR\ElasticsearchDSL\Sort\FieldSort;
23
use Sulu\Bundle\ElasticsearchActivityLogBundle\Document\ActivityLoggerViewDocument;
24
use Sulu\Component\ActivityLog\Model\ActivityLogInterface;
25
use Sulu\Component\ActivityLog\Repository\UserRepositoryInterface;
26
use Sulu\Component\ActivityLog\Storage\ActivityLogStorageInterface;
27
28
/**
29
 * Implements activity-storage with elasticsearch.
30
 */
31
class ElasticsearchActivityStorage implements ActivityLogStorageInterface
32
{
33
    /**
34
     * @var Manager
35
     */
36
    private $manager;
37
38
    /**
39
     * @var Repository
40
     */
41
    private $repository;
42
43
    /**
44
     * @var UserRepositoryInterface
45
     */
46
    private $userRepository;
47
48
    /**
49
     * @param Manager $manager
50
     * @param UserRepositoryInterface $userRepository
51
     */
52
    public function __construct(Manager $manager, UserRepositoryInterface $userRepository)
53
    {
54
        $this->manager = $manager;
55
        $this->repository = $manager->getRepository(ActivityLoggerViewDocument::class);
56
        $this->userRepository = $userRepository;
57
    }
58
59
    /**
60
     * {@inheritdoc}
61
     */
62
    public function create($type, $uuid = null)
63
    {
64
        return new ActivityLoggerViewDocument($type, $uuid);
65
    }
66
67
    /**
68
     * {@inheritdoc}
69
     */
70
    public function find($uuid)
71
    {
72
        /** @var ActivityLoggerViewDocument $activityLog */
73
        $activityLog = $this->repository->find($uuid);
74
75
        if ($activityLog->getCreatorId()) {
76
            $activityLog->setCreator($this->userRepository->find($activityLog->getCreatorId()));
0 ignored issues
show
Bug introduced by
The method find() does not seem to exist on object<Sulu\Component\Ac...serRepositoryInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
77
        }
78
79
        if ($activityLog->getParentUuid()) {
80
            $activityLog->setParent($this->find($activityLog->getParentUuid()));
81
        }
82
83
        return $activityLog;
84
    }
85
86
    /**
87
     * {@inheritdoc}
88
     */
89 View Code Duplication
    public function findAll($page = 1, $pageSize = null)
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...
90
    {
91
        $search = $this->repository->createSearch()->addQuery(new MatchAllQuery());
92
93
        if (!$pageSize) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $pageSize of type integer|null is loosely compared to false; this is ambiguous if the integer can be zero. 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...
94
            $search->setScroll('10m');
95
        } else {
96
            $search = $search->setFrom(($page - 1) * $pageSize)->setSize($pageSize);
97
        }
98
99
        return $this->execute($search);
100
    }
101
102
    /**
103
     * {@inheritdoc}
104
     */
105
    public function findAllWithSearch(
106
        $query = null,
107
        $fields = null,
108
        $page = 1,
109
        $pageSize = null,
110
        $sortColumn = null,
111
        $sortOrder = null
112
    ) {
113
        $search = $this->createQueryForSearch($query, $fields);
114
115
        if ($sortColumn && $sortOrder) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $sortColumn of type string|null is loosely compared to true; this is ambiguous if the string can be empty. 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 string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
Bug Best Practice introduced by
The expression $sortOrder of type string|null is loosely compared to true; this is ambiguous if the string can be empty. 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 string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
116
            $search->addSort(new FieldSort($sortColumn . '.raw', $sortOrder));
117
        }
118
119
        if (!$pageSize) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $pageSize of type integer|null is loosely compared to false; this is ambiguous if the integer can be zero. 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...
120
            $search->setScroll('10m');
121
        } else {
122
            $search = $search->setFrom(($page - 1) * $pageSize)->setSize($pageSize);
123
        }
124
125
        return $this->execute($search);
126
    }
127
128
    /**
129
     * {@inheritdoc}
130
     */
131
    public function getCountForAllWithSearch($query = null, $fields = null)
132
    {
133
        $search = $this->createQueryForSearch($query, $fields);
134
135
        $search->setScroll('10m');
136
137
        return $this->repository->count($search);
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->repository->count($search); of type integer|array adds the type array to the return on line 137 which is incompatible with the return type declared by the interface Sulu\Component\ActivityL...etCountForAllWithSearch of type integer.
Loading history...
138
    }
139
140
    /**
141
     * {@inheritdoc}
142
     */
143 View Code Duplication
    public function findByParent(ActivityLogInterface $activityLog, $page = 1, $pageSize = null)
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...
144
    {
145
        $search = $this->repository->createSearch()->addQuery(new TermQuery('parentUuid', $activityLog->getUuid()));
146
147
        if (!$pageSize) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $pageSize of type integer|null is loosely compared to false; this is ambiguous if the integer can be zero. 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...
148
            $search->setScroll('10m');
149
        } else {
150
            $search->setFrom(($page - 1) * $pageSize)->setSize($pageSize);
151
        }
152
153
        return $this->execute($search);
154
    }
155
156
    /**
157
     * {@inheritdoc}
158
     */
159
    public function persist(ActivityLogInterface $activityLog)
160
    {
161
        $this->manager->persist($activityLog);
162
163
        return $activityLog;
164
    }
165
166
    /**
167
     * {@inheritdoc}
168
     */
169
    public function flush()
170
    {
171
        $this->manager->commit();
172
        $this->manager->flush();
173
    }
174
175
    /**
176
     * Executes given search and append parents and creators.
177
     *
178
     * @param Search $search
179
     *
180
     * @return ResultIterator
181
     */
182
    private function execute(Search $search)
183
    {
184
        $search->addAggregation(new TermsAggregation('parentUuid', 'parentUuid'))
185
            ->addAggregation(new TermsAggregation('creatorId', 'creatorId'));
186
187
        $result = $this->repository->findDocuments($search);
188
189
        $aggregation = $result->getAggregation('parentUuid');
190
        $parentUuids = [];
191
        foreach ($aggregation->getBuckets() as $bucket) {
192
            $parentUuids[] = $bucket->getValue();
193
        }
194
195
        $parents = null;
196
        if (0 < count($parentUuids)) {
197
            $parents = $this->repository->findByIds($parentUuids);
198
        }
199
200
        $aggregation = $result->getAggregation('creatorId');
201
        $creatorIds = [];
202
        foreach ($aggregation->getBuckets() as $bucket) {
203
            $creatorIds[] = $bucket->getValue();
204
        }
205
206
        $creators = null;
207
        if (0 < count($creatorIds)) {
208
            $creators = $this->userRepository->findBy(['id' => $creatorIds]);
0 ignored issues
show
Bug introduced by
The method findBy() does not seem to exist on object<Sulu\Component\Ac...serRepositoryInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
209
        }
210
211
        return iterator_to_array(new ResultIterator($result, $parents, $creators));
212
    }
213
214
    /**
215
     * @param string $query
216
     * @param array $fields
217
     *
218
     * @return Search
219
     */
220
    private function createQueryForSearch($query = null, $fields = null)
221
    {
222
        $search = $this->repository->createSearch()->addQuery(new MatchAllQuery());
223
224
        if (isset($query)) {
225
            $boolQuery = new BoolQuery();
226
227
            foreach ($fields as $field) {
0 ignored issues
show
Bug introduced by
The expression $fields of type array|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
228
                $boolQuery->add(new WildcardQuery($field, '*' . $query . '*'), BoolQuery::SHOULD);
229
            }
230
231
            $search->addQuery($boolQuery);
232
        }
233
234
        return $search;
235
    }
236
}
237