Passed
Push — master ( 19fdc3...a3afa9 )
by Ben
07:24
created

RemovalAction   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
eloc 18
c 1
b 0
f 0
dl 0
loc 36
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A handle() 0 26 4
1
<?php
2
declare(strict_types=1);
3
4
namespace Thinktomorrow\Chief\MediaGallery\Application;
5
6
use Illuminate\Http\Request;
7
use Illuminate\Support\Facades\DB;
8
use Thinktomorrow\Chief\Audit\Audit;
9
use Thinktomorrow\AssetLibrary\Application\DeleteAsset;
10
use Thinktomorrow\AssetLibrary\Exceptions\FileNotAccessibleException;
11
12
final class RemovalAction
13
{
14
    /** @var DeleteAsset */
15
    private $deleteAsset;
16
17
    public function __construct(DeleteAsset $deleteAsset)
18
    {
19
        $this->deleteAsset = $deleteAsset;
20
    }
21
22
    public function handle(Request $request)
23
    {
24
        // Strict protection enabled: we won't remove assets who are still being used...
25
        $assetIds = collect($request->input('asset_ids', []))->reject(function($assetId){
26
            return DB::table('asset_pivots')
27
                ->where('asset_id', $assetId)
28
                ->where('unused', 0)
29
                ->exists();
30
        })->toArray();
31
32
        if($assetIds)
0 ignored issues
show
Bug Best Practice introduced by
The expression $assetIds of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
33
        {
34
                foreach($assetIds as $k => $assetId) {
35
                    try{
36
                        $this->deleteAsset->remove($assetId);
37
                    } catch(FileNotAccessibleException $e) {
38
                        unset($assetIds[$k]); // So our count of removed assets is correct in the log.
39
                    }
40
                }
41
42
                Audit::activity()->log('removed ' . count($assetIds) . ' assets from the mediagallery.');
43
44
                return true;
45
        }
46
47
        return false;
48
    }
49
}
50