Test Setup Failed
Push — master ( 6805d0...4b4113 )
by Ben
03:28
created

DetachAsset::detachAll()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 3
Bugs 0 Features 1
Metric Value
cc 2
eloc 5
c 3
b 0
f 1
nc 2
nop 2
dl 0
loc 9
ccs 6
cts 6
cp 1
crap 2
rs 10
1
<?php
2
3
namespace Thinktomorrow\AssetLibrary\Application;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Support\Facades\DB;
7
use Thinktomorrow\AssetLibrary\HasAsset;
8
9
class DetachAsset
10
{
11
    /**
12
     * Detaches an asset from a model.
13
     *
14 5
     * @param $ids
15
     */
16 5
    public function detach(HasAsset $model, $ids, $type, $locale): void
17 4
    {
18
        if (! is_array($ids)) {
19
            $ids = (array) $ids;
20 5
        }
21 5
22
        $ids = $this->ensureIdsArePassedAsString($ids);
23 5
24
        foreach ($ids as $id) {
25
            $model->assetRelation()->where('asset_pivots.type', $type)->where('asset_pivots.locale', $locale)->detach($id);
26
        }
27
    }
28
29
    /**
30 2
     * Detaches all assets or for a specific type from a model.
31
     *
32 2
     * @param $ids
33
     */
34 2
    public function detachAll(HasAsset&Model $model, ?string $type = null): void
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected T_STRING, expecting T_VARIABLE on line 34 at column 39
Loading history...
35 1
    {
36 1
        $query = DB::table('asset_pivots')
37
            ->where('entity_type', $model->getMorphClass())
38 1
            ->where('entity_id', (string) $model->getKey());
39
40 2
        if($type) {
41
            $query->where('type', $type);
42
        }
43
44
        $query->delete();
45
    }
46
47
    /**
48
     * @param mixed $ids
49
     * @return string[]
50
     */
51
    private function ensureIdsArePassedAsString(array $ids): array
52
    {
53
        return array_map(fn($id) => (string)$id, $ids);
54
    }
55
}
56