Passed
Branch main (d2dd60)
by Sammy
07:24 queued 47s
created

RelationManyToMany::setMany()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace HexMakina\TightORM;
4
5
use HexMakina\Crudites\CruditesException;
6
use HexMakina\BlackBox\ORM\ModelInterface;
7
8
trait RelationManyToMany
9
{
10
    abstract public static function model_type(): string;
11
12
    //------------------------------------------------------------  Data Relation
13
    // returns true on success, error message on failure
14
    public static function setMany($linked_models, ModelInterface $m)
15
    {
16
        $linked_ids = [];
17
        foreach ($linked_models as $m) {
18
            $linked_ids[] = $m->getId();
19
        }
20
21
        return static::setManyByIds($linked_ids, $m);
22
    }
23
24
    // returns true on success, error message on failure
25
    public static function setManyByIds($linked_ids, ModelInterface $m)
26
    {
27
        $join_info = static::otm();
28
29
        $j_table = static::inspect($join_info['t']);
30
        $j_table_key = $join_info['k'];
31
32
        if (empty($j_table) || empty($j_table_key)) {
33
            throw new CruditesException('ERR_JOIN_INFO');
34
        }
35
36
        $assoc_data = ['model_id' => $m->getId(), 'model_type' => get_class($m)::model_type()];
37
38
        $j_table->connection()->transact();
39
        try {
40
            $res = $j_table->delete($assoc_data)->run();
41
            if (!$res->isSuccess()) {
42
                throw new CruditesException('QUERY_FAILED');
43
            }
44
45
            if (!empty($linked_ids)) {
46
                $join_data = $assoc_data;
47
48
                $Query = $j_table->insert($join_data);
49
50
                foreach ($linked_ids as $linked_id) {
51
                    $Query->addBinding($j_table_key, $linked_id);
52
                    $res = $Query->run();
53
54
                    if (!$res->isSuccess()) {
55
                        throw new CruditesException('QUERY_FAILED');
56
                    }
57
                }
58
            }
59
            $j_table->connection()->commit();
60
        } catch (\Exception $e) {
61
            $j_table->connection()->rollback();
62
            return $e->getMessage();
63
        }
64
        return true;
65
    }
66
67
    public static function otm($k = null)
68
    {
69
        $type = static::model_type();
70
        $d = ['t' => $type . 's_models', 'k' => $type . '_id', 'a' => $type . 's_otm'];
71
        return is_null($k) ? $d : $d[$k];
72
    }
73
}
74