Completed
Push — master ( abe227...316baf )
by Raffael
13:55 queued 08:01
created

Mongodb::transformQuery()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 0
cts 10
cp 0
rs 9.568
c 0
b 0
f 0
cc 4
nc 6
nop 1
crap 20
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * tubee.io
7
 *
8
 * @copyright   Copryright (c) 2017-2019 gyselroth GmbH (https://gyselroth.com)
9
 * @license     GPL-3.0 https://opensource.org/licenses/GPL-3.0
10
 */
11
12
namespace Tubee\Endpoint;
13
14
use Generator;
15
use InvalidArgumentException;
16
use MongoDB\Collection;
17
use Psr\Log\LoggerInterface;
18
use Tubee\AttributeMap\AttributeMapInterface;
19
use Tubee\Collection\CollectionInterface;
20
use Tubee\EndpointObject\EndpointObjectInterface;
21
use Tubee\Workflow\Factory as WorkflowFactory;
22
23
class Mongodb extends AbstractEndpoint
24
{
25
    /**
26
     * Kind.
27
     */
28
    public const KIND = 'MongodbEndpoint';
29
30
    /**
31
     * Collection.
32
     *
33
     * @var Collection
34
     */
35
    protected $pool;
36
37
    /**
38
     * Init endpoint.
39
     */
40
    public function __construct(string $name, string $type, Collection $pool, CollectionInterface $collection, WorkflowFactory $workflow, LoggerInterface $logger, array $resource = [])
41
    {
42
        $this->pool = $pool;
43
        parent::__construct($name, $type, $collection, $workflow, $logger, $resource);
44
    }
45
46
    /**
47
     * {@inheritdoc}
48
     */
49
    public function getOne(array $object, array $attributes = []): EndpointObjectInterface
50
    {
51
        return $this->build($this->get($object, $attributes));
52
    }
53
54
    /**
55
     * {@inheritdoc}
56
     */
57
    public function transformQuery(?array $query = null)
58
    {
59
        $result = null;
60
        if ($this->filter_all !== null) {
61
            $result = json_decode(stripslashes($this->filter_all), true);
62
        }
63
64
        if (!empty($query)) {
65
            if ($this->filter_all === null) {
66
                $result = $query;
67
            } else {
68
                $result = [
69
                    '$and' => [
70
                        json_decode(stripslashes($this->filter_all), true),
71
                        $query,
72
                    ],
73
                ];
74
            }
75
        }
76
77
        return $result;
78
    }
79
80
    /**
81
     * {@inheritdoc}
82
     */
83
    public function getAll(?array $query = null): Generator
84
    {
85
        $i = 0;
86
        foreach ($this->pool->find($this->transformQuery($query)) as $data) {
87
            yield $this->build($data);
88
            ++$i;
89
        }
90
91
        return $i;
92
    }
93
94
    /**
95
     * {@inheritdoc}
96
     */
97
    public function create(AttributeMapInterface $map, array $object, bool $simulate = false): ?string
98
    {
99
        $this->logger->debug('create new mongodb object on endpoint ['.$this->name.'] with values [{values}]', [
100
            'category' => get_class($this),
101
            'values' => $object,
102
        ]);
103
104
        if ($simulate === false) {
105
            return (string) $this->pool->insertOne($object);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return (string) $this->pool->insertOne($object); (string) is incompatible with the return type declared by the interface Tubee\Endpoint\EndpointInterface::create of type boolean.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
106
        }
107
108
        return null;
109
    }
110
111
    /**
112
     * {@inheritdoc}
113
     */
114
    public function change(AttributeMapInterface $map, array $diff, array $object, array $endpoint_object, bool $simulate = false): ?string
115
    {
116
        $filter = $this->getFilterOne($object);
117
        $this->logger->info('update mongodb object on endpoint ['.$this->getIdentifier().']', [
118
            'category' => get_class($this),
119
        ]);
120
121
        if ($simulate === false) {
122
            $this->pool->updateOne($filter, $diff);
123
        }
124
125
        return (string) $endpoint_object['_id'];
0 ignored issues
show
Bug Best Practice introduced by
The return type of return (string) $endpoint_object['_id']; (string) is incompatible with the return type declared by the interface Tubee\Endpoint\EndpointInterface::change of type boolean.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
126
    }
127
128
    /**
129
     * {@inheritdoc}
130
     */
131
    public function getDiff(AttributeMapInterface $map, array $diff): array
132
    {
133
        $result = [];
134
        foreach ($diff as $attribute => $update) {
135
            switch ($update['action']) {
136
                case AttributeMapInterface::ACTION_REPLACE:
137
                    $result['$set'][$attribute] = $update['value'];
138
139
                break;
140
                case AttributeMapInterface::ACTION_REMOVE:
141
                    $result['$unset'][$attribute] = true;
142
143
                break;
144
                case AttributeMapInterface::ACTION_ADD:
145
                    $result['$addToSet'][$attribute] = $update['value'];
146
147
                break;
148
                default:
149
                    throw new InvalidArgumentException('unknown diff action '.$update['action'].' given');
150
            }
151
        }
152
153
        return $result;
154
    }
155
156
    /**
157
     * {@inheritdoc}
158
     */
159
    public function delete(AttributeMapInterface $map, array $object, ?array $endpoint_object = null, bool $simulate = false): bool
160
    {
161
        $filter = $this->getFilterOne($object);
162
163
        $this->logger->info('delete mongodb object on endpoint ['.$this->name.'] with filter ['.json_encode($filter).']', [
164
            'category' => get_class($this),
165
        ]);
166
167
        if ($simulate === false) {
168
            $this->pool->deleteOne($filter);
169
        }
170
171
        return true;
172
    }
173
174
    /**
175
     * Get existing object.
176
     */
177
    protected function get(array $object, array $attributes = []): array
0 ignored issues
show
Unused Code introduced by
The parameter $attributes is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
178
    {
179
        $result = [];
180
        $filter = $this->getFilterOne($object);
181
182
        foreach ($this->pool->find($filter) as $data) {
183
            $result[] = $data;
184
        }
185
186
        if (count($result) > 1) {
187
            throw new Exception\ObjectMultipleFound('found more than one object with filter '.json_encode($filter));
188
        }
189
        if (count($result) === 0) {
190
            throw new Exception\ObjectNotFound('no object found with filter '.json_encode($filter));
191
        }
192
193
        return (array) array_shift($result);
194
    }
195
}
196