Completed
Push — feature/EVO-5751-text-search-t... ( e9be3c )
by
unknown
12:00
created

DocumentModel::findAll()   D

Complexity

Conditions 18
Paths 224

Size

Total Lines 101
Code Lines 58

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 342

Importance

Changes 8
Bugs 0 Features 0
Metric Value
c 8
b 0
f 0
dl 0
loc 101
ccs 0
cts 64
cp 0
rs 4.106
cc 18
eloc 58
nc 224
nop 3
crap 342

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Use doctrine odm as backend
4
 */
5
6
namespace Graviton\RestBundle\Model;
7
8
use Doctrine\ODM\MongoDB\DocumentManager;
9
use Doctrine\ODM\MongoDB\DocumentRepository;
10
use Graviton\RestBundle\Service\RqlTranslator;
11
use Graviton\Rql\Node\SearchNode;
12
use Graviton\SchemaBundle\Model\SchemaModel;
13
use Graviton\SecurityBundle\Entities\SecurityUser;
14
use Symfony\Bridge\Monolog\Logger;
15
use Symfony\Component\HttpFoundation\Request;
16
use Doctrine\ODM\MongoDB\Query\Builder;
17
use Graviton\Rql\Visitor\MongoOdm as Visitor;
18
use Xiag\Rql\Parser\Node\LimitNode;
19
use Xiag\Rql\Parser\Query;
20
use Graviton\ExceptionBundle\Exception\RecordOriginModifiedException;
21
use Xiag\Rql\Parser\Exception\SyntaxErrorException as RqlSyntaxErrorException;
22
use Graviton\SchemaBundle\Document\Schema as SchemaDocument;
23
use Xiag\Rql\Parser\Query as XiagQuery;
24
25
/**
26
 * Use doctrine odm as backend
27
 *
28
 * @author  List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
29
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
30
 * @link    http://swisscom.ch
31
 */
32
class DocumentModel extends SchemaModel implements ModelInterface
33
{
34
    /**
35
     * @var string
36
     */
37
    protected $description;
38
    /**
39
     * @var string[]
40
     */
41
    protected $fieldTitles;
42
    /**
43
     * @var string[]
44
     */
45
    protected $fieldDescriptions;
46
    /**
47
     * @var string[]
48
     */
49
    protected $requiredFields = array();
50
    /**
51
     * @var string[]
52
     */
53
    protected $searchableFields = array();
54
    /**
55
     * @var DocumentRepository
56
     */
57
    private $repository;
58
    /**
59
     * @var Visitor
60
     */
61
    private $visitor;
62
    /**
63
     * @var array
64
     */
65
    protected $notModifiableOriginRecords;
66
    /**
67
     * @var  integer
68
     */
69
    private $paginationDefaultLimit;
70
71
    /**
72
     * @var boolean
73
     */
74
    protected $filterByAuthUser;
75
76
    /**
77
     * @var string
78
     */
79
    protected $filterByAuthField;
80
81
    /**
82
     * @var RqlTranslator
83
     */
84
    protected $translator;
85
86
    /**
87
     * @var DocumentManager
88
     */
89
    protected $manager;
90
91
    /**
92
     * @param Visitor       $visitor                    rql query visitor
93
     * @param RqlTranslator $translator                 Translator for query modification
94
     * @param array         $notModifiableOriginRecords strings with not modifiable recordOrigin values
95
     * @param integer       $paginationDefaultLimit     amount of data records to be returned when in pagination context
96
     */
97 4
    public function __construct(
98
        Visitor $visitor,
99
        RqlTranslator $translator,
100
        $notModifiableOriginRecords,
101
        $paginationDefaultLimit
102
    ) {
103 4
        parent::__construct();
104 4
        $this->visitor = $visitor;
105 4
        $this->translator = $translator;
106 4
        $this->notModifiableOriginRecords = $notModifiableOriginRecords;
107 4
        $this->paginationDefaultLimit = (int) $paginationDefaultLimit;
108 4
    }
109
110
    /**
111
     * get repository instance
112
     *
113
     * @return DocumentRepository
114
     */
115 2
    public function getRepository()
116
    {
117 2
        return $this->repository;
118
    }
119
120
    /**
121
     * create new app model
122
     *
123
     * @param DocumentRepository $repository Repository of countries
124
     *
125
     * @return \Graviton\RestBundle\Model\DocumentModel
126
     */
127 4
    public function setRepository(DocumentRepository $repository)
128
    {
129 4
        $this->repository = $repository;
130 4
        $this->manager = $repository->getDocumentManager();
131
132 4
        return $this;
133
    }
134
135
    /**
136
     * {@inheritDoc}
137
     *
138
     * @param Request        $request The request object
139
     * @param SecurityUser   $user    SecurityUser Object
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user not be null|SecurityUser?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
140
     * @param SchemaDocument $schema  Schema model used for search fields extraction
0 ignored issues
show
Documentation introduced by
Should the type for parameter $schema not be null|SchemaDocument?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
141
     *
142
     * @return array
143
     */
144
    public function findAll(Request $request, SecurityUser $user = null, SchemaDocument $schema = null)
145
    {
146
        $pageNumber = $request->query->get('page', 1);
147
        $numberPerPage = (int) $request->query->get('perPage', $this->getDefaultLimit());
148
        $startAt = ($pageNumber - 1) * $numberPerPage;
149
        // Only 1 search text node allowed.
150
        $hasSearch = false;
151
        $queryParams = new XiagQuery();
152
153
        /** @var \Doctrine\ODM\MongoDB\Query\Builder $queryBuilder */
154
        $queryBuilder = $this->repository
155
            ->createQueryBuilder();
156
157
        if ($this->filterByAuthUser && $user && $user->hasRole(SecurityUser::ROLE_USER)) {
158
            $queryBuilder->field($this->filterByAuthField)->equals($user->getUser()->getId());
159
        }
160
161
        // *** do we have an RQL expression, do we need to filter data?
162
        if ($request->attributes->get('hasRql', false)) {
163
            $innerQuery = $request->attributes->get('rqlQuery')->getQuery();
164
165
            if ($innerQuery instanceof SearchNode &&
166
                (float) $this->getMongoDBVersion() >= 2.6
167
                && $this->hasCustomSearchIndex()
168
            ) {
169
                $queryBuilder->text(implode("&", $innerQuery->getSearchTerms()));
170
                $hasSearch = true;
171
            } else {
172
                // do rql filtering
173
                $searchableFields = $this->getSearchableFields();
174
                if (!is_null($schema)) {
175
                    $searchableFields = $schema->getSearchable();
176
                }
177
                $queryBuilder = $this->doRqlQuery(
178
                    $queryBuilder,
179
                    $this->translator->translateSearchQuery(
180
                        $request->attributes->get('rqlQuery'),
181
                        $searchableFields
0 ignored issues
show
Bug introduced by
It seems like $searchableFields defined by $schema->getSearchable() on line 175 can also be of type null; however, Graviton\RestBundle\Serv...:translateSearchQuery() does only seem to accept array, 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...
182
                    )
183
                );
184
            }
185
        } else {
186
            // @todo [lapistano]: seems the offset is missing for this query.
187
            /** @var \Doctrine\ODM\MongoDB\Query\Builder $qb */
188
            $queryBuilder->find($this->repository->getDocumentName());
189
        }
190
191
        /** @var LimitNode $rqlLimit */
192
        $rqlLimit = $queryParams->getLimit();
193
        
194
        // define offset and limit
195
        if (!$rqlLimit || !$rqlLimit->getOffset()) {
196
            $queryBuilder->skip($startAt);
0 ignored issues
show
Bug introduced by
The method skip does only exist in Doctrine\ODM\MongoDB\Query\Builder, but not in Doctrine\ODM\MongoDB\Query\Expr.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
197
        } else {
198
            $startAt = (int) $queryParams->getLimit()->getOffset();
199
            $queryBuilder->skip($startAt);
200
        }
201
202
        if (!$rqlLimit || is_null($rqlLimit->getLimit())) {
203
            $queryBuilder->limit($numberPerPage);
0 ignored issues
show
Bug introduced by
The method limit does only exist in Doctrine\ODM\MongoDB\Query\Builder, but not in Doctrine\ODM\MongoDB\Query\Expr.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
204
        } else {
205
            $numberPerPage = (int) $queryParams->getLimit()->getLimit();
206
            $queryBuilder->limit($numberPerPage);
207
        }
208
209
        // Limit can not be negative nor null.
210
        if ($numberPerPage < 1) {
211
            throw new RqlSyntaxErrorException('negative or null limit in rql');
212
        }
213
214
        /**
215
         * add a default sort on id if none was specified earlier
216
         *
217
         * not specifying something to sort on leads to very weird cases when fetching references
218
         * If search node, sort by Score
219
         * TODO Review this sorting, not 100% sure
220
         */
221
        if ($hasSearch && !array_key_exists('sort', $queryBuilder->getQuery()->getQuery())) {
222
            $queryBuilder->sortMeta('score', 'textScore');
0 ignored issues
show
Bug introduced by
The method sortMeta does only exist in Doctrine\ODM\MongoDB\Query\Builder, but not in Doctrine\ODM\MongoDB\Query\Expr.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
223
        } elseif (!array_key_exists('sort', $queryBuilder->getQuery()->getQuery())) {
224
            $queryBuilder->sort('_id');
225
        }
226
227
        // run query
228
        $query = $queryBuilder->getQuery();
229
        $records = array_values($query->execute()->toArray());
230
231
        $totalCount = $query->count();
232
        $numPages = (int) ceil($totalCount / $numberPerPage);
233
        $page = (int) ceil($startAt / $numberPerPage) + 1;
234
        if ($numPages > 1) {
235
            $request->attributes->set('paging', true);
236
            $request->attributes->set('page', $page);
237
            $request->attributes->set('numPages', $numPages);
238
            $request->attributes->set('startAt', $startAt);
239
            $request->attributes->set('perPage', $numberPerPage);
240
            $request->attributes->set('totalCount', $totalCount);
241
        }
242
243
        return $records;
244
    }
245
246
    /**
247
     * @param string $prefix the prefix for custom text search indexes
248
     * @return bool
249
     * @throws \Doctrine\ODM\MongoDB\MongoDBException
250
     */
251
    private function hasCustomSearchIndex($prefix = 'search')
252
    {
253
        $collection = $this->repository->getDocumentManager()->getDocumentCollection($this->repository->getClassName());
254
        $indexesInfo = $collection->getIndexInfo();
255
        foreach ($indexesInfo as $indexInfo) {
256
            if ($indexInfo['name']==$prefix.$collection->getName().'Index') {
257
                return true;
258
            }
259
        }
260
        return false;
261
    }
262
263
    /**
264
     * @return string the version of the MongoDB as a string
265
     */
266
    private function getMongoDBVersion()
267
    {
268
        $buildInfo = $this->repository->getDocumentManager()->getDocumentDatabase(
269
            $this->repository->getClassName()
270
        )->command(['buildinfo'=>1]);
271
        if (isset($buildInfo['version'])) {
272
            return $buildInfo['version'];
273
        } else {
274
            return "unkown";
275
        }
276
    }
277
278
    /**
279
     * @param object $entity       entity to insert
280
     * @param bool   $returnEntity true to return entity
281
     * @param bool   $doFlush      if we should flush or not after insert
282
     *
283
     * @return Object|null
284
     */
285
    public function insertRecord($entity, $returnEntity = true, $doFlush = true)
286
    {
287
        $this->checkIfOriginRecord($entity);
288
        $this->manager->persist($entity);
289
290
        if ($doFlush) {
291
            $this->manager->flush($entity);
292
        }
293
        if ($returnEntity) {
294
            return $this->find($entity->getId());
295
        }
296
    }
297
298
    /**
299
     * @param string $documentId id of entity to find
300
     *
301
     * @return Object
0 ignored issues
show
Documentation introduced by
Should the return type not be object|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
302
     */
303 4
    public function find($documentId)
304
    {
305 4
        return $this->repository->find($documentId);
306
    }
307
308
    /**
309
     * {@inheritDoc}
310
     *
311
     * @param string $documentId   id of entity to update
312
     * @param Object $entity       new entity
313
     * @param bool   $returnEntity true to return entity
314
     *
315
     * @return Object|null
316
     */
317 3
    public function updateRecord($documentId, $entity, $returnEntity = true)
318
    {
319
        // In both cases the document attribute named originRecord must not be 'core'
320 2
        $this->checkIfOriginRecord($entity);
321 2
        $this->checkIfOriginRecord($this->selectSingleFields($documentId, ['recordOrigin']));
0 ignored issues
show
Bug introduced by
It seems like $this->selectSingleField... array('recordOrigin')) targeting Graviton\RestBundle\Mode...l::selectSingleFields() can also be of type array or null; however, Graviton\RestBundle\Mode...::checkIfOriginRecord() does only seem to accept object, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
322
323 2
        if (!is_null($documentId)) {
324 2
            $this->deleteById($documentId);
325
            // detach so odm knows it's gone
326 3
            $this->manager->detach($entity);
327 2
            $this->manager->clear();
328 1
        }
329
330 2
        $entity = $this->manager->merge($entity);
331
332 2
        $this->manager->persist($entity);
333 2
        $this->manager->flush($entity);
334
335 2
        if ($returnEntity) {
336
            return $entity;
337
        }
338 2
    }
339
340
    /**
341
     * {@inheritDoc}
342
     *
343
     * @param string|object $id id of entity to delete or entity instance
344
     *
345
     * @return null|Object
346
     */
347
    public function deleteRecord($id)
348
    {
349
        if (is_object($id)) {
350
            $entity = $id;
351
        } else {
352
            $entity = $this->find($id);
353
        }
354
355
        $return = $entity;
356
        if ($entity) {
357
            $this->checkIfOriginRecord($entity);
358
            $this->manager->remove($entity);
359
            $this->manager->flush();
360
            $return = null;
361
        }
362
363
        return $return;
364
    }
365
366
    /**
367
     * Triggers a flush on the DocumentManager
368
     *
369
     * @param null $document optional document
370
     *
371
     * @return void
372
     */
373
    public function flush($document = null)
374
    {
375
        $this->manager->flush($document);
376
    }
377
378
    /**
379
     * A low level delete without any checks
380
     *
381
     * @param mixed $id record id
382
     *
383
     * @return void
384
     */
385 2
    private function deleteById($id)
386
    {
387 2
        $builder = $this->repository->createQueryBuilder();
388
        $builder
389 2
            ->remove()
390 2
            ->field('id')->equals($id)
391 2
            ->getQuery()
392 2
            ->execute();
393 2
    }
394
395
    /**
396
     * Checks in a performant way if a certain record id exists in the database
397
     *
398
     * @param mixed $id record id
399
     *
400
     * @return bool true if it exists, false otherwise
401
     */
402 4
    public function recordExists($id)
0 ignored issues
show
Coding Style introduced by
function recordExists() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
403
    {
404 4
        return is_array($this->selectSingleFields($id, ['id'], false));
405
    }
406
407
    /**
408
     * Returns a set of fields from an existing resource in a performant manner.
409
     * If you need to check certain fields on an object (and don't need everything), this
410
     * is a better way to get what you need.
411
     * If the record is not present, you will receive null. If you don't need an hydrated
412
     * instance, make sure to pass false there.
413
     *
414
     * @param mixed $id      record id
415
     * @param array $fields  list of fields you need.
416
     * @param bool  $hydrate whether to hydrate object or not
417
     *
418
     * @return array|null|object
419
     */
420 4
    public function selectSingleFields($id, array $fields, $hydrate = true)
421
    {
422 4
        $builder = $this->repository->createQueryBuilder();
423 4
        $idField = $this->repository->getClassMetadata()->getIdentifier()[0];
424
425
        $record = $builder
426 4
            ->field($idField)->equals($id)
427 4
            ->select($fields)
428 4
            ->hydrate($hydrate)
429 4
            ->getQuery()
430 4
            ->getSingleResult();
431
432 4
        return $record;
433
    }
434
435
    /**
436
     * get classname of entity
437
     *
438
     * @return string|null
439
     */
440 4
    public function getEntityClass()
441
    {
442 4
        if ($this->repository instanceof DocumentRepository) {
443 4
            return $this->repository->getDocumentName();
444
        }
445
446
        return null;
447
    }
448
449
    /**
450
     * {@inheritDoc}
451
     *
452
     * Currently this is being used to build the route id used for redirecting
453
     * to newly made documents. It might benefit from having a different name
454
     * for those purposes.
455
     *
456
     * We might use a convention based mapping here:
457
     * Graviton\CoreBundle\Document\App -> mongodb://graviton_core
458
     * Graviton\CoreBundle\Entity\Table -> mysql://graviton_core
459
     *
460
     * @todo implement this in a more convention based manner
461
     *
462
     * @return string
463
     */
464
    public function getConnectionName()
465
    {
466
        $bundle = strtolower(substr(explode('\\', get_class($this))[1], 0, -6));
467
468
        return 'graviton.' . $bundle;
469
    }
470
471
    /**
472
     * Does the actual query using the RQL Bundle.
473
     *
474
     * @param Builder $queryBuilder Doctrine ODM QueryBuilder
475
     * @param Query   $query        query from parser
476
     *
477
     * @return array
0 ignored issues
show
Documentation introduced by
Should the return type not be Builder|\Doctrine\ODM\MongoDB\Query\Expr?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
478
     */
479
    protected function doRqlQuery($queryBuilder, Query $query)
480
    {
481
        $this->visitor->setBuilder($queryBuilder);
482
483
        return $this->visitor->visit($query);
484
    }
485
486
    /**
487
     * Checks the recordOrigin attribute of a record and will throw an exception if value is not allowed
488
     *
489
     * @param Object $record record
490
     *
491
     * @return void
492
     */
493 14
    protected function checkIfOriginRecord($record)
494
    {
495 7
        if ($record instanceof RecordOriginInterface
496 14
            && !$record->isRecordOriginModifiable()
497 7
        ) {
498 6
            $values = $this->notModifiableOriginRecords;
499 6
            $originValue = strtolower(trim($record->getRecordOrigin()));
500
501 6
            if (in_array($originValue, $values)) {
502 2
                $msg = sprintf("Must not be one of the following keywords: %s", implode(', ', $values));
503
504 2
                throw new RecordOriginModifiedException($msg);
505
            }
506 2
        }
507 12
    }
508
509
    /**
510
     * Determines the configured amount fo data records to be returned in pagination context.
511
     *
512
     * @return int
513
     */
514
    private function getDefaultLimit()
515
    {
516
        if (0 < $this->paginationDefaultLimit) {
517
            return $this->paginationDefaultLimit;
518
        }
519
520
        return 10;
521
    }
522
523
    /**
524
     * @param Boolean $active active
525
     * @param String  $field  field
526
     * @return void
527
     */
528 4
    public function setFilterByAuthUser($active, $field)
529
    {
530 4
        $this->filterByAuthUser = is_bool($active) ? $active : false;
531 4
        $this->filterByAuthField = $field;
532 4
    }
533
}
534