Completed
Push — feature/fix-options-request-on... ( 7b326e )
by Narcotic
70:55 queued 65:04
created

DocumentModel::setRepository()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 9.4285
c 1
b 0
f 0
cc 1
eloc 4
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\RestBundle\Service\RqlTranslator;
11
use Graviton\Rql\Node\SearchNode;
12
use Graviton\SchemaBundle\Model\SchemaModel;
13
use Graviton\SecurityBundle\Entities\SecurityUser;
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\Query\LogicOperator\AndNode;
18
use Xiag\Rql\Parser\Node\Query\LogicOperator\OrNode;
19
use Xiag\Rql\Parser\Node\Query\ScalarOperator\LikeNode;
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
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
150
        /** @var \Doctrine\ODM\MongoDB\Query\Builder $queryBuilder */
151
        $queryBuilder = $this->repository
152
            ->createQueryBuilder();
153
154
        if ($this->filterByAuthUser && $user && $user->hasRole(SecurityUser::ROLE_USER)) {
155
            $queryBuilder->field($this->filterByAuthField)->equals($user->getUser()->getId());
156
        }
157
158
159
        $searchableFields = $this->getSearchableFields();
160
        if (!is_null($schema)) {
161
            $searchableFields = $schema->getSearchable();
162
        }
163
164
        // *** do we have an RQL expression, do we need to filter data?
165
        if ($request->attributes->get('hasRql', false)) {
166
            $queryBuilder = $this->doRqlQuery(
167
                $queryBuilder,
168
                $this->translator->translateSearchQuery(
169
                    $request->attributes->get('rqlQuery'),
170
                    $searchableFields
0 ignored issues
show
Bug introduced by
It seems like $searchableFields defined by $schema->getSearchable() on line 161 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...
171
                )
172
            );
173
        } else {
174
            // @todo [lapistano]: seems the offset is missing for this query.
175
            /** @var \Doctrine\ODM\MongoDB\Query\Builder $qb */
176
            $queryBuilder->find($this->repository->getDocumentName());
177
        }
178
179
        // define offset and limit
180
        if (!array_key_exists('skip', $queryBuilder->getQuery()->getQuery())) {
181
            $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...
182
        } else {
183
            $startAt = (int) $queryBuilder->getQuery()->getQuery()['skip'];
184
        }
185
186
        if (!array_key_exists('limit', $queryBuilder->getQuery()->getQuery())) {
187
            $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...
188
        } else {
189
            $numberPerPage = (int) $queryBuilder->getQuery()->getQuery()['limit'];
190
        }
191
192
        // Limit can not be negative nor null.
193
        if ($numberPerPage < 1) {
194
            throw new RqlSyntaxErrorException('negative or null limit in rql');
195
        }
196
197
        /**
198
         * add a default sort on id if none was specified earlier
199
         *
200
         * not specifying something to sort on leads to very weird cases when fetching references
201
         */
202
        if (!array_key_exists('sort', $queryBuilder->getQuery()->getQuery())) {
203
            $queryBuilder->sort('_id');
204
        }
205
206
        // run query
207
        $query = $queryBuilder->getQuery();
208
        $records = array_values($query->execute()->toArray());
209
210
        $totalCount = $query->count();
211
        $numPages = (int) ceil($totalCount / $numberPerPage);
212
        $page = (int) ceil($startAt / $numberPerPage) + 1;
213
        if ($numPages > 1) {
214
            $request->attributes->set('paging', true);
215
            $request->attributes->set('page', $page);
216
            $request->attributes->set('numPages', $numPages);
217
            $request->attributes->set('startAt', $startAt);
218
            $request->attributes->set('perPage', $numberPerPage);
219
            $request->attributes->set('totalCount', $totalCount);
220
        }
221
222
        return $records;
223
    }
224
225
    /**
226
     * @param object $entity       entity to insert
227
     * @param bool   $returnEntity true to return entity
228
     * @param bool   $doFlush      if we should flush or not after insert
229
     *
230
     * @return Object|null
231
     */
232
    public function insertRecord($entity, $returnEntity = true, $doFlush = true)
233
    {
234
        $this->checkIfOriginRecord($entity);
235
        $this->manager->persist($entity);
236
237
        if ($doFlush) {
238
            $this->manager->flush($entity);
239
        }
240
        if ($returnEntity) {
241
            return $this->find($entity->getId());
242
        }
243
    }
244
245
    /**
246
     * @param string $documentId id of entity to find
247
     *
248
     * @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...
249
     */
250 4
    public function find($documentId)
251
    {
252 4
        return $this->repository->find($documentId);
253
    }
254
255
    /**
256
     * {@inheritDoc}
257
     *
258
     * @param string $documentId   id of entity to update
259
     * @param Object $entity       new entity
260
     * @param bool   $returnEntity true to return entity
261
     *
262
     * @return Object|null
263
     */
264 2
    public function updateRecord($documentId, $entity, $returnEntity = true)
265
    {
266
        // In both cases the document attribute named originRecord must not be 'core'
267 2
        $this->checkIfOriginRecord($entity);
268 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...
269
270 2
        if (!is_null($documentId)) {
271 2
            $this->deleteById($documentId);
272
            // detach so odm knows it's gone
273 2
            $this->manager->detach($entity);
274 2
            $this->manager->clear();
275 1
        }
276
277 2
        $entity = $this->manager->merge($entity);
278
279 2
        $this->manager->persist($entity);
280 2
        $this->manager->flush($entity);
281
282 2
        if ($returnEntity) {
283
            return $entity;
284
        }
285 2
    }
286
287
    /**
288
     * {@inheritDoc}
289
     *
290
     * @param string|object $id id of entity to delete or entity instance
291
     *
292
     * @return null|Object
293
     */
294
    public function deleteRecord($id)
295
    {
296
        if (is_object($id)) {
297
            $entity = $id;
298
        } else {
299
            $entity = $this->find($id);
300
        }
301
302
        $return = $entity;
303
        if ($entity) {
304
            $this->checkIfOriginRecord($entity);
305
            $this->manager->remove($entity);
306
            $this->manager->flush();
307
            $return = null;
308
        }
309
310
        return $return;
311
    }
312
313
    /**
314
     * Triggers a flush on the DocumentManager
315
     *
316
     * @param null $document optional document
317
     *
318
     * @return void
319
     */
320
    public function flush($document = null)
321
    {
322
        $this->manager->flush($document);
323
    }
324
325
    /**
326
     * A low level delete without any checks
327
     *
328
     * @param mixed $id record id
329
     *
330
     * @return void
331
     */
332 2
    private function deleteById($id)
333
    {
334 2
        $builder = $this->repository->createQueryBuilder();
335
        $builder
336 2
            ->remove()
337 2
            ->field('id')->equals($id)
338 2
            ->getQuery()
339 2
            ->execute();
340 2
    }
341
342
    /**
343
     * Checks in a performant way if a certain record id exists in the database
344
     *
345
     * @param mixed $id record id
346
     *
347
     * @return bool true if it exists, false otherwise
348
     */
349 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...
350
    {
351 4
        return is_array($this->selectSingleFields($id, ['id'], false));
352
    }
353
354
    /**
355
     * Returns a set of fields from an existing resource in a performant manner.
356
     * If you need to check certain fields on an object (and don't need everything), this
357
     * is a better way to get what you need.
358
     * If the record is not present, you will receive null. If you don't need an hydrated
359
     * instance, make sure to pass false there.
360
     *
361
     * @param mixed $id      record id
362
     * @param array $fields  list of fields you need.
363
     * @param bool  $hydrate whether to hydrate object or not
364
     *
365
     * @return array|null|object
366
     */
367 4
    public function selectSingleFields($id, array $fields, $hydrate = true)
368
    {
369 4
        $builder = $this->repository->createQueryBuilder();
370 4
        $idField = $this->repository->getClassMetadata()->getIdentifier()[0];
371
372
        $record = $builder
373 4
            ->field($idField)->equals($id)
374 4
            ->select($fields)
375 4
            ->hydrate($hydrate)
376 4
            ->getQuery()
377 4
            ->getSingleResult();
378
379 4
        return $record;
380
    }
381
382
    /**
383
     * get classname of entity
384
     *
385
     * @return string|null
386
     */
387 4
    public function getEntityClass()
388
    {
389 4
        if ($this->repository instanceof DocumentRepository) {
390 4
            return $this->repository->getDocumentName();
391
        }
392
393
        return null;
394
    }
395
396
    /**
397
     * {@inheritDoc}
398
     *
399
     * Currently this is being used to build the route id used for redirecting
400
     * to newly made documents. It might benefit from having a different name
401
     * for those purposes.
402
     *
403
     * We might use a convention based mapping here:
404
     * Graviton\CoreBundle\Document\App -> mongodb://graviton_core
405
     * Graviton\CoreBundle\Entity\Table -> mysql://graviton_core
406
     *
407
     * @todo implement this in a more convention based manner
408
     *
409
     * @return string
410
     */
411
    public function getConnectionName()
412
    {
413
        $bundle = strtolower(substr(explode('\\', get_class($this))[1], 0, -6));
414
415
        return 'graviton.' . $bundle;
416
    }
417
418
    /**
419
     * Does the actual query using the RQL Bundle.
420
     *
421
     * @param Builder $queryBuilder Doctrine ODM QueryBuilder
422
     * @param Query   $query        query from parser
423
     *
424
     * @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...
425
     */
426
    protected function doRqlQuery($queryBuilder, Query $query)
427
    {
428
        $this->visitor->setBuilder($queryBuilder);
429
430
        return $this->visitor->visit($query);
431
    }
432
433
    /**
434
     * Checks the recordOrigin attribute of a record and will throw an exception if value is not allowed
435
     *
436
     * @param Object $record record
437
     *
438
     * @return void
439
     */
440 14
    protected function checkIfOriginRecord($record)
441
    {
442 7
        if ($record instanceof RecordOriginInterface
443 14
            && !$record->isRecordOriginModifiable()
444 7
        ) {
445 6
            $values = $this->notModifiableOriginRecords;
446 6
            $originValue = strtolower(trim($record->getRecordOrigin()));
447
448 6
            if (in_array($originValue, $values)) {
449 2
                $msg = sprintf("Must not be one of the following keywords: %s", implode(', ', $values));
450
451 2
                throw new RecordOriginModifiedException($msg);
452
            }
453 2
        }
454 12
    }
455
456
    /**
457
     * Determines the configured amount fo data records to be returned in pagination context.
458
     *
459
     * @return int
460
     */
461
    private function getDefaultLimit()
462
    {
463
        if (0 < $this->paginationDefaultLimit) {
464
            return $this->paginationDefaultLimit;
465
        }
466
467
        return 10;
468
    }
469
470
    /**
471
     * @param Boolean $active active
472
     * @param String  $field  field
473
     * @return void
474
     */
475 4
    public function setFilterByAuthUser($active, $field)
476
    {
477 4
        $this->filterByAuthUser = is_bool($active) ? $active : false;
478 4
        $this->filterByAuthField = $field;
479 4
    }
480
}
481