Completed
Push — master ( a84497...7e4c82 )
by Damian
10s
created

AssetAdminFile::getFilesInUse()   B

Complexity

Conditions 4
Paths 2

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 25
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 15
nc 2
nop 0
1
<?php
2
3
namespace SilverStripe\AssetAdmin\Controller;
4
5
use SilverStripe\Assets\File;
6
use SilverStripe\Assets\Folder;
7
use SilverStripe\CMS\Model\SiteTree;
8
use SilverStripe\CMS\Model\SiteTreeFileExtension;
9
use SilverStripe\Control\Director;
10
use SilverStripe\ORM\ArrayList;
11
use SilverStripe\ORM\DataExtension;
12
use SilverStripe\ORM\SS_List;
13
use SilverStripe\ORM\Versioning\Versioned;
14
use SilverStripe\ORM\Versioning\DataDifferencer;
15
16
/**
17
 * Update File dataobjects to be editable in this asset admin
18
 *
19
 * @property File $owner
20
 */
21
class AssetAdminFile extends DataExtension
22
{
23
    /**
24
     * Max width for inserted images
25
     *
26
     * @config
27
     * @var int
28
     */
29
    private static $insert_width = 600;
0 ignored issues
show
Unused Code introduced by
The property $insert_width is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
30
31
    /**
32
     * Max height for inserted images
33
     *
34
     * @config
35
     * @var int
36
     */
37
    private static $insert_height = 400;
0 ignored issues
show
Unused Code introduced by
The property $insert_height is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
38
39
    public function updateCMSEditLink(&$link)
40
    {
41
        // Update edit link for this file to point to the new asset admin
42
        $controller = AssetAdmin::singleton();
43
        $link = Director::absoluteURL($controller->getFileEditLink($this->owner));
44
    }
45
46
    /**
47
     * Calculate width to insert into html area
48
     *
49
     * @return int|null
50
     */
51
    public function getInsertWidth()
52
    {
53
        $size = $this->getInsertDimensions();
54
        return $size ? $size['width'] : null;
55
    }
56
57
    /**
58
     * Calculate width to insert into html area
59
     *
60
     * @return int
61
     */
62
    public function getInsertHeight()
63
    {
64
        $size = $this->getInsertDimensions();
65
        return $size ? $size['height'] : null;
66
    }
67
68
    /**
69
     * Get dimensions of this image sized within insert_width x insert_height
70
     *
71
     * @return array|null
72
     */
73
    protected function getInsertDimensions()
74
    {
75
        $dimensions = $this->owner->getDimensions('array');
76
        if (!$dimensions) {
77
            return null;
78
        }
79
80
        list ($width, $height) = $dimensions;
81
        $maxWidth = $this->owner->config()->get('insert_width');
82
        $maxHeight = $this->owner->config()->get('insert_height');
83
84
        // Within bounds
85
        if ($width < $maxWidth && $height < $maxHeight) {
86
            return [
87
                'width' => $width,
88
                'height' => $height,
89
            ];
90
        }
91
92
        // Check if sizing by height or width
93
        if (($width * $maxHeight) < ($height * $maxWidth)) {
94
            // Size by height
95
            return [
96
                'width' => intval(($width * $maxHeight) / $height + 0.5),
97
                'height' => $maxHeight,
98
            ];
99
        } else {
100
            // Size by width
101
            return [
102
                'width' => $maxWidth,
103
                'height' => intval(($height * $maxWidth) / $width + 0.5),
104
            ];
105
        }
106
    }
107
108
    /**
109
     * @param int $from
110
     * @param int $to
111
     *
112
     * @return string
113
     */
114
    public function humanizedChanges($from, $to)
115
    {
116
        if (!$from) {
117
            return _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.UPLOADEDFILE', "Uploaded file");
118
        }
119
120
        $fromRecord = Versioned::get_version($this->owner->class, $this->owner->ID, $from);
121
        $toRecord = Versioned::get_version($this->owner->class, $this->owner->ID, $to);
122
123
        $diff = new DataDifferencer($fromRecord, $toRecord);
124
        $changes = $diff->changedFieldNames();
125
126
        $k = array_search('LastEdited', $changes);
127
128
        if ($k !== false) {
129
            unset($changes[$k]);
130
        }
131
132
        $output = array();
133
134
        foreach ($changes as $change) {
135
            $human = $change;
0 ignored issues
show
Unused Code introduced by
$human is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
136
137
            if ($change == "ParentID") {
138
                // updated folder ID
139
                $human = _t(
140
                    'SilverStripe\\AssetAdmin\\Controller\\AssetAdminFile.MOVEDFOLDER',
141
                    "Moved file"
142
                );
143
            } elseif ($change == 'Title') {
144
                $human = _t(
145
                    'SilverStripe\\AssetAdmin\\Controller\\AssetAdminFile.RENAMEDTITLE',
146
                    "Updated title to "
147
                ) . $fromRecord->Title;
148
            } elseif ($change == 'Name') {
149
                $human = _t(
150
                    'SilverStripe\\AssetAdmin\\Controller\\AssetAdminFile.RENAMEDFILE',
151
                    "Renamed file to "
152
                ) . $fromRecord->Filename;
153
            } elseif ($change == 'File') {
154
                // check to make sure the files are actually different
155
                if ($fromRecord->getHash() != $toRecord->getHash()) {
156
                    $human = _t(
157
                        'SilverStripe\\AssetAdmin\\Controller\\AssetAdminFile.RENAMEDFILE',
158
                        "Replaced file"
159
                    );
160
                } else {
161
                    $human = false;
162
                }
163
            } else {
164
                $human = false;
165
            }
166
167
            if ($human) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $human of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
168
                $output[] = $human;
169
            }
170
        }
171
172
        return implode(", ", $output);
173
    }
174
175
    /**
176
     * Get the list of all nested files in use
177
     *
178
     * @return SS_List
179
     */
180
    public function getFilesInUse()
181
    {
182
        $list = ArrayList::create();
183
184
        // Check SiteTreeFileExtension
185
        if (File::has_extension(SiteTreeFileExtension::class)
186
            && class_exists(SiteTree::class)
187
            && $this->owner instanceof Folder
188
        ) {
189
            // Join on tracking table
190
            $parents = static::nestedFolderIDs($this->owner->ID);
191
            $list = File::get()->filter('ParentID', $parents)
192
                ->innerJoin(
193
                    'SiteTree_ImageTracking',
194
                    '"File"."ID" = "SiteTree_ImageTracking"."FileID"'
195
                )->innerJoin(
196
                    'SiteTree',
197
                    '"SiteTree"."ID" = "SiteTree_ImageTracking"."SiteTreeID"'
198
                );
199
        }
200
201
        // Allow extension
202
        $this->owner->extend('updateFilesInUse', $list);
203
        return $list;
204
    }
205
206
    /**
207
     * Get recursive parent IDs
208
     *
209
     * @param int $parentID
210
     * @param int $maxDepth Hard limit of max depth
211
     * @return array List of parent IDs, including $parentID
212
     */
213
    public static function nestedFolderIDs($parentID, $maxDepth = 5)
214
    {
215
        $ids = [$parentID];
216
        if ($maxDepth === 0) {
217
            return $ids;
218
        }
219
        $childIDs = Folder::get()->filter('ParentID', $parentID)->column('ID');
220
        foreach ($childIDs as $childID) {
221
            $ids = array_merge($ids, static::nestedFolderIDs($childID, $maxDepth - 1));
222
        }
223
        return $ids;
224
    }
225
}
226