Completed
Push — feature/EVO-5751-mongodb-3.x ( f7410f...d456eb )
by Lucas
67:06 queued 60:09
created

DocumentModel::find()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
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\Rql\Node\SearchNode;
11
use Graviton\SchemaBundle\Model\SchemaModel;
12
use Graviton\SecurityBundle\Entities\SecurityUser;
13
use Symfony\Bridge\Monolog\Logger;
14
use Symfony\Component\HttpFoundation\Request;
15
use Doctrine\ODM\MongoDB\Query\Builder;
16
use Graviton\Rql\Visitor\MongoOdm as Visitor;
17
use Xiag\Rql\Parser\Node\LimitNode;
18
use Xiag\Rql\Parser\Node\Query\AbstractLogicOperatorNode;
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
use \Doctrine\ODM\MongoDB\Query\Builder as MongoBuilder;
25
26
/**
27
 * Use doctrine odm as backend
28
 *
29
 * @author  List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
30
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
31
 * @link    http://swisscom.ch
32
 */
33
class DocumentModel extends SchemaModel implements ModelInterface
34
{
35
    /**
36
     * @var string
37
     */
38
    protected $description;
39
    /**
40
     * @var string[]
41
     */
42
    protected $fieldTitles;
43
    /**
44
     * @var string[]
45
     */
46
    protected $fieldDescriptions;
47
    /**
48
     * @var string[]
49
     */
50
    protected $requiredFields = array();
51
    /**
52
     * @var string[]
53
     */
54
    protected $searchableFields = array();
55
    /**
56
     * @var DocumentRepository
57
     */
58
    private $repository;
59
    /**
60
     * @var Visitor
61
     */
62
    private $visitor;
63
    /**
64
     * @var array
65
     */
66
    protected $notModifiableOriginRecords;
67
    /**
68
     * @var  integer
69
     */
70
    private $paginationDefaultLimit;
71
72
    /**
73
     * @var boolean
74
     */
75
    protected $filterByAuthUser;
76
77
    /**
78
     * @var string
79
     */
80
    protected $filterByAuthField;
81
82
    /**
83
     * @var DocumentManager
84
     */
85
    protected $manager;
86
87
    /**
88
     * @param Visitor $visitor                    rql query visitor
89
     * @param array   $notModifiableOriginRecords strings with not modifiable recordOrigin values
90
     * @param integer $paginationDefaultLimit     amount of data records to be returned when in pagination context
91
     */
92 4
    public function __construct(
93
        Visitor $visitor,
94
        $notModifiableOriginRecords,
95
        $paginationDefaultLimit
96
    ) {
97 4
        parent::__construct();
98 4
        $this->visitor = $visitor;
99 4
        $this->notModifiableOriginRecords = $notModifiableOriginRecords;
100 4
        $this->paginationDefaultLimit = (int) $paginationDefaultLimit;
101 4
    }
102
103
    /**
104
     * get repository instance
105
     *
106
     * @return DocumentRepository
107
     */
108 2
    public function getRepository()
109
    {
110 2
        return $this->repository;
111
    }
112
113
    /**
114
     * create new app model
115
     *
116
     * @param DocumentRepository $repository Repository of countries
117
     *
118
     * @return \Graviton\RestBundle\Model\DocumentModel
119
     */
120 4
    public function setRepository(DocumentRepository $repository)
121
    {
122 4
        $this->repository = $repository;
123 4
        $this->manager = $repository->getDocumentManager();
124
125 4
        return $this;
126
    }
127
128
    /**
129
     * {@inheritDoc}
130
     *
131
     * @param Request        $request The request object
132
     * @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...
133
     * @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...
134
     *
135
     * @return array
136
     */
137
    public function findAll(Request $request, SecurityUser $user = null, SchemaDocument $schema = null)
138
    {
139
        $pageNumber = $request->query->get('page', 1);
140
        $numberPerPage = (int) $request->query->get('perPage', $this->getDefaultLimit());
141
        $startAt = ($pageNumber - 1) * $numberPerPage;
142
143
        /** @var XiagQuery $xiagQuery */
144
        $xiagQuery = $request->attributes->get('rqlQuery');
145
146
        /** @var MongoBuilder $queryBuilder */
147
        $queryBuilder = $this->repository
148
            ->createQueryBuilder();
149
150
        // Setting RQL Query
151
        if ($xiagQuery) {
152
            // Clean up Search rql param and set it as Doctrine query
153
            if ($xiagQuery->getQuery() && $this->hasCustomSearchIndex() && (float) $this->getMongoDBVersion() >= 2.6) {
154
                $searchQueries = $this->buildSearchQuery($xiagQuery, $queryBuilder);
155
                $xiagQuery = $searchQueries['xiagQuery'];
156
                $queryBuilder = $searchQueries['queryBuilder'];
157
            }
158
            $queryBuilder = $this->doRqlQuery(
159
                $queryBuilder,
160
                $xiagQuery
161
            );
162
        } else {
163
            // @todo [lapistano]: seems the offset is missing for this query.
164
            /** @var \Doctrine\ODM\MongoDB\Query\Builder $qb */
165
            $queryBuilder->find($this->repository->getDocumentName());
166
        }
167
168
169
        /** @var LimitNode $rqlLimit */
170
        $rqlLimit = $xiagQuery instanceof XiagQuery ? $xiagQuery->getLimit() : false;
171
172
        // define offset and limit
173
        if (!$rqlLimit || !$rqlLimit->getOffset()) {
174
            $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...
175
        } else {
176
            $startAt = (int) $rqlLimit->getOffset();
177
            $queryBuilder->skip($startAt);
178
        }
179
180
        if (!$rqlLimit || is_null($rqlLimit->getLimit())) {
181
            $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...
182
        } else {
183
            $numberPerPage = (int) $rqlLimit->getLimit();
184
            $queryBuilder->limit($numberPerPage);
185
        }
186
187
        // Limit can not be negative nor null.
188
        if ($numberPerPage < 1) {
189
            throw new RqlSyntaxErrorException('negative or null limit in rql');
190
        }
191
192
        /**
193
         * add a default sort on id if none was specified earlier
194
         *
195
         * not specifying something to sort on leads to very weird cases when fetching references.
196
         */
197
        if (!array_key_exists('sort', $queryBuilder->getQuery()->getQuery())) {
198
            $queryBuilder->sort('_id');
199
        }
200
201
        // run query
202
        $query = $queryBuilder->getQuery();
203
        $records = array_values($query->execute()->toArray());
204
205
        $totalCount = $query->count();
206
        $numPages = (int) ceil($totalCount / $numberPerPage);
207
        $page = (int) ceil($startAt / $numberPerPage) + 1;
208
        if ($numPages > 1) {
209
            $request->attributes->set('paging', true);
210
            $request->attributes->set('page', $page);
211
            $request->attributes->set('numPages', $numPages);
212
            $request->attributes->set('startAt', $startAt);
213
            $request->attributes->set('perPage', $numberPerPage);
214
            $request->attributes->set('totalCount', $totalCount);
215
        }
216
217
        return $records;
218
    }
219
220
    /**
221
     * @param XiagQuery    $xiagQuery    Xiag Builder
222
     * @param MongoBuilder $queryBuilder Mongo Doctrine query builder
223
     * @return array
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use array<string,Query|Builder>.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
224
     */
225
    private function buildSearchQuery(XiagQuery $xiagQuery, MongoBuilder $queryBuilder)
226
    {
227
        $innerQuery = $xiagQuery->getQuery();
228
        $hasSearch = false;
229
        $nodes = [];
230
        if ($innerQuery instanceof AbstractLogicOperatorNode) {
231
            foreach ($innerQuery->getQueries() as $key => $innerRql) {
232
                if ($innerRql instanceof SearchNode) {
233
                    if (!$hasSearch) {
234
                        $searchString = implode(' ', $innerRql->getSearchTerms());
235
                        $queryBuilder->addAnd($queryBuilder->expr()->text($searchString));
236
                        $hasSearch = true;
237
                    }
238
                } else {
239
                    $nodes[] = $innerRql;
240
                }
241
            }
242
        } elseif ($innerQuery instanceof SearchNode) {
243
            $queryBuilder = $this->repository->createQueryBuilder();
244
            $queryBuilder->text(implode(' ', $innerQuery->getSearchTerms()));
245
            $hasSearch = true;
246
        }
247
        // Remove the Search from RQL xiag
248
        if ($hasSearch && $nodes) {
249
            $newXiagQuery = new XiagQuery();
250
            if ($xiagQuery->getLimit()) {
251
                $newXiagQuery->setLimit($xiagQuery->getLimit());
252
            }
253
            if ($xiagQuery->getSelect()) {
254
                $newXiagQuery->setSelect($xiagQuery->getSelect());
255
            }
256
            if ($xiagQuery->getSort()) {
257
                $newXiagQuery->setSort($xiagQuery->getSort());
258
            }
259
            $binderClass = get_class($innerQuery);
260
            /** @var AbstractLogicOperatorNode $newBinder */
261
            $newBinder = new $binderClass();
262
            foreach ($nodes as $node) {
263
                $newBinder->addQuery($node);
264
            }
265
            $newXiagQuery->setQuery($newBinder);
266
            // Reset original query, so that there is no Search param
267
            $xiagQuery = $newXiagQuery;
268
        }
269
        if ($hasSearch) {
270
            $queryBuilder->sortMeta('score', 'textScore');
271
        }
272
        return [
273
            'xiagQuery'     => $xiagQuery,
274
            'queryBuilder'  => $queryBuilder
275
        ];
276
    }
277
278
    /**
279
     * @param string $prefix the prefix for custom text search indexes
280
     * @return bool
281
     * @throws \Doctrine\ODM\MongoDB\MongoDBException
282
     */
283
    private function hasCustomSearchIndex($prefix = 'search')
284
    {
285
        $collection = $this->repository->getDocumentManager()->getDocumentCollection($this->repository->getClassName());
286
        $indexesInfo = $collection->getIndexInfo();
287
        foreach ($indexesInfo as $indexInfo) {
288
            if ($indexInfo['name']==$prefix.$collection->getName().'Index') {
289
                return true;
290
            }
291
        }
292
        return false;
293
    }
294
295
    /**
296
     * @return string the version of the MongoDB as a string
297
     */
298
    private function getMongoDBVersion()
299
    {
300
        $buildInfo = $this->repository->getDocumentManager()->getDocumentDatabase(
301
            $this->repository->getClassName()
302
        )->command(['buildinfo'=>1]);
303
        if (isset($buildInfo['version'])) {
304
            return $buildInfo['version'];
305
        } else {
306
            return "unkown";
307
        }
308
    }
309
310
    /**
311
     * @param object $entity       entity to insert
312
     * @param bool   $returnEntity true to return entity
313
     * @param bool   $doFlush      if we should flush or not after insert
314
     *
315
     * @return Object|null
316
     */
317 1
    public function insertRecord($entity, $returnEntity = true, $doFlush = true)
318
    {
319
        $this->manager->persist($entity);
320
321
        if ($doFlush) {
322
            $this->manager->flush($entity);
323
        }
324
        if ($returnEntity) {
325
            return $this->find($entity->getId());
326 1
        }
327
    }
328
329
    /**
330
     * @param string $documentId id of entity to find
331
     *
332
     * @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...
333
     */
334 4
    public function find($documentId)
335
    {
336 4
        return $this->repository->find($documentId);
337
    }
338
339
    /**
340
     * {@inheritDoc}
341
     *
342
     * @param string $documentId   id of entity to update
343
     * @param Object $entity       new entity
344
     * @param bool   $returnEntity true to return entity
345
     *
346
     * @return Object|null
347
     */
348 2
    public function updateRecord($documentId, $entity, $returnEntity = true)
349
    {
350 2
        if (!is_null($documentId)) {
351 2
            $this->deleteById($documentId);
352
            // detach so odm knows it's gone
353 2
            $this->manager->detach($entity);
354 2
            $this->manager->clear();
355 1
        }
356
357 2
        $entity = $this->manager->merge($entity);
358
359 2
        $this->manager->persist($entity);
360 2
        $this->manager->flush($entity);
361
362 2
        if ($returnEntity) {
363
            return $entity;
364
        }
365 2
    }
366
367
    /**
368
     * {@inheritDoc}
369
     *
370
     * @param string|object $id id of entity to delete or entity instance
371
     *
372
     * @return null|Object
373
     */
374
    public function deleteRecord($id)
375
    {
376
        if (is_object($id)) {
377
            $entity = $id;
378
        } else {
379
            $entity = $this->find($id);
380
        }
381
382
        $return = $entity;
383
        if ($entity) {
384
            $this->checkIfOriginRecord($entity);
385
            $this->manager->remove($entity);
386
            $this->manager->flush();
387
            $return = null;
388
        }
389
390
        return $return;
391
    }
392
393
    /**
394
     * Triggers a flush on the DocumentManager
395
     *
396
     * @param null $document optional document
397
     *
398
     * @return void
399
     */
400
    public function flush($document = null)
401
    {
402
        $this->manager->flush($document);
403
    }
404
405
    /**
406
     * A low level delete without any checks
407
     *
408
     * @param mixed $id record id
409
     *
410
     * @return void
411
     */
412 2
    private function deleteById($id)
413
    {
414 2
        $builder = $this->repository->createQueryBuilder();
415
        $builder
416 2
            ->remove()
417 2
            ->field('id')->equals($id)
418 2
            ->getQuery()
419 2
            ->execute();
420 2
    }
421
422
    /**
423
     * Checks in a performant way if a certain record id exists in the database
424
     *
425
     * @param mixed $id record id
426
     *
427
     * @return bool true if it exists, false otherwise
428
     */
429 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...
430
    {
431 4
        return is_array($this->selectSingleFields($id, ['id'], false));
432
    }
433
434
    /**
435
     * Returns a set of fields from an existing resource in a performant manner.
436
     * If you need to check certain fields on an object (and don't need everything), this
437
     * is a better way to get what you need.
438
     * If the record is not present, you will receive null. If you don't need an hydrated
439
     * instance, make sure to pass false there.
440
     *
441
     * @param mixed $id      record id
442
     * @param array $fields  list of fields you need.
443
     * @param bool  $hydrate whether to hydrate object or not
444
     *
445
     * @return array|null|object
446
     */
447 4
    public function selectSingleFields($id, array $fields, $hydrate = true)
448
    {
449 4
        $builder = $this->repository->createQueryBuilder();
450 4
        $idField = $this->repository->getClassMetadata()->getIdentifier()[0];
451
452
        $record = $builder
453 4
            ->field($idField)->equals($id)
454 4
            ->select($fields)
455 4
            ->hydrate($hydrate)
456 4
            ->getQuery()
457 4
            ->getSingleResult();
458
459 4
        return $record;
460
    }
461
462
    /**
463
     * get classname of entity
464
     *
465
     * @return string|null
466
     */
467 4
    public function getEntityClass()
468
    {
469 4
        if ($this->repository instanceof DocumentRepository) {
470 4
            return $this->repository->getDocumentName();
471
        }
472
473
        return null;
474
    }
475
476
    /**
477
     * {@inheritDoc}
478
     *
479
     * Currently this is being used to build the route id used for redirecting
480
     * to newly made documents. It might benefit from having a different name
481
     * for those purposes.
482
     *
483
     * We might use a convention based mapping here:
484
     * Graviton\CoreBundle\Document\App -> mongodb://graviton_core
485
     * Graviton\CoreBundle\Entity\Table -> mysql://graviton_core
486
     *
487
     * @todo implement this in a more convention based manner
488
     *
489
     * @return string
490
     */
491
    public function getConnectionName()
492
    {
493
        $bundle = strtolower(substr(explode('\\', get_class($this))[1], 0, -6));
494
495
        return 'graviton.' . $bundle;
496
    }
497
498
    /**
499
     * Does the actual query using the RQL Bundle.
500
     *
501
     * @param Builder $queryBuilder Doctrine ODM QueryBuilder
502
     * @param Query   $query        query from parser
503
     *
504
     * @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...
505
     */
506
    protected function doRqlQuery($queryBuilder, Query $query)
507
    {
508
        $this->visitor->setBuilder($queryBuilder);
509
510
        return $this->visitor->visit($query);
511
    }
512
513
    /**
514
     * Checks the recordOrigin attribute of a record and will throw an exception if value is not allowed
515
     *
516
     * @param Object $record record
517
     *
518
     * @return void
519
     */
520
    protected function checkIfOriginRecord($record)
521
    {
522
        if ($record instanceof RecordOriginInterface
523
            && !$record->isRecordOriginModifiable()
524
        ) {
525
            $values = $this->notModifiableOriginRecords;
526
            $originValue = strtolower(trim($record->getRecordOrigin()));
527
528
            if (in_array($originValue, $values)) {
529
                $msg = sprintf("Must not be one of the following keywords: %s", implode(', ', $values));
530
531
                throw new RecordOriginModifiedException($msg);
532
            }
533
        }
534
    }
535
536
    /**
537
     * Determines the configured amount fo data records to be returned in pagination context.
538
     *
539
     * @return int
540
     */
541
    private function getDefaultLimit()
542
    {
543
        if (0 < $this->paginationDefaultLimit) {
544
            return $this->paginationDefaultLimit;
545
        }
546
547
        return 10;
548
    }
549
550
    /**
551
     * @param Boolean $active active
552
     * @param String  $field  field
553
     * @return void
554
     */
555 4
    public function setFilterByAuthUser($active, $field)
556
    {
557 4
        $this->filterByAuthUser = is_bool($active) ? $active : false;
558 4
        $this->filterByAuthField = $field;
559 4
    }
560
}
561