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

DetachAsset   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 1 Features 1
Metric Value
eloc 11
c 3
b 1
f 1
dl 0
loc 41
ccs 13
cts 13
cp 1
rs 10
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A detach() 0 10 3
A detachAll() 0 7 2
A ensureParameterIsString() 0 3 1
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