ShareRelation::unlink()   B
last analyzed

Complexity

Conditions 7
Paths 32

Size

Total Lines 35
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 19
c 1
b 0
f 0
nc 32
nop 2
dl 0
loc 35
rs 8.8333
1
<?php
2
3
/**
4
 * Platine ORM
5
 *
6
 * Platine ORM provides a flexible and powerful ORM implementing a data-mapper pattern.
7
 *
8
 * This content is released under the MIT License (MIT)
9
 *
10
 * Copyright (c) 2020 Platine ORM
11
 *
12
 * Permission is hereby granted, free of charge, to any person obtaining a copy
13
 * of this software and associated documentation files (the "Software"), to deal
14
 * in the Software without restriction, including without limitation the rights
15
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
 * copies of the Software, and to permit persons to whom the Software is
17
 * furnished to do so, subject to the following conditions:
18
 *
19
 * The above copyright notice and this permission notice shall be included in all
20
 * copies or substantial portions of the Software.
21
 *
22
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
 * SOFTWARE.
29
 */
30
31
/**
32
 *  @file ShareRelation.php
33
 *
34
 *  The ShareRelation class
35
 *
36
 *  @package    Platine\Orm\Relation
37
 *  @author Platine Developers Team
38
 *  @copyright  Copyright (c) 2020
39
 *  @license    http://opensource.org/licenses/MIT  MIT License
40
 *  @link   https://www.platine-php.com
41
 *  @version 1.0.0
42
 *  @filesource
43
 */
44
45
declare(strict_types=1);
46
47
namespace Platine\Orm\Relation;
48
49
use Platine\Database\Query\Delete;
50
use Platine\Database\Query\Insert;
51
use Platine\Database\Query\Join;
52
use Platine\Database\Query\QueryStatement;
53
use Platine\Orm\Entity;
54
use Platine\Orm\EntityManager;
55
use Platine\Orm\Mapper\DataMapper;
56
use Platine\Orm\Mapper\EntityMapper;
57
use Platine\Orm\Mapper\Proxy;
58
use Platine\Orm\Query\EntityQuery;
59
use Platine\Orm\Query\Query;
60
use Platine\Orm\Relation\ForeignKey;
61
use Platine\Orm\Relation\Junction;
62
use Platine\Orm\Relation\Relation;
63
use Platine\Orm\Relation\RelationLoader;
64
65
/**
66
 * @class ShareRelation
67
 * @package Platine\Orm\Relation
68
 * @template TEntity as Entity
69
 * @extends Relation<TEntity>
70
 */
71
abstract class ShareRelation extends Relation
72
{
73
    /**
74
     * Whether is many or not
75
     * @var bool
76
     */
77
    protected bool $hasMany = false;
78
79
    /**
80
     * The junction instance
81
     * @var Junction|null
82
     */
83
    protected ?Junction $junction = null;
84
85
    /**
86
     * Create new instance
87
     * @param class-string<TEntity> $entityClass
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string<TEntity> at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string<TEntity>.
Loading history...
88
     * @param ForeignKey|null $foreignKey
89
     * @param Junction|null $junction
90
     */
91
    public function __construct(
92
        string $entityClass,
93
        ?ForeignKey $foreignKey = null,
94
        ?Junction $junction = null
95
    ) {
96
        parent::__construct($entityClass, $foreignKey);
97
        $this->junction = $junction;
98
    }
99
100
        /**
101
     *
102
     * @param DataMapper<TEntity> $mapper
103
     * @param TEntity $entity
0 ignored issues
show
Bug introduced by
The type Platine\Orm\Relation\TEntity was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
104
     *
105
     * @return bool
106
     */
107
    public function link(DataMapper $mapper, Entity $entity): bool
108
    {
109
        $manager = $mapper->getEntityManager();
110
        $owner = $mapper->getEntityMapper();
111
        $related = $manager->getEntityMapper($this->entityClass);
112
113
        if ($this->junction === null) {
114
            $this->junction = $this->buildJunction($owner, $related);
115
        }
116
117
        if ($this->foreignKey === null) {
118
            $this->foreignKey = $owner->getForeignKey();
119
        }
120
121
        /** @var array<string, mixed> $values */
122
        $values = [];
123
124
        $foreignKeys = $this->foreignKey->getValue($mapper->getRawColumns(), true);
0 ignored issues
show
Bug introduced by
The method getValue() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

124
        /** @scrutinizer ignore-call */ 
125
        $foreignKeys = $this->foreignKey->getValue($mapper->getRawColumns(), true);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
125
        if (is_array($foreignKeys)) {
126
            foreach ($foreignKeys as $fkColumn => $fkValue) {
127
                $values[$fkColumn] = $fkValue;
128
            }
129
        }
130
131
        $columns = Proxy::instance()->getEntityDataMapper($entity)->getRawColumns();
132
        foreach ($this->junction->columns() as $pkColumn => $fkColumn) {
0 ignored issues
show
Bug introduced by
The method columns() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

132
        foreach ($this->junction->/** @scrutinizer ignore-call */ columns() as $pkColumn => $fkColumn) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
133
            $values[$fkColumn] = $columns[$pkColumn];
134
        }
135
136
        $cmd = new Insert($manager->getConnection());
137
        $cmd->insert($values);
138
139
        return (bool) $cmd->into($this->junction->table());
140
    }
141
142
    /**
143
     *
144
     * @param DataMapper<TEntity> $mapper
145
     * @param TEntity $entity
146
     *
147
     * @return bool
148
     */
149
    public function unlink(DataMapper $mapper, Entity $entity): bool
150
    {
151
        $manager = $mapper->getEntityManager();
152
        $owner = $mapper->getEntityMapper();
153
        $related = $manager->getEntityMapper($this->entityClass);
154
155
        if ($this->junction === null) {
156
            $this->junction = $this->buildJunction($owner, $related);
157
        }
158
159
        if ($this->foreignKey === null) {
160
            $this->foreignKey = $owner->getForeignKey();
161
        }
162
163
        /** @var array<string, mixed> $values */
164
        $values = [];
165
166
        $foreignKeys = $this->foreignKey->getValue($mapper->getRawColumns(), true);
167
        if (is_array($foreignKeys)) {
168
            foreach ($foreignKeys as $fkColumn => $fkValue) {
169
                $values[$fkColumn] = $fkValue;
170
            }
171
        }
172
173
        $columns = Proxy::instance()->getEntityDataMapper($entity)->getRawColumns();
174
        foreach ($this->junction->columns() as $pkColumn => $fkColumn) {
175
            $values[$fkColumn] = $columns[$pkColumn];
176
        }
177
        $cmd = new Delete($manager->getConnection(), $this->junction->table());
178
179
        foreach ($values as $column => $value) {
180
            $cmd->where($column)->is($value);
181
        }
182
183
        return (bool) $cmd->delete();
184
    }
185
186
    /**
187
     * {@inheritedoc}
188
     * @param EntityManager<TEntity> $manager
189
     * @param EntityMapper<TEntity> $owner
190
     * @param array<string, mixed> $options
191
     *
192
     * @return RelationLoader<TEntity>
193
     */
194
    public function getLoader(
195
        EntityManager $manager,
196
        EntityMapper $owner,
197
        array $options
198
    ): RelationLoader {
199
        $related = $manager->getEntityMapper($this->entityClass);
200
201
        if ($this->junction === null) {
202
            $this->junction = $this->buildJunction($owner, $related);
203
        }
204
205
        if ($this->foreignKey === null) {
206
            $this->foreignKey = $owner->getForeignKey();
207
        }
208
209
        $junctionTable = $this->junction->table();
210
        $joinTable = $related->getTable();
211
212
        /** @var array<string, array<mixed>> $ids */
213
        $ids = [];
214
        foreach ($options['results'] as $result) {
215
            $primaryKeys = $owner->getPrimaryKey()->getValue($result, true);
216
            if (is_array($primaryKeys)) {
217
                foreach ($primaryKeys as $pkColumn => $pkValue) {
218
                    $ids[$pkColumn][] = $pkValue;
219
                }
220
            }
221
        }
222
223
        $queryStatement = new QueryStatement();
224
225
        $select = new class ($manager, $related, $queryStatement, $junctionTable) extends EntityQuery
226
        {
227
            /**
228
             *
229
             * @var string
230
             */
231
            protected string $junctionTable;
232
233
            /**
234
             *
235
             * @param EntityManager<TEntity> $manager
236
             * @param EntityMapper<TEntity> $mapper
237
             * @param QueryStatement $queryStatement
238
             * @param string $table
239
             */
240
            public function __construct(
241
                EntityManager $manager,
242
                EntityMapper $mapper,
243
                QueryStatement $queryStatement,
244
                string $table
245
            ) {
246
                parent::__construct($manager, $mapper, $queryStatement);
247
                $this->junctionTable = $table;
248
            }
249
250
            /**
251
             *
252
             * @return EntityQuery<TEntity>
253
             */
254
            protected function buildQuery(): EntityQuery
255
            {
256
                $this->locked = true;
257
                $this->queryStatement->addTables([$this->junctionTable]);
258
259
                return $this;
260
            }
261
262
            /**
263
             *
264
             * @return bool
265
             */
266
            protected function isReadOnly(): bool
267
            {
268
                return count($this->queryStatement->getJoins()) > 1;
269
            }
270
        };
271
272
        $linkKey = new ForeignKey(array_map(function ($value) use ($junctionTable) {
273
            return 'hidden_' . $junctionTable . $value;
274
        }, $this->foreignKey->columns()));
275
276
        $select->join($joinTable, function (Join $join) use ($junctionTable, $joinTable) {
277
            if ($this->junction !== null) {
278
                foreach ($this->junction->columns() as $pkColumn => $fkColumn) {
279
                    $join->on($junctionTable . '.' . $fkColumn, $joinTable . '.' . $pkColumn);
280
                }
281
            }
282
        });
283
284
        $foreignKeys = $this->foreignKey->getValue($ids, true);
285
        if (is_array($foreignKeys)) {
286
            foreach ($foreignKeys as $fkColumn => $fkValue) {
287
                $select->where($junctionTable . '.' . $fkColumn)->in([$fkValue]);
288
            }
289
        }
290
291
        $queryStatement->addColumn($joinTable . '.*');
292
293
        $linkKeyCols = $linkKey->columns();
294
        foreach ($this->foreignKey->columns() as $pkColumn => $fkColumn) {
295
            $queryStatement->addColumn($junctionTable . '.' . $fkColumn, $linkKeyCols[$pkColumn]);
296
        }
297
298
        if ($options['callback'] !== null) {
299
            $callback = $options['callback'];
300
            $callback(new Query($queryStatement));
301
        }
302
303
        $select->with($options['with'], $options['immediate']);
304
305
        /** @var RelationLoader<TEntity> $loader */
306
        $loader = new RelationLoader(
307
            $select,
308
            $linkKey,
309
            false,
310
            $this->hasMany,
311
            $options['immediate']
312
        );
313
314
        return $loader;
315
    }
316
317
    /**
318
     * {@inheritedoc}
319
     * @param DataMapper<TEntity> $mapper
320
     *
321
     * @return TEntity|array<TEntity>|null
322
     */
323
    public function getResult(DataMapper $mapper, ?callable $callback = null): Entity|array|null
324
    {
325
        $manager = $mapper->getEntityManager();
326
        $owner = $mapper->getEntityMapper();
327
        $related = $manager->getEntityMapper($this->entityClass);
328
329
        if ($this->junction === null) {
330
            $this->junction = $this->buildJunction($owner, $related);
331
        }
332
333
        if ($this->foreignKey === null) {
334
            $this->foreignKey = $owner->getForeignKey();
335
        }
336
337
        $junctionTable = $this->junction->table();
338
        $joinTable = $related->getTable();
339
340
        $queryStatement = new QueryStatement();
341
        $select = new class ($manager, $related, $queryStatement, $junctionTable) extends EntityQuery
342
        {
343
            /**
344
             *
345
             * @var string
346
             */
347
            protected string $junctionTable;
348
349
            /**
350
             *
351
             * @param EntityManager<TEntity> $manager
352
             * @param EntityMapper<TEntity> $mapper
353
             * @param QueryStatement $queryStatement
354
             * @param string $table
355
             */
356
            public function __construct(
357
                EntityManager $manager,
358
                EntityMapper $mapper,
359
                QueryStatement $queryStatement,
360
                string $table
361
            ) {
362
                parent::__construct($manager, $mapper, $queryStatement);
363
                $this->junctionTable = $table;
364
            }
365
366
            /**
367
             *
368
             * @return EntityQuery<TEntity>
369
             */
370
            protected function buildQuery(): EntityQuery
371
            {
372
                $this->locked = true;
373
                $this->queryStatement->addTables([$this->junctionTable]);
374
375
                return $this;
376
            }
377
378
            /**
379
             *
380
             * @return bool
381
             */
382
            protected function isReadOnly(): bool
383
            {
384
                return count($this->queryStatement->getJoins()) > 1;
385
            }
386
        };
387
388
        $select->join($joinTable, function (Join $join) use ($junctionTable, $joinTable) {
389
            if ($this->junction !== null) {
390
                foreach ($this->junction->columns() as $pkColumn => $fkColumn) {
391
                    $join->on($junctionTable . '.' . $fkColumn, $joinTable . '.' . $pkColumn);
392
                }
393
            }
394
        });
395
396
         $foreignKeys = $this->foreignKey->getValue($mapper->getRawColumns(), true);
397
        if (is_array($foreignKeys)) {
398
            foreach ($foreignKeys as $fkColumn => $value) {
399
                $select->where($junctionTable . '.' . $fkColumn)->is($value);
400
            }
401
        }
402
403
        $queryStatement->addColumn($joinTable . '.*');
404
405
        if ($this->queryCallback !== null || $callback !== null) {
406
            $query = $select;
407
408
            if ($this->queryCallback !== null) {
409
                ($this->queryCallback)($query);
410
            }
411
412
            if ($callback !== null) {
413
                $callback($query);
414
            }
415
        }
416
417
        if ($this->hasMany) {
418
            /** @var TEntity[] $results */
419
            $results = $select->all();
420
421
            return $results;
422
        }
423
424
        /** @var TEntity|null $result */
425
        $result = $select->get();
426
427
        return $result;
428
    }
429
430
    /**
431
     * Build Junction instance
432
     * @param EntityMapper<TEntity> $owner
433
     * @param EntityMapper<TEntity> $related
434
     * @return Junction
435
     */
436
    protected function buildJunction(EntityMapper $owner, EntityMapper $related): Junction
437
    {
438
        return new class ($owner, $related) extends Junction
439
        {
440
            /**
441
             *
442
             * @param EntityMapper<TEntity> $owner
443
             * @param EntityMapper<TEntity> $related
444
             */
445
            public function __construct(EntityMapper $owner, EntityMapper $related)
446
            {
447
                $table = [$owner->getTable(), $related->getTable()];
448
                sort($table);
449
                parent::__construct(implode('_', $table), $related->getForeignKey()->columns());
450
            }
451
        };
452
    }
453
}
454