thinktomorrow /
assetlibrary
| 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 | DB::table('asset_pivots') |
||
| 23 | 5 | ->where('entity_type', $model->getMorphClass()) |
|
| 24 | ->where('entity_id', (string) $model->getKey()) |
||
| 25 | ->whereIn('asset_id', $ids) |
||
| 26 | ->where('type', $type) |
||
| 27 | ->where('locale', $locale) |
||
| 28 | ->delete(); |
||
| 29 | } |
||
| 30 | 2 | ||
| 31 | /** |
||
| 32 | 2 | * Detaches all assets or for a specific type from a model. |
|
| 33 | * |
||
| 34 | 2 | * @param $ids |
|
| 35 | 1 | */ |
|
| 36 | 1 | public function detachAll(HasAsset&Model $model, ?string $type = null): void |
|
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 37 | { |
||
| 38 | 1 | $query = DB::table('asset_pivots') |
|
| 39 | ->where('entity_type', $model->getMorphClass()) |
||
| 40 | 2 | ->where('entity_id', (string) $model->getKey()); |
|
| 41 | |||
| 42 | if($type) { |
||
| 43 | $query->where('type', $type); |
||
| 44 | } |
||
| 45 | |||
| 46 | $query->delete(); |
||
| 47 | } |
||
| 48 | |||
| 49 | /** |
||
| 50 | * @param mixed $ids |
||
| 51 | * @return string[] |
||
| 52 | */ |
||
| 53 | private function ensureIdsArePassedAsString(array $ids): array |
||
| 54 | { |
||
| 55 | return array_map(fn($id) => (string)$id, $ids); |
||
| 56 | } |
||
| 57 | } |
||
| 58 |