Passed
Push — master ( 336aa4...192c12 )
by Fran
02:09
created

NOSQLQuery::findPk()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 11
rs 9.9666
c 0
b 0
f 0
cc 2
nc 2
nop 3
1
<?php
2
namespace NOSQL\Models;
3
4
use MongoDB\BSON\ObjectId;
5
use MongoDB\Database;
6
use NOSQL\Dto\Model\ResultsetDto;
7
use NOSQL\Models\base\NOSQLParserTrait;
8
use PSFS\base\config\Config;
9
use PSFS\base\exception\ApiException;
10
use PSFS\base\types\Api;
11
12
final class NOSQLQuery {
13
    /**
14
     * @param $pk
15
     * @param Database|null $con
16
     * @return mixed
17
     * @throws ApiException
18
     */
19
    public static function findPk($modelName, $pk, Database $con = null) {
20
        $model = new $modelName();
21
        $con = NOSQLParserTrait::initConnection($con, $model);
22
        $collection = $con->selectCollection($model->getSchema()->name);
23
        $result = $collection->findOne(['_id' => new ObjectId($pk)]);
24
        if(null !== $result) {
25
            $model->feed($result->getArrayCopy());
26
        } else {
27
            throw new ApiException(t('Document not found'), 404);
28
        }
29
        return $model;
30
    }
31
32
    /**
33
     * @param $modelName
34
     * @param array $criteria
35
     * @param Database|null $con
36
     * @return ResultsetDto
37
     * @throws \PSFS\base\exception\GeneratorException
38
     */
39
    public static function find($modelName, array $criteria, Database $con = null) {
40
        $model = new $modelName();
41
        $con = NOSQLParserTrait::initConnection($con, $model);
42
        $collection = $con->selectCollection($model->getSchema()->name);
43
        $nosqlOptions = [
44
            'limit' => array_key_exists(Api::API_LIMIT_FIELD, $criteria) ? $criteria[Api::API_LIMIT_FIELD] : Config::getParam('pagination.limit', 50),
45
        ];
46
        $resultSet = new ResultsetDto(false);
47
        $resultSet->count = $collection->countDocuments($criteria, $nosqlOptions);
48
        $results = $collection->find($criteria, $nosqlOptions);
49
        /** @var  $result */
50
        foreach($results->toArray() as $result) {
51
            $model->feed($result->getArrayCopy());
52
            $resultSet->items[] = $model->getDtoCopy(true);
53
        }
54
        return $resultSet;
55
    }
56
}