Test Failed
Pull Request — master (#4)
by
unknown
03:29
created

BelongsToMany::formatRecordsList()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 7
nc 1
nop 1
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: admin
5
 * Date: 09.05.2018
6
 * Time: 11:47
7
 */
8
9
namespace sonrac\Arango\Eloquent\Reletations;
10
11
use \Illuminate\Database\Eloquent\Relations\BelongsToMany as BelongsToManyBase;
12
use \Illuminate\Database\Query\Builder;
13
14
class BelongsToMany extends BelongsToManyBase
15
{
16
    /**
17
     * {@inheritdoc}
18
     */
19
    public function attach($id, array $attributes = [], $touch = true)
20
    {
21
        // Here we will insert the attachment records into the pivot table. Once we have
22
        // inserted the records, we will touch the relationships if necessary and the
23
        // function will return. We can parse the IDs before inserting the records.
24
        $this->newPivotStatement()->insert($this->formatAttachRecords(
25
            $this->parseIds($id), $attributes
26
        ));
27
28
        if ($touch) {
29
            $this->touchIfTouching();
30
        }
31
    }
32
33
    /**
34
     * {@inheritdoc}
35
     */
36
    protected function attachNew(array $records, array $current, $touch = true)
37
    {
38
        $changes = ['attached' => [], 'updated' => []];
39
40
        foreach ($records as $id => $attributes) {
41
            $id = (string) $id;
42
            // If the ID is not in the list of existing pivot IDs, we will insert a new pivot
43
            // record, otherwise, we will just update this existing record on this joining
44
            // table, so that the developers will easily update these records pain free.
45
            if (!in_array($id, $current)) {
46
                $this->attach($id, $attributes, $touch);
47
48
                $changes['attached'][] = $id;
49
            }
50
51
            // Now we'll try to update an existing pivot record with the attributes that were
52
            // given to the method. If the model is actually updated we will add it to the
53
            // list of updated pivot records so we return them back out to the consumer.
54
            elseif (count($attributes) > 0 &&
55
                $this->updateExistingPivot($id, $attributes, $touch)) {
56
                $changes['updated'][] = $id;
57
            }
58
        }
59
60
        return $changes;
61
    }
62
63
    /**
64
     * {@inheritdoc}
65
     */
66
    protected function formatRecordsList(array $records)
67
    {
68
        $records = collect($records)->mapWithKeys(function ($attributes, $id) {
69
            if (!is_array($attributes)) {
70
                list($id, $attributes) = [$attributes, []];
71
            }
72
73
            return [$id => $attributes];
74
        })->all();
75
76
        return $records;
77
    }
78
}