Test Setup Failed
Push — master ( 8a9f0f...befa7d )
by Ben
04:43
created

DetachAsset::detach()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 2
Bugs 0 Features 1
Metric Value
cc 3
eloc 5
c 2
b 0
f 1
nc 4
nop 4
dl 0
loc 10
ccs 6
cts 6
cp 1
crap 3
rs 10
1
<?php
2
3
namespace Thinktomorrow\AssetLibrary\Application;
4
5
use Thinktomorrow\AssetLibrary\HasAsset;
6
7
class DetachAsset
8
{
9
    /**
10
     * Detaches an asset from a model.
11
     *
12
     * @param $ids
13
     */
14 5
    public function detach(HasAsset $model, $ids, $type, $locale): void
15
    {
16 5
        if (! is_array($ids)) {
17 4
            $ids = (array) $ids;
18
        }
19
20 5
        $ids = $this->ensureParameterIsString($ids);
21 5
22
        foreach ($ids as $id) {
23 5
            $model->assetRelation()->where('asset_pivots.type', $type)->where('asset_pivots.locale', $locale)->detach($id);
24
        }
25
    }
26
27
    /**
28
     * Detaches all assets or for a specific type from a model.
29
     *
30 2
     * @param $ids
31
     */
32 2
    public function detachAll(HasAsset $model, ?string $type = null): void
33
    {
34 2
        $assetIds = $type
35 1
            ? $model->assetRelation()->where('asset_pivots.type', $type)->get()->pluck('id')
36 1
            : $model->assetRelation()->get()->pluck('id');
37
38 1
        $model->assetRelation()->detach($assetIds);
39
    }
40 2
41
    /**
42
     * @param mixed $ids
43
     * @return string[]
44
     */
45
    public function ensureParameterIsString(mixed $ids): array
46
    {
47
        return array_map(fn($id) => (string)$id, $ids);
48
    }
49
}
50