Completed
Push — feature/EVO-6505-update-jsonpa... ( 0fbd37...da422d )
by Narcotic
30:28 queued 24:26
created

DocumentModel::getMongoDBVersion()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 11
ccs 0
cts 7
cp 0
rs 9.4285
cc 2
eloc 8
nc 2
nop 0
crap 6
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->checkIfOriginRecord($entity);
320
        $this->manager->persist($entity);
321
322
        if ($doFlush) {
323
            $this->manager->flush($entity);
324
        }
325
        if ($returnEntity) {
326 1
            return $this->find($entity->getId());
327
        }
328
    }
329
330
    /**
331
     * @param string $documentId id of entity to find
332
     *
333
     * @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...
334
     */
335 4
    public function find($documentId)
336
    {
337 4
        return $this->repository->find($documentId);
338
    }
339
340
    /**
341
     * {@inheritDoc}
342
     *
343
     * @param string $documentId   id of entity to update
344
     * @param Object $entity       new entity
345
     * @param bool   $returnEntity true to return entity
346
     *
347
     * @return Object|null
348
     */
349 2
    public function updateRecord($documentId, $entity, $returnEntity = true)
350
    {
351
        // In both cases the document attribute named originRecord must not be 'core'
352 2
        $this->checkIfOriginRecord($entity);
353 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...
354
355 2
        if (!is_null($documentId)) {
356 2
            $this->deleteById($documentId);
357
            // detach so odm knows it's gone
358 2
            $this->manager->detach($entity);
359 2
            $this->manager->clear();
360 1
        }
361
362 2
        $entity = $this->manager->merge($entity);
363
364 2
        $this->manager->persist($entity);
365 2
        $this->manager->flush($entity);
366
367 2
        if ($returnEntity) {
368
            return $entity;
369
        }
370 2
    }
371
372
    /**
373
     * {@inheritDoc}
374
     *
375
     * @param string|object $id id of entity to delete or entity instance
376
     *
377
     * @return null|Object
378
     */
379
    public function deleteRecord($id)
380
    {
381
        if (is_object($id)) {
382
            $entity = $id;
383
        } else {
384
            $entity = $this->find($id);
385
        }
386
387
        $return = $entity;
388
        if ($entity) {
389
            $this->checkIfOriginRecord($entity);
390
            $this->manager->remove($entity);
391
            $this->manager->flush();
392
            $return = null;
393
        }
394
395
        return $return;
396
    }
397
398
    /**
399
     * Triggers a flush on the DocumentManager
400
     *
401
     * @param null $document optional document
402
     *
403
     * @return void
404
     */
405
    public function flush($document = null)
406
    {
407
        $this->manager->flush($document);
408
    }
409
410
    /**
411
     * A low level delete without any checks
412
     *
413
     * @param mixed $id record id
414
     *
415
     * @return void
416
     */
417 2
    private function deleteById($id)
418
    {
419 2
        $builder = $this->repository->createQueryBuilder();
420
        $builder
421 2
            ->remove()
422 2
            ->field('id')->equals($id)
423 2
            ->getQuery()
424 2
            ->execute();
425 2
    }
426
427
    /**
428
     * Checks in a performant way if a certain record id exists in the database
429
     *
430
     * @param mixed $id record id
431
     *
432
     * @return bool true if it exists, false otherwise
433
     */
434 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...
435
    {
436 4
        return is_array($this->selectSingleFields($id, ['id'], false));
437
    }
438
439
    /**
440
     * Returns a set of fields from an existing resource in a performant manner.
441
     * If you need to check certain fields on an object (and don't need everything), this
442
     * is a better way to get what you need.
443
     * If the record is not present, you will receive null. If you don't need an hydrated
444
     * instance, make sure to pass false there.
445
     *
446
     * @param mixed $id      record id
447
     * @param array $fields  list of fields you need.
448
     * @param bool  $hydrate whether to hydrate object or not
449
     *
450
     * @return array|null|object
451
     */
452 4
    public function selectSingleFields($id, array $fields, $hydrate = true)
453
    {
454 4
        $builder = $this->repository->createQueryBuilder();
455 4
        $idField = $this->repository->getClassMetadata()->getIdentifier()[0];
456
457
        $record = $builder
458 4
            ->field($idField)->equals($id)
459 4
            ->select($fields)
460 4
            ->hydrate($hydrate)
461 4
            ->getQuery()
462 4
            ->getSingleResult();
463
464 4
        return $record;
465
    }
466
467
    /**
468
     * get classname of entity
469
     *
470
     * @return string|null
471
     */
472 4
    public function getEntityClass()
473
    {
474 4
        if ($this->repository instanceof DocumentRepository) {
475 4
            return $this->repository->getDocumentName();
476
        }
477
478
        return null;
479
    }
480
481
    /**
482
     * {@inheritDoc}
483
     *
484
     * Currently this is being used to build the route id used for redirecting
485
     * to newly made documents. It might benefit from having a different name
486
     * for those purposes.
487
     *
488
     * We might use a convention based mapping here:
489
     * Graviton\CoreBundle\Document\App -> mongodb://graviton_core
490
     * Graviton\CoreBundle\Entity\Table -> mysql://graviton_core
491
     *
492
     * @todo implement this in a more convention based manner
493
     *
494
     * @return string
495
     */
496
    public function getConnectionName()
497
    {
498
        $bundle = strtolower(substr(explode('\\', get_class($this))[1], 0, -6));
499
500
        return 'graviton.' . $bundle;
501
    }
502
503
    /**
504
     * Does the actual query using the RQL Bundle.
505
     *
506
     * @param Builder $queryBuilder Doctrine ODM QueryBuilder
507
     * @param Query   $query        query from parser
508
     *
509
     * @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...
510
     */
511
    protected function doRqlQuery($queryBuilder, Query $query)
512
    {
513
        $this->visitor->setBuilder($queryBuilder);
514
515
        return $this->visitor->visit($query);
516
    }
517
518
    /**
519
     * Checks the recordOrigin attribute of a record and will throw an exception if value is not allowed
520
     *
521
     * @param Object $record record
522
     *
523
     * @return void
524
     */
525 14
    protected function checkIfOriginRecord($record)
526
    {
527 7
        if ($record instanceof RecordOriginInterface
528 14
            && !$record->isRecordOriginModifiable()
529 7
        ) {
530 6
            $values = $this->notModifiableOriginRecords;
531 6
            $originValue = strtolower(trim($record->getRecordOrigin()));
532
533 6
            if (in_array($originValue, $values)) {
534 2
                $msg = sprintf("Must not be one of the following keywords: %s", implode(', ', $values));
535
536 2
                throw new RecordOriginModifiedException($msg);
537
            }
538 2
        }
539 12
    }
540
541
    /**
542
     * Determines the configured amount fo data records to be returned in pagination context.
543
     *
544
     * @return int
545
     */
546
    private function getDefaultLimit()
547
    {
548
        if (0 < $this->paginationDefaultLimit) {
549
            return $this->paginationDefaultLimit;
550
        }
551
552
        return 10;
553
    }
554
555
    /**
556
     * @param Boolean $active active
557
     * @param String  $field  field
558
     * @return void
559
     */
560 4
    public function setFilterByAuthUser($active, $field)
561
    {
562 4
        $this->filterByAuthUser = is_bool($active) ? $active : false;
563 4
        $this->filterByAuthField = $field;
564 4
    }
565
}
566