Completed
Pull Request — master (#1)
by
unknown
13:02
created

ElasticsearchActivityStorage::create()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 2
1
<?php
2
3
namespace Sulu\Bundle\ElasticsearchActivityLogBundle\Storage;
4
5
use ONGR\ElasticsearchBundle\Service\Manager;
6
use ONGR\ElasticsearchBundle\Service\Repository;
7
use ONGR\ElasticsearchDSL\Aggregation\Bucketing\TermsAggregation;
8
use ONGR\ElasticsearchDSL\Query\Compound\BoolQuery;
9
use ONGR\ElasticsearchDSL\Query\MatchAllQuery;
10
use ONGR\ElasticsearchDSL\Query\TermLevel\TermQuery;
11
use ONGR\ElasticsearchDSL\Query\TermLevel\WildcardQuery;
12
use ONGR\ElasticsearchDSL\Search;
13
use ONGR\ElasticsearchDSL\Sort\FieldSort;
14
use Sulu\Bundle\ElasticsearchActivityLogBundle\Document\ActivityLoggerViewDocument;
15
use Sulu\Component\ActivityLog\Model\ActivityLogInterface;
16
use Sulu\Component\ActivityLog\Repository\UserRepositoryInterface;
17
use Sulu\Component\ActivityLog\Storage\ActivityLogStorageInterface;
18
19
/**
20
 * Implements activity-storage with elasticsearch.
21
 */
22
class ElasticsearchActivityStorage implements ActivityLogStorageInterface
23
{
24
    /**
25
     * @var Manager
26
     */
27
    private $manager;
28
29
    /**
30
     * @var Repository
31
     */
32
    private $repository;
33
34
    /**
35
     * @var UserRepositoryInterface
36
     */
37
    private $userRepository;
38
39
    /**
40
     * @param Manager $manager
41
     * @param UserRepositoryInterface $userRepository
42
     */
43
    public function __construct(Manager $manager, UserRepositoryInterface $userRepository)
44
    {
45
        $this->manager = $manager;
46
        $this->repository = $manager->getRepository(ActivityLoggerViewDocument::class);
47
        $this->userRepository = $userRepository;
48
    }
49
50
    /**
51
     * {@inheritdoc}
52
     */
53
    public function create($type, $uuid = null)
54
    {
55
        return new ActivityLoggerViewDocument($type, $uuid);
56
    }
57
58
    /**
59
     * {@inheritdoc}
60
     */
61
    public function find($uuid)
62
    {
63
        /** @var ActivityLoggerViewDocument $activityLog */
64
        $activityLog = $this->repository->find($uuid);
65
66
        if ($activityLog->getCreatorId()) {
67
            $activityLog->setCreator($this->userRepository->find($activityLog->getCreatorId()));
68
        }
69
70
        if ($activityLog->getParentUuid()) {
71
            $activityLog->setParent($this->find($activityLog->getParentUuid()));
72
        }
73
74
        return $activityLog;
75
    }
76
77
    /**
78
     * {@inheritdoc}
79
     */
80 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...
81
    {
82
        $search = $this->repository->createSearch()->addQuery(new MatchAllQuery());
83
84
        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...
85
            $search->setScroll('10m');
86
        } else {
87
            $search = $search->setFrom(($page - 1) * $pageSize)->setSize($pageSize);
88
        }
89
90
        return $this->execute($search);
91
    }
92
93
    /**
94
     * {@inheritdoc}
95
     */
96
    public function findAllWithSearch(
97
        $query = null,
98
        $fields = null,
99
        $page = 1,
100
        $pageSize = null,
101
        $sortColumn = null,
102
        $sortOrder = null
103
    ) {
104
        $search = $this->createQueryForSearch($query, $fields);
105
106
        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...
107
            $search->addSort(new FieldSort($sortColumn . '.raw', $sortOrder));
108
        }
109
110
        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...
111
            $search->setScroll('10m');
112
        } else {
113
            $search = $search->setFrom(($page - 1) * $pageSize)->setSize($pageSize);
114
        }
115
116
        return $this->execute($search);
117
    }
118
119
    /**
120
     * {@inheritdoc}
121
     */
122
    public function getCountForAllWithSearch($query = null, $fields = null)
123
    {
124
        $search = $this->createQueryForSearch($query, $fields);
125
126
        $search->setScroll('10m');
127
128
        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 128 which is incompatible with the return type declared by the interface Sulu\Component\ActivityL...etCountForAllWithSearch of type integer.
Loading history...
129
    }
130
131
    /**
132
     * {@inheritdoc}
133
     */
134 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...
135
    {
136
        $search = $this->repository->createSearch()->addQuery(new TermQuery('parentUuid', $activityLog->getUuid()));
137
138
        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...
139
            $search->setScroll('10m');
140
        } else {
141
            $search->setFrom(($page - 1) * $pageSize)->setSize($pageSize);
142
        }
143
144
        return $this->execute($search);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->execute($search); (array) is incompatible with the return type declared by the interface Sulu\Component\ActivityL...Interface::findByParent of type Sulu\Component\ActivityL...el\ActivityLogInterface.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
145
    }
146
147
    /**
148
     * {@inheritdoc}
149
     */
150
    public function persist(ActivityLogInterface $activityLog)
151
    {
152
        $this->manager->persist($activityLog);
153
154
        return $activityLog;
155
    }
156
157
    /**
158
     * {@inheritdoc}
159
     */
160
    public function flush()
161
    {
162
        $this->manager->commit();
163
        $this->manager->flush();
164
    }
165
166
    /**
167
     * Executes given search and append parents and creators.
168
     *
169
     * @param Search $search
170
     *
171
     * @return ResultIterator
172
     */
173
    private function execute(Search $search)
174
    {
175
        $search->addAggregation(new TermsAggregation('parentUuid', 'parentUuid'))
176
            ->addAggregation(new TermsAggregation('creatorId', 'creatorId'));
177
178
        $result = $this->repository->findDocuments($search);
179
180
        $aggregation = $result->getAggregation('parentUuid');
181
        $parentUuids = [];
182
        foreach ($aggregation->getBuckets() as $bucket) {
183
            $parentUuids[] = $bucket->getValue();
184
        }
185
186
        $parents = null;
187
        if (0 < count($parentUuids)) {
188
            $parents = $this->repository->findByIds($parentUuids);
189
        }
190
191
        $aggregation = $result->getAggregation('creatorId');
192
        $creatorIds = [];
193
        foreach ($aggregation->getBuckets() as $bucket) {
194
            $creatorIds[] = $bucket->getValue();
195
        }
196
197
        $creators = null;
198
        if (0 < count($creatorIds)) {
199
            $creators = $this->userRepository->findBy(['id' => $creatorIds]);
200
        }
201
202
        return iterator_to_array(new ResultIterator($result, $parents, $creators));
203
    }
204
205
    /**
206
     * @param string $query
207
     * @param array $fields
208
     *
209
     * @return Search
210
     */
211
    private function createQueryForSearch($query = null, $fields = null)
212
    {
213
        $search = $this->repository->createSearch()->addQuery(new MatchAllQuery());
214
215
        if (isset($query)) {
216
            $boolQuery = new BoolQuery();
217
218
            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...
219
                $boolQuery->add(new WildcardQuery($field, '*' . $query . '*'), BoolQuery::SHOULD);
220
            }
221
222
            $search->addQuery($boolQuery);
223
        }
224
225
        return $search;
226
    }
227
}
228