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

DetachAsset   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 4
Bugs 1 Features 1
Metric Value
eloc 12
c 4
b 1
f 1
dl 0
loc 43
ccs 13
cts 13
cp 1
rs 10
wmc 6
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