Completed
Push — feature/EVO-5751-text-index-mo... ( 1e4bc7 )
by
unknown
14:51 queued 02:37
created

DocumentModel::getConnectionName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
ccs 0
cts 3
cp 0
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
crap 2
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\Node\Query\AbstractLogicOperatorNode;
20
use Xiag\Rql\Parser\Query;
21
use Graviton\ExceptionBundle\Exception\RecordOriginModifiedException;
22
use Xiag\Rql\Parser\Exception\SyntaxErrorException as RqlSyntaxErrorException;
23
use Graviton\SchemaBundle\Document\Schema as SchemaDocument;
24
use Xiag\Rql\Parser\Query as XiagQuery;
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 RqlTranslator
84
     */
85
    protected $translator;
86
87
    /**
88
     * @var DocumentManager
89
     */
90
    protected $manager;
91
92
    /**
93
     * @param Visitor       $visitor                    rql query visitor
94
     * @param RqlTranslator $translator                 Translator for query modification
95
     * @param array         $notModifiableOriginRecords strings with not modifiable recordOrigin values
96
     * @param integer       $paginationDefaultLimit     amount of data records to be returned when in pagination context
97
     */
98 4
    public function __construct(
99
        Visitor $visitor,
100
        RqlTranslator $translator,
101
        $notModifiableOriginRecords,
102
        $paginationDefaultLimit
103
    ) {
104 4
        parent::__construct();
105 4
        $this->visitor = $visitor;
106 4
        $this->translator = $translator;
107 4
        $this->notModifiableOriginRecords = $notModifiableOriginRecords;
108 4
        $this->paginationDefaultLimit = (int) $paginationDefaultLimit;
109 4
    }
110
111
    /**
112
     * get repository instance
113
     *
114
     * @return DocumentRepository
115
     */
116 2
    public function getRepository()
117
    {
118 2
        return $this->repository;
119
    }
120
121
    /**
122
     * create new app model
123
     *
124
     * @param DocumentRepository $repository Repository of countries
125
     *
126
     * @return \Graviton\RestBundle\Model\DocumentModel
127
     */
128 4
    public function setRepository(DocumentRepository $repository)
129
    {
130 4
        $this->repository = $repository;
131 4
        $this->manager = $repository->getDocumentManager();
132
133 4
        return $this;
134
    }
135
136
    /**
137
     * {@inheritDoc}
138
     *
139
     * @param Request        $request The request object
140
     * @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...
141
     * @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...
142
     *
143
     * @return array
144
     */
145
    public function findAll(Request $request, SecurityUser $user = null, SchemaDocument $schema = null)
146
    {
147
        $pageNumber = $request->query->get('page', 1);
148
        $numberPerPage = (int) $request->query->get('perPage', $this->getDefaultLimit());
149
        $startAt = ($pageNumber - 1) * $numberPerPage;
150
        // Only 1 search text node allowed.
151
        $hasSearch = false;
152
        /** @var XiagQuery $queryParams */
153
        $xiagQuery = $request->attributes->get('rqlQuery');
154
155
        /** @var \Doctrine\ODM\MongoDB\Query\Builder $queryBuilder */
156
        $queryBuilder = $this->repository
157
            ->createQueryBuilder();
158
159
        // *** do we have an RQL expression, do we need to filter data?
160
        if ($request->attributes->get('hasRql', false)) {
161
            $innerQuery = $request->attributes->get('rqlQuery')->getQuery();
162
            if ($this->hasCustomSearchIndex() && (float) $this->getMongoDBVersion() >= 2.6) {
163
                if ($innerQuery instanceof AbstractLogicOperatorNode) {
164
                    $queryBuilder = $this->doRqlQuery(
165
                        $queryBuilder,
166
                        $this->translator->translateSearchQuery($xiagQuery, ['_id'])
167
                    );
168
                    foreach ($innerQuery->getQueries() as $innerRql) {
169
                        if (!$hasSearch && $innerRql instanceof SearchNode) {
170
                            $queryBuilder->addAnd(
171
                                $queryBuilder->expr()->text(implode(' ', $innerRql->getSearchTerms()))
0 ignored issues
show
Bug introduced by
The method expr 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...
172
                            );
173
                            $hasSearch = true;
174
                        }
175
                    }
176
                } elseif ($innerQuery instanceof SearchNode) {
177
                    $queryBuilder->text(implode(' ', $innerQuery->getSearchTerms()));
178
                    $hasSearch = true;
179
                }
180
            }
181
        } else {
182
            // @todo [lapistano]: seems the offset is missing for this query.
183
            /** @var \Doctrine\ODM\MongoDB\Query\Builder $qb */
184
            $queryBuilder->find($this->repository->getDocumentName());
185
        }
186
187
        //die(print_r($queryBuilder->getQuery()->getQuery()));
188
189
        /** @var LimitNode $rqlLimit */
190
        $rqlLimit = $xiagQuery instanceof XiagQuery ? $xiagQuery->getLimit() : false;
191
192
        // define offset and limit
193
        if (!$rqlLimit || !$rqlLimit->getOffset()) {
194
            $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...
195
        } else {
196
            $startAt = (int) $rqlLimit->getOffset();
197
            $queryBuilder->skip($startAt);
198
        }
199
200
        if (!$rqlLimit || is_null($rqlLimit->getLimit())) {
201
            $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...
202
        } else {
203
            $numberPerPage = (int) $rqlLimit->getLimit();
204
            $queryBuilder->limit($numberPerPage);
205
        }
206
207
        // Limit can not be negative nor null.
208
        if ($numberPerPage < 1) {
209
            throw new RqlSyntaxErrorException('negative or null limit in rql');
210
        }
211
212
        /**
213
         * add a default sort on id if none was specified earlier
214
         *
215
         * not specifying something to sort on leads to very weird cases when fetching references
216
         * If search node, sort by Score
217
         * TODO Review this sorting, not 100% sure
218
         */
219
        if ($hasSearch && !array_key_exists('sort', $queryBuilder->getQuery()->getQuery())) {
220
            $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...
221
        } elseif (!array_key_exists('sort', $queryBuilder->getQuery()->getQuery())) {
222
            $queryBuilder->sort('_id');
223
        }
224
225
        // run query
226
        $query = $queryBuilder->getQuery();
227
        $records = array_values($query->execute()->toArray());
228
229
        $totalCount = $query->count();
230
        $numPages = (int) ceil($totalCount / $numberPerPage);
231
        $page = (int) ceil($startAt / $numberPerPage) + 1;
232
        if ($numPages > 1) {
233
            $request->attributes->set('paging', true);
234
            $request->attributes->set('page', $page);
235
            $request->attributes->set('numPages', $numPages);
236
            $request->attributes->set('startAt', $startAt);
237
            $request->attributes->set('perPage', $numberPerPage);
238
            $request->attributes->set('totalCount', $totalCount);
239
        }
240
241
        return $records;
242
    }
243
244
    /**
245
     * @param string $prefix the prefix for custom text search indexes
246
     * @return bool
247
     * @throws \Doctrine\ODM\MongoDB\MongoDBException
248
     */
249
    private function hasCustomSearchIndex($prefix = 'search')
250
    {
251
        $collection = $this->repository->getDocumentManager()->getDocumentCollection($this->repository->getClassName());
252
        $indexesInfo = $collection->getIndexInfo();
253
        foreach ($indexesInfo as $indexInfo) {
254
            if ($indexInfo['name']==$prefix.$collection->getName().'Index') {
255
                return true;
256
            }
257
        }
258
        return false;
259
    }
260
261
    /**
262
     * @return string the version of the MongoDB as a string
263
     */
264
    private function getMongoDBVersion()
265
    {
266
        $buildInfo = $this->repository->getDocumentManager()->getDocumentDatabase(
267
            $this->repository->getClassName()
268
        )->command(['buildinfo'=>1]);
269
        if (isset($buildInfo['version'])) {
270
            return $buildInfo['version'];
271
        } else {
272
            return "unkown";
273
        }
274
    }
275
276
    /**
277
     * @param object $entity       entity to insert
278
     * @param bool   $returnEntity true to return entity
279
     * @param bool   $doFlush      if we should flush or not after insert
280
     *
281
     * @return Object|null
282
     */
283
    public function insertRecord($entity, $returnEntity = true, $doFlush = true)
284
    {
285
        $this->checkIfOriginRecord($entity);
286
        $this->manager->persist($entity);
287
288
        if ($doFlush) {
289
            $this->manager->flush($entity);
290
        }
291
        if ($returnEntity) {
292
            return $this->find($entity->getId());
293
        }
294
    }
295
296
    /**
297
     * @param string $documentId id of entity to find
298
     *
299
     * @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...
300
     */
301 4
    public function find($documentId)
302
    {
303 4
        return $this->repository->find($documentId);
304
    }
305
306
    /**
307
     * {@inheritDoc}
308
     *
309
     * @param string $documentId   id of entity to update
310
     * @param Object $entity       new entity
311
     * @param bool   $returnEntity true to return entity
312
     *
313
     * @return Object|null
314
     */
315 3
    public function updateRecord($documentId, $entity, $returnEntity = true)
316
    {
317
        // In both cases the document attribute named originRecord must not be 'core'
318 2
        $this->checkIfOriginRecord($entity);
319 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...
320
321 2
        if (!is_null($documentId)) {
322 2
            $this->deleteById($documentId);
323
            // detach so odm knows it's gone
324 2
            $this->manager->detach($entity);
325 2
            $this->manager->clear();
326 2
        }
327
328 2
        $entity = $this->manager->merge($entity);
329
330 2
        $this->manager->persist($entity);
331 2
        $this->manager->flush($entity);
332
333 2
        if ($returnEntity) {
334
            return $entity;
335
        }
336 2
    }
337
338
    /**
339
     * {@inheritDoc}
340
     *
341
     * @param string|object $id id of entity to delete or entity instance
342
     *
343
     * @return null|Object
344
     */
345
    public function deleteRecord($id)
346
    {
347
        if (is_object($id)) {
348
            $entity = $id;
349
        } else {
350
            $entity = $this->find($id);
351
        }
352
353
        $return = $entity;
354
        if ($entity) {
355
            $this->checkIfOriginRecord($entity);
356
            $this->manager->remove($entity);
357
            $this->manager->flush();
358
            $return = null;
359
        }
360
361
        return $return;
362
    }
363
364
    /**
365
     * Triggers a flush on the DocumentManager
366
     *
367
     * @param null $document optional document
368
     *
369
     * @return void
370
     */
371
    public function flush($document = null)
372
    {
373
        $this->manager->flush($document);
374
    }
375
376
    /**
377
     * A low level delete without any checks
378
     *
379
     * @param mixed $id record id
380
     *
381
     * @return void
382
     */
383 2
    private function deleteById($id)
384
    {
385 2
        $builder = $this->repository->createQueryBuilder();
386
        $builder
387 2
            ->remove()
388 2
            ->field('id')->equals($id)
389 2
            ->getQuery()
390 2
            ->execute();
391 2
    }
392
393
    /**
394
     * Checks in a performant way if a certain record id exists in the database
395
     *
396
     * @param mixed $id record id
397
     *
398
     * @return bool true if it exists, false otherwise
399
     */
400 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...
401
    {
402 4
        return is_array($this->selectSingleFields($id, ['id'], false));
403
    }
404
405
    /**
406
     * Returns a set of fields from an existing resource in a performant manner.
407
     * If you need to check certain fields on an object (and don't need everything), this
408
     * is a better way to get what you need.
409
     * If the record is not present, you will receive null. If you don't need an hydrated
410
     * instance, make sure to pass false there.
411
     *
412
     * @param mixed $id      record id
413
     * @param array $fields  list of fields you need.
414
     * @param bool  $hydrate whether to hydrate object or not
415
     *
416
     * @return array|null|object
417
     */
418 4
    public function selectSingleFields($id, array $fields, $hydrate = true)
419
    {
420 4
        $builder = $this->repository->createQueryBuilder();
421 4
        $idField = $this->repository->getClassMetadata()->getIdentifier()[0];
422
423
        $record = $builder
424 4
            ->field($idField)->equals($id)
425 4
            ->select($fields)
426 4
            ->hydrate($hydrate)
427 4
            ->getQuery()
428 4
            ->getSingleResult();
429
430 4
        return $record;
431
    }
432
433
    /**
434
     * get classname of entity
435
     *
436
     * @return string|null
437
     */
438 4
    public function getEntityClass()
439
    {
440 4
        if ($this->repository instanceof DocumentRepository) {
441 4
            return $this->repository->getDocumentName();
442
        }
443
444
        return null;
445
    }
446
447
    /**
448
     * {@inheritDoc}
449
     *
450
     * Currently this is being used to build the route id used for redirecting
451
     * to newly made documents. It might benefit from having a different name
452
     * for those purposes.
453
     *
454
     * We might use a convention based mapping here:
455
     * Graviton\CoreBundle\Document\App -> mongodb://graviton_core
456
     * Graviton\CoreBundle\Entity\Table -> mysql://graviton_core
457
     *
458
     * @todo implement this in a more convention based manner
459
     *
460
     * @return string
461
     */
462
    public function getConnectionName()
463
    {
464
        $bundle = strtolower(substr(explode('\\', get_class($this))[1], 0, -6));
465
466
        return 'graviton.' . $bundle;
467
    }
468
469
    /**
470
     * Does the actual query using the RQL Bundle.
471
     *
472
     * @param Builder $queryBuilder Doctrine ODM QueryBuilder
473
     * @param Query   $query        query from parser
474
     *
475
     * @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...
476
     */
477
    protected function doRqlQuery($queryBuilder, Query $query)
478
    {
479
        $this->visitor->setBuilder($queryBuilder);
480
481
        return $this->visitor->visit($query);
482
    }
483
484
    /**
485
     * Checks the recordOrigin attribute of a record and will throw an exception if value is not allowed
486
     *
487
     * @param Object $record record
488
     *
489
     * @return void
490
     */
491 14
    protected function checkIfOriginRecord($record)
492
    {
493 7
        if ($record instanceof RecordOriginInterface
494 14
            && !$record->isRecordOriginModifiable()
495 7
        ) {
496 6
            $values = $this->notModifiableOriginRecords;
497 6
            $originValue = strtolower(trim($record->getRecordOrigin()));
498
499 6
            if (in_array($originValue, $values)) {
500 2
                $msg = sprintf("Must not be one of the following keywords: %s", implode(', ', $values));
501
502 2
                throw new RecordOriginModifiedException($msg);
503
            }
504 2
        }
505 12
    }
506
507
    /**
508
     * Determines the configured amount fo data records to be returned in pagination context.
509
     *
510
     * @return int
511
     */
512
    private function getDefaultLimit()
513
    {
514
        if (0 < $this->paginationDefaultLimit) {
515
            return $this->paginationDefaultLimit;
516
        }
517
518
        return 10;
519
    }
520
521
    /**
522
     * @param Boolean $active active
523
     * @param String  $field  field
524
     * @return void
525
     */
526 4
    public function setFilterByAuthUser($active, $field)
527
    {
528 4
        $this->filterByAuthUser = is_bool($active) ? $active : false;
529 4
        $this->filterByAuthField = $field;
530 4
    }
531
}
532