Completed
Pull Request — master (#110)
by Franco
02:04
created

DMSDocument::validate()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 7
nc 4
nop 0
1
<?php
2
3
/**
4
 * @package dms
5
 *
6
 * @property Varchar Filename
7
 * @property Varchar Folder
8
 * @property Varchar Title
9
 * @property Text Description
10
 * @property int ViewCount
11
 * @property DateTime LastChanged
12
 * @property Boolean EmbargoedIndefinitely
13
 * @property Boolean EmbargoedUntilPublished
14
 * @property DateTime EmbargoedUntilDate
15
 * @property DateTime ExpireAtDate
16
 * @property Enum DownloadBehavior
17
 * @property Enum CanViewType Enum('Anyone, LoggedInUsers, OnlyTheseUsers', 'Anyone')
18
 * @property Enum CanEditType Enum('LoggedInUsers, OnlyTheseUsers', 'LoggedInUsers')
19
 *
20
 * @method ManyManyList RelatedDocuments
21
 * @method ManyManyList Tags
22
 * @method ManyManyList ViewerGroups
23
 * @method ManyManyList EditorGroups
24
 *
25
 */
26
class DMSDocument extends DataObject implements DMSDocumentInterface
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
27
{
28
    private static $db = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $db 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...
29
        "Filename" => "Varchar(255)", // eg. 3469~2011-energysaving-report.pdf
30
        "Folder" => "Varchar(255)",    // eg.	0
31
        "Title" => 'Varchar(1024)', // eg. "Energy Saving Report for Year 2011, New Zealand LandCorp"
32
        "Description" => 'Text',
33
        "ViewCount" => 'Int',
34
        // When this document's file was created or last replaced (small changes like updating title don't count)
35
        "LastChanged" => 'SS_DateTime',
36
37
        "EmbargoedIndefinitely" => 'Boolean(false)',
38
        "EmbargoedUntilPublished" => 'Boolean(false)',
39
        "EmbargoedUntilDate" => 'SS_DateTime',
40
        "ExpireAtDate" => 'SS_DateTime',
41
        "DownloadBehavior" => 'Enum(array("open","download"), "download")',
42
        "CanViewType" => "Enum('Anyone, LoggedInUsers, OnlyTheseUsers', 'Anyone')",
43
        "CanEditType" => "Enum('LoggedInUsers, OnlyTheseUsers', 'LoggedInUsers')",
44
    );
45
46
    private static $many_many = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $many_many 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...
47
        'Pages' => 'SiteTree',
48
        'RelatedDocuments' => 'DMSDocument',
49
        'Tags' => 'DMSTag',
50
        'ViewerGroups' => 'Group',
51
        'EditorGroups' => 'Group',
52
    );
53
54
    private static $many_many_extraFields = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $many_many_extraFields 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...
55
        'Pages' => array(
56
            'DocumentSort' => 'Int'
57
        )
58
    );
59
60
    private static $display_fields = array(
0 ignored issues
show
Unused Code introduced by
The property $display_fields 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...
61
        'ID' => 'ID',
62
        'Title' => 'Title',
63
        'FilenameWithoutID' => 'Filename',
64
        'LastChanged' => 'LastChanged'
65
    );
66
67
    private static $singular_name = 'Document';
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $singular_name 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...
68
69
    private static $plural_name = 'Documents';
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $plural_name 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...
70
71
    private static $searchable_fields = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $searchable_fields 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...
72
        'ID' => array(
73
            'filter' => 'ExactMatchFilter',
74
            'field' => 'NumericField'
75
        ),
76
        'Title',
77
        'Filename',
78
        'LastChanged'
79
    );
80
81
    private static $summary_fields = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $summary_fields 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...
82
        'Filename' => 'Filename',
83
        'Title' => 'Title',
84
        'ViewCount' => 'ViewCount',
85
        'getPages.count' => 'Page Use'
86
    );
87
88
    /**
89
     * @var string download|open
90
     * @config
91
     */
92
    private static $default_download_behaviour = 'download';
0 ignored issues
show
Unused Code introduced by
The property $default_download_behaviour 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...
93
94
    public function canView($member = null)
95
    {
96
        if (!$member || !(is_a($member, 'Member')) || is_numeric($member)) {
97
            $member = Member::currentUser();
98
        }
99
100
        if (!$this->CanViewType || $this->CanViewType == 'Anyone') {
101
            return true;
102
        }
103
104
        if ($member && Permission::checkMember($member,
105
                array(
106
                    'ADMIN',
107
                    'SITETREE_EDIT_ALL',
108
                    'SITETREE_VIEW_ALL',
109
                )
110
            )
111
        ) {
112
            return true;
113
        }
114
115
        if ($this->isHidden()) {
116
            return false;
117
        }
118
119
        if ($this->CanViewType == 'LoggedInUsers') {
120
            return $member && $member->exists();
121
        }
122
123
        if ($this->CanViewType == 'OnlyTheseUsers' && $this->ViewerGroups()->count()) {
0 ignored issues
show
Documentation Bug introduced by
The method ViewerGroups does not exist on object<DMSDocument>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
124
            $result = ($member && $member->inGroups($this->ViewerGroups()));
0 ignored issues
show
Documentation Bug introduced by
The method ViewerGroups does not exist on object<DMSDocument>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
125
126
            return $result;
127
        }
128
129
        return $this->canEdit($member);
130
    }
131
132
    public function canEdit($member = null)
133
    {
134
        if (!$member || !(is_a($member, 'Member')) || is_numeric($member)) {
135
            $member = Member::currentUser();
136
        }
137
138
        if ($this->CanEditType === 'LoggedInUsers') {
139
            return $member && $member->exists();
140
        }
141
        if ($this->CanEditType === 'OnlyTheseUsers' && $this->EditorGroups()->count()) {
0 ignored issues
show
Documentation Bug introduced by
The method EditorGroups does not exist on object<DMSDocument>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
142
            return $member && $member->inGroups($this->EditorGroups());
0 ignored issues
show
Documentation Bug introduced by
The method EditorGroups does not exist on object<DMSDocument>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
143
        }
144
145
        return ($member && Permission::checkMember($member, array('ADMIN', 'SITETREE_EDIT_ALL')));
146
    }
147
148
    /**
149
     * @param Member $member
0 ignored issues
show
Documentation introduced by
Should the type for parameter $member not be Member|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
150
     *
151
     * @return boolean
152
     */
153
    public function canCreate($member = null)
154
    {
155
        return $this->canEdit($member);
156
    }
157
158
    /**
159
     * @param Member $member
0 ignored issues
show
Documentation introduced by
Should the type for parameter $member not be Member|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
160
     *
161
     * @return boolean
162
     */
163
    public function canDelete($member = null)
164
    {
165
        if (!$member || !(is_a($member, 'Member')) || is_numeric($member)) {
166
            $member = Member::currentUser();
167
        }
168
169
        $results = $this->extend('canDelete', $member);
170
171
        if ($results && is_array($results)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $results 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...
172
            if (!min($results)) {
173
                return false;
174
            }
175
        }
176
177
        return $this->canView();
178
    }
179
180
181
182
    /**
183
     * Associates this document with a Page. This method does nothing if the
184
     * association already exists.
185
     *
186
     * This could be a simple wrapper around $myDoc->Pages()->add($myPage) to
187
     * add a many_many relation.
188
     *
189
     * @param SiteTree $pageObject Page object to associate this Document with
190
     *
191
     * @return DMSDocument
192
     */
193
    public function addPage($pageObject)
194
    {
195
        $this->Pages()->add($pageObject);
196
197
        DB::query(
198
            "UPDATE \"DMSDocument_Pages\" SET \"DocumentSort\"=\"DocumentSort\"+1"
199
            . " WHERE \"SiteTreeID\" = $pageObject->ID"
200
        );
201
202
        return $this;
203
    }
204
205
    /**
206
     * Associates this DMSDocument with a set of Pages. This method loops
207
     * through a set of page ids, and then associates this DMSDocument with the
208
     * individual Page with the each page id in the set.
209
     *
210
     * @param array $pageIDs
211
     *
212
     * @return DMSDocument
213
     */
214
    public function addPages($pageIDs)
215
    {
216
        foreach ($pageIDs as $id) {
217
            $pageObject = DataObject::get_by_id("SiteTree", $id);
218
219
            if ($pageObject && $pageObject->exists()) {
220
                $this->addPage($pageObject);
0 ignored issues
show
Compatibility introduced by
$pageObject of type object<DataObject> is not a sub-type of object<SiteTree>. It seems like you assume a child class of the class DataObject to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
221
            }
222
        }
223
224
        return $this;
225
    }
226
227
    /**
228
     * Removes the association between this Document and a Page. This method
229
     * does nothing if the association does not exist.
230
     *
231
     * @param SiteTree $pageObject Page object to remove the association to
232
     *
233
     * @return DMSDocument
234
     */
235
    public function removePage($pageObject)
236
    {
237
        $this->Pages()->remove($pageObject);
0 ignored issues
show
Documentation introduced by
$pageObject is of type object<SiteTree>, but the function expects a object<DataClass>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
238
239
        return $this;
240
    }
241
242
    /**
243
     * @see getPages()
244
     *
245
     * @return DataList
246
     */
247
    public function Pages()
248
    {
249
        $pages = $this->getManyManyComponents('Pages');
250
        $this->extend('updatePages', $pages);
251
252
        return $pages;
253
    }
254
255
    /**
256
     * Returns a list of the Page objects associated with this Document.
257
     *
258
     * @return DataList
259
     */
260
    public function getPages()
261
    {
262
        return $this->Pages();
263
    }
264
265
    /**
266
     * Removes all associated Pages from the DMSDocument
267
     *
268
     * @return DMSDocument
269
     */
270
    public function removeAllPages()
271
    {
272
        $this->Pages()->removeAll();
273
274
        return $this;
275
    }
276
277
    /**
278
     * Increase ViewCount by 1, without update any other record fields such as
279
     * LastEdited.
280
     *
281
     * @return DMSDocument
282
     */
283
    public function trackView()
284
    {
285
        if ($this->ID > 0) {
286
            $count = $this->ViewCount + 1;
287
288
            $this->ViewCount = $count;
289
290
            DB::query("UPDATE \"DMSDocument\" SET \"ViewCount\"='$count' WHERE \"ID\"={$this->ID}");
291
        }
292
293
        return $this;
294
    }
295
296
297
    /**
298
     * Adds a metadata tag to the Document. The tag has a category and a value.
299
     *
300
     * Each category can have multiple values by default. So:
301
     * addTag("fruit","banana") addTag("fruit", "apple") will add two items.
302
     *
303
     * However, if the third parameter $multiValue is set to 'false', then all
304
     * updates to a category only ever update a single value. So:
305
     * addTag("fruit","banana") addTag("fruit", "apple") would result in a
306
     * single metadata tag: fruit->apple.
307
     *
308
     * Can could be implemented as a key/value store table (although it is more
309
     * like category/value, because the same category can occur multiple times)
310
     *
311
     * @param string $category of a metadata category to add (required)
312
     * @param string $value of a metadata value to add (required)
313
     * @param bool $multiValue Boolean that determines if the category is
314
     *                  multi-value or single-value (optional)
315
     *
316
     * @return DMSDocument
317
     */
318
    public function addTag($category, $value, $multiValue = true)
319
    {
320
        if ($multiValue) {
321
            //check for a duplicate tag, don't add the duplicate
322
            $currentTag = $this->Tags()->filter(array('Category' => $category, 'Value' => $value));
0 ignored issues
show
Documentation Bug introduced by
The method Tags does not exist on object<DMSDocument>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
323
            if ($currentTag->Count() == 0) {
324
                //multi value tag
325
                $tag = new DMSTag();
326
                $tag->Category = $category;
0 ignored issues
show
Documentation introduced by
The property Category does not exist on object<DMSTag>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
327
                $tag->Value = $value;
0 ignored issues
show
Documentation introduced by
The property Value does not exist on object<DMSTag>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
328
                $tag->MultiValue = true;
0 ignored issues
show
Documentation introduced by
The property MultiValue does not exist on object<DMSTag>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
329
                $tag->write();
330
                $tag->Documents()->add($this);
0 ignored issues
show
Documentation Bug introduced by
The method Documents does not exist on object<DMSTag>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
331
            } else {
332
                //add the relation between the tag and document
333
                foreach ($currentTag as $tagObj) {
334
                    $tagObj->Documents()->add($this);
335
                }
336
            }
337
        } else {
338
            //single value tag
339
            $currentTag = $this->Tags()->filter(array('Category' => $category));
0 ignored issues
show
Documentation Bug introduced by
The method Tags does not exist on object<DMSDocument>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
340
            $tag = null;
0 ignored issues
show
Unused Code introduced by
$tag 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...
341
            if ($currentTag->Count() == 0) {
342
                //create the single-value tag
343
                $tag = new DMSTag();
344
                $tag->Category = $category;
0 ignored issues
show
Documentation introduced by
The property Category does not exist on object<DMSTag>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
345
                $tag->Value = $value;
0 ignored issues
show
Documentation introduced by
The property Value does not exist on object<DMSTag>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
346
                $tag->MultiValue = false;
0 ignored issues
show
Documentation introduced by
The property MultiValue does not exist on object<DMSTag>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
347
                $tag->write();
348
            } else {
349
                //update the single value tag
350
                $tag = $currentTag->first();
351
                $tag->Value = $value;
352
                $tag->MultiValue = false;
353
                $tag->write();
354
            }
355
356
            // regardless of whether we created a new tag or are just updating an
357
            // existing one, add the relation
358
            $tag->Documents()->add($this);
359
        }
360
361
        return $this;
362
    }
363
364
    /**
365
     * @param string $category
366
     * @param string $value
0 ignored issues
show
Documentation introduced by
Should the type for parameter $value not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
367
     *
368
     * @return DataList
369
     */
370
    protected function getTagsObjects($category, $value = null)
371
    {
372
        $valueFilter = array("Category" => $category);
373
        if (!empty($value)) {
374
            $valueFilter['Value'] = $value;
375
        }
376
377
        $tags = $this->Tags()->filter($valueFilter);
0 ignored issues
show
Documentation Bug introduced by
The method Tags does not exist on object<DMSDocument>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
378
        return $tags;
379
    }
380
381
    /**
382
     * Fetches all tags associated with this DMSDocument within a given
383
     * category. If a value is specified this method tries to fetch that
384
     * specific tag.
385
     *
386
     * @param string $category metadata category to get
387
     * @param string $value value of the tag to get
0 ignored issues
show
Documentation introduced by
Should the type for parameter $value not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
388
     *
389
     * @return array Strings of all the tags or null if there is no match found
0 ignored issues
show
Documentation introduced by
Should the return type not be array|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
390
     */
391
    public function getTagsList($category, $value = null)
392
    {
393
        $tags = $this->getTagsObjects($category, $value);
394
395
        $returnArray = null;
396
397
        if ($tags->Count() > 0) {
398
            $returnArray = array();
399
400
            foreach ($tags as $t) {
401
                $returnArray[] = $t->Value;
402
            }
403
        }
404
405
        return $returnArray;
406
    }
407
408
    /**
409
     * Removes a tag from the Document. If you only set a category, then all
410
     * values in that category are deleted.
411
     *
412
     * If you specify both a category and a value, then only that single
413
     * category/value pair is deleted.
414
     *
415
     * Nothing happens if the category or the value do not exist.
416
     *
417
     * @param string $category Category to remove
418
     * @param string $value Value to remove
0 ignored issues
show
Documentation introduced by
Should the type for parameter $value not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
419
     *
420
     * @return DMSDocument
421
     */
422
    public function removeTag($category, $value = null)
423
    {
424
        $tags = $this->getTagsObjects($category, $value);
425
426
        if ($tags->Count() > 0) {
427
            foreach ($tags as $t) {
428
                $documentList = $t->Documents();
429
430
                //remove the relation between the tag and the document
431
                $documentList->remove($this);
432
433
                //delete the entire tag if it has no relations left
434
                if ($documentList->Count() == 0) {
435
                    $t->delete();
436
                }
437
            }
438
        }
439
440
        return $this;
441
    }
442
443
    /**
444
     * Deletes all tags associated with this Document.
445
     *
446
     * @return DMSDocument
447
     */
448
    public function removeAllTags()
449
    {
450
        $allTags = $this->Tags();
0 ignored issues
show
Documentation Bug introduced by
The method Tags does not exist on object<DMSDocument>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
451
452
        foreach ($allTags as $tag) {
453
            $documentlist = $tag->Documents();
454
            $documentlist->remove($this);
455
            if ($tag->Documents()->Count() == 0) {
456
                $tag->delete();
457
            }
458
        }
459
460
        return $this;
461
    }
462
463
    /**
464
     * Returns a link to download this document from the DMS store.
465
     *
466
     * @return string
467
     */
468
    public function getLink()
469
    {
470
        return Controller::join_links(Director::baseURL(), 'dmsdocument/'.$this->ID);
471
    }
472
473
    /**
474
     * @return string
475
     */
476
    public function Link()
477
    {
478
        return $this->getLink();
479
    }
480
481
    /**
482
     * Hides the document, so it does not show up when getByPage($myPage) is
483
     * called (without specifying the $showEmbargoed = true parameter).
484
     *
485
     * This is similar to expire, except that this method should be used to hide
486
     * documents that have not yet gone live.
487
     *
488
     * @param bool $write Save change to the database
489
     *
490
     * @return DMSDocument
491
     */
492
    public function embargoIndefinitely($write = true)
493
    {
494
        $this->EmbargoedIndefinitely = true;
495
496
        if ($write) {
497
            $this->write();
498
        }
499
500
        return $this;
501
    }
502
503
    /**
504
     * Hides the document until any page it is linked to is published
505
     *
506
     * @param bool $write Save change to database
507
     *
508
     * @return DMSDocument
509
     */
510
    public function embargoUntilPublished($write = true)
511
    {
512
        $this->EmbargoedUntilPublished = true;
513
514
        if ($write) {
515
            $this->write();
516
        }
517
518
        return $this;
519
    }
520
521
    /**
522
     * Returns if this is Document is embargoed or expired.
523
     *
524
     * Also, returns if the document should be displayed on the front-end,
525
     * respecting the current reading mode of the site and the embargo status.
526
     *
527
     * I.e. if a document is embargoed until published, then it should still
528
     * show up in draft mode.
529
     *
530
     * @return bool
531
     */
532
    public function isHidden()
533
    {
534
        $hidden = $this->isEmbargoed() || $this->isExpired();
535
        $readingMode = Versioned::get_reading_mode();
536
537
        if ($readingMode == "Stage.Stage") {
538
            if ($this->EmbargoedUntilPublished == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
539
                $hidden = false;
540
            }
541
        }
542
543
        return $hidden;
544
    }
545
546
    /**
547
     * Returns if this is Document is embargoed.
548
     *
549
     * @return bool
550
     */
551
    public function isEmbargoed()
552
    {
553
        if (is_object($this->EmbargoedUntilDate)) {
554
            $this->EmbargoedUntilDate = $this->EmbargoedUntilDate->Value;
0 ignored issues
show
Bug introduced by
The property Value does not seem to exist in DateTime.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
555
        }
556
557
        $embargoed = false;
558
559
        if ($this->EmbargoedIndefinitely) {
560
            $embargoed = true;
561
        } elseif ($this->EmbargoedUntilPublished) {
562
            $embargoed = true;
563
        } elseif (!empty($this->EmbargoedUntilDate)) {
564
            if (SS_Datetime::now()->Value < $this->EmbargoedUntilDate) {
565
                $embargoed = true;
566
            }
567
        }
568
569
        return $embargoed;
570
    }
571
572
    /**
573
     * Hides the document, so it does not show up when getByPage($myPage) is
574
     * called. Automatically un-hides the Document at a specific date.
575
     *
576
     * @param string $datetime date time value when this Document should expire.
577
     * @param bool $write
578
     *
579
     * @return DMSDocument
580
     */
581 View Code Duplication
    public function embargoUntilDate($datetime, $write = true)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
582
    {
583
        $this->EmbargoedUntilDate = DBField::create_field('SS_Datetime', $datetime)->Format('Y-m-d H:i:s');
584
585
        if ($write) {
586
            $this->write();
587
        }
588
589
        return $this;
590
    }
591
592
    /**
593
     * Clears any previously set embargos, so the Document always shows up in
594
     * all queries.
595
     *
596
     * @param bool $write
597
     *
598
     * @return DMSDocument
599
     */
600
    public function clearEmbargo($write = true)
601
    {
602
        $this->EmbargoedIndefinitely = false;
603
        $this->EmbargoedUntilPublished = false;
604
        $this->EmbargoedUntilDate = null;
605
606
        if ($write) {
607
            $this->write();
608
        }
609
610
        return $this;
611
    }
612
613
    /**
614
     * Returns if this is Document is expired.
615
     *
616
     * @return bool
617
     */
618
    public function isExpired()
619
    {
620
        if (is_object($this->ExpireAtDate)) {
621
            $this->ExpireAtDate = $this->ExpireAtDate->Value;
0 ignored issues
show
Bug introduced by
The property Value does not seem to exist in DateTime.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
622
        }
623
624
        $expired = false;
625
626
        if (!empty($this->ExpireAtDate)) {
627
            if (SS_Datetime::now()->Value >= $this->ExpireAtDate) {
628
                $expired = true;
629
            }
630
        }
631
632
        return $expired;
633
    }
634
635
    /**
636
     * Hides the document at a specific date, so it does not show up when
637
     * getByPage($myPage) is called.
638
     *
639
     * @param string $datetime date time value when this Document should expire
640
     * @param bool $write
641
     *
642
     * @return DMSDocument
643
     */
644 View Code Duplication
    public function expireAtDate($datetime, $write = true)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
645
    {
646
        $this->ExpireAtDate = DBField::create_field('SS_Datetime', $datetime)->Format('Y-m-d H:i:s');
647
648
        if ($write) {
649
            $this->write();
650
        }
651
652
        return $this;
653
    }
654
655
    /**
656
     * Clears any previously set expiry.
657
     *
658
     * @param bool $write
659
     *
660
     * @return DMSDocument
661
     */
662
    public function clearExpiry($write = true)
663
    {
664
        $this->ExpireAtDate = null;
665
666
        if ($write) {
667
            $this->write();
668
        }
669
670
        return $this;
671
    }
672
673
    /**
674
     * Returns a DataList of all previous Versions of this document (check the
675
     * LastEdited date of each object to find the correct one).
676
     *
677
     * If {@link DMSDocument_versions::$enable_versions} is disabled then an
678
     * Exception is thrown
679
     *
680
     * @throws Exception
681
     *
682
     * @return DataList List of Document objects
683
     */
684
    public function getVersions()
685
    {
686
        if (!DMSDocument_versions::$enable_versions) {
687
            throw new Exception("DMSDocument versions are disabled");
688
        }
689
690
        return DMSDocument_versions::get_versions($this);
691
    }
692
693
    /**
694
     * Returns the full filename of the document stored in this object.
695
     *
696
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be string|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
697
     */
698
    public function getFullPath()
699
    {
700
        if ($this->Filename) {
701
            return DMS::get_dms_path() . DIRECTORY_SEPARATOR . $this->Folder . DIRECTORY_SEPARATOR . $this->Filename;
702
        }
703
704
        return null;
705
    }
706
707
    /**
708
     * Returns the filename of this asset.
709
     *
710
     * @return string
711
     */
712
    public function getFileName()
713
    {
714
        if ($this->getField('Filename')) {
715
            return $this->getField('Filename');
716
        } else {
717
            return ASSETS_DIR . '/';
718
        }
719
    }
720
721
    /**
722
     * @return string
723
     */
724
    public function getName()
725
    {
726
        return $this->getField('Title');
727
    }
728
729
730
    /**
731
     * @return string
732
     */
733
    public function getFilenameWithoutID()
734
    {
735
        $filenameParts = explode('~', $this->Filename);
736
        $filename = array_pop($filenameParts);
737
738
        return $filename;
739
    }
740
741
    /**
742
     * @return string
743
     */
744
    public function getStorageFolder()
745
    {
746
        return DMS::get_dms_path() . DIRECTORY_SEPARATOR . DMS::get_storage_folder($this->ID);
747
    }
748
749
    /**
750
     * Deletes the DMSDocument, its underlying file, as well as any tags related
751
     * to this DMSDocument. Also calls the parent DataObject's delete method in
752
     * order to complete an cascade.
753
     *
754
     * @return void
755
     */
756
    public function delete()
757
    {
758
        // remove tags
759
        $this->removeAllTags();
760
761
        // delete the file (and previous versions of files)
762
        $filesToDelete = array();
763
        $storageFolder = $this->getStorageFolder();
764
765
        if (file_exists($storageFolder)) {
766
            if ($handle = opendir($storageFolder)) {
767
                while (false !== ($entry = readdir($handle))) {
768
                    // only delete if filename starts the the relevant ID
769
                    if (strpos($entry, $this->ID.'~') === 0) {
770
                        $filesToDelete[] = $entry;
771
                    }
772
                }
773
774
                closedir($handle);
775
776
                //delete all this files that have the id of this document
777
                foreach ($filesToDelete as $file) {
778
                    $filePath = $storageFolder .DIRECTORY_SEPARATOR . $file;
779
780
                    if (is_file($filePath)) {
781
                        unlink($filePath);
782
                    }
783
                }
784
            }
785
        }
786
787
        $this->removeAllPages();
788
789
        // get rid of any versions have saved for this DMSDocument, too
790
        if (DMSDocument_versions::$enable_versions) {
791
            $versions = $this->getVersions();
792
793
            if ($versions->Count() > 0) {
794
                foreach ($versions as $v) {
795
                    $v->delete();
796
                }
797
            }
798
        }
799
800
        parent::delete();
801
    }
802
803
804
805
    /**
806
     * Relate an existing file on the filesystem to the document.
807
     *
808
     * Copies the file to the new destination, as defined in {@link get_DMS_path()}.
809
     *
810
     * @param string $filePath Path to file, relative to webroot.
811
     *
812
     * @return DMSDocument
813
     */
814
    public function storeDocument($filePath)
815
    {
816
        if (empty($this->ID)) {
817
            user_error("Document must be written to database before it can store documents", E_USER_ERROR);
818
        }
819
820
        // calculate all the path to copy the file to
821
        $fromFilename = basename($filePath);
822
        $toFilename = $this->ID. '~' . $fromFilename; //add the docID to the start of the Filename
823
        $toFolder = DMS::get_storage_folder($this->ID);
824
        $toPath = DMS::get_dms_path() . DIRECTORY_SEPARATOR . $toFolder . DIRECTORY_SEPARATOR . $toFilename;
825
826
        DMS::create_storage_folder(DMS::get_dms_path() . DIRECTORY_SEPARATOR . $toFolder);
827
828
        //copy the file into place
829
        $fromPath = BASE_PATH . DIRECTORY_SEPARATOR . $filePath;
830
831
        //version the existing file (copy it to a new "very specific" filename
832
        if (DMSDocument_versions::$enable_versions) {
833
            DMSDocument_versions::create_version($this);
834
        } else {    //otherwise delete the old document file
835
            $oldPath = $this->getFullPath();
836
            if (file_exists($oldPath)) {
837
                unlink($oldPath);
838
            }
839
        }
840
841
        copy($fromPath, $toPath);   //this will overwrite the existing file (if present)
842
843
        //write the filename of the stored document
844
        $this->Filename = $toFilename;
845
        $this->Folder = strval($toFolder);
846
847
        $extension = pathinfo($this->Filename, PATHINFO_EXTENSION);
848
849
        if (empty($this->Title)) {
850
            // don't overwrite existing document titles
851
            $this->Title = basename($filePath, '.'.$extension);
852
        }
853
854
        $this->LastChanged = SS_Datetime::now()->Rfc2822();
855
        $this->write();
856
857
        return $this;
858
    }
859
860
    /**
861
     * Takes a File object or a String (path to a file) and copies it into the
862
     * DMS, replacing the original document file but keeping the rest of the
863
     * document unchanged.
864
     *
865
     * @param File|string $file path to a file to store
866
     *
867
     * @return DMSDocument object that we replaced the file in
868
     */
869
    public function replaceDocument($file)
870
    {
871
        $filePath = DMS::transform_file_to_file_path($file);
872
        $doc = $this->storeDocument($filePath); // replace the document
873
874
        return $doc;
875
    }
876
877
878
    /**
879
     * Return the type of file for the given extension
880
     * on the current file name.
881
     *
882
     * @param string $ext
883
     *
884
     * @return string
885
     */
886
    public static function get_file_type($ext)
887
    {
888
        $types = array(
889
            'gif' => 'GIF image - good for diagrams',
890
            'jpg' => 'JPEG image - good for photos',
891
            'jpeg' => 'JPEG image - good for photos',
892
            'png' => 'PNG image - good general-purpose format',
893
            'ico' => 'Icon image',
894
            'tiff' => 'Tagged image format',
895
            'doc' => 'Word document',
896
            'xls' => 'Excel spreadsheet',
897
            'zip' => 'ZIP compressed file',
898
            'gz' => 'GZIP compressed file',
899
            'dmg' => 'Apple disk image',
900
            'pdf' => 'Adobe Acrobat PDF file',
901
            'mp3' => 'MP3 audio file',
902
            'wav' => 'WAV audo file',
903
            'avi' => 'AVI video file',
904
            'mpg' => 'MPEG video file',
905
            'mpeg' => 'MPEG video file',
906
            'js' => 'Javascript file',
907
            'css' => 'CSS file',
908
            'html' => 'HTML file',
909
            'htm' => 'HTML file'
910
        );
911
912
        return isset($types[$ext]) ? $types[$ext] : $ext;
913
    }
914
915
916
    /**
917
     * Returns the Description field with HTML <br> tags added when there is a
918
     * line break.
919
     *
920
     * @return string
921
     */
922
    public function getDescriptionWithLineBreak()
923
    {
924
        return nl2br($this->getField('Description'));
925
    }
926
927
    /**
928
     * @return FieldList
929
     */
930
    public function getCMSFields()
931
    {
932
        //include JS to handling showing and hiding of bottom "action" tabs
933
        Requirements::javascript(DMS_DIR.'/javascript/DMSDocumentCMSFields.js');
934
        Requirements::css(DMS_DIR.'/css/DMSDocumentCMSFields.css');
935
936
        $fields = new FieldList();  //don't use the automatic scaffolding, it is slow and unnecessary here
937
938
        $extraTasks = '';   //additional text to inject into the list of tasks at the bottom of a DMSDocument CMSfield
939
940
        //get list of shortcode page relations
941
        $relationFinder = new ShortCodeRelationFinder();
942
        $relationList = $relationFinder->getList($this->ID);
943
944
        $fieldsTop = $this->getFieldsForFile($relationList->count());
945
        $fields->add($fieldsTop);
946
947
        $fields->add(new TextField('Title', 'Title'));
948
        $fields->add(new TextareaField('Description', 'Description'));
949
950
        $downloadBehaviorSource = array(
951
            'open' => _t('DMSDocument.OPENINBROWSER', 'Open in browser'),
952
            'download' => _t('DMSDocument.FORCEDOWNLOAD', 'Force download'),
953
        );
954
        $defaultDownloadBehaviour = Config::inst()->get('DMSDocument', 'default_download_behaviour');
955
        if (!isset($downloadBehaviorSource[$defaultDownloadBehaviour])) {
956
            user_error('Default download behaviour "' . $defaultDownloadBehaviour . '" not supported.', E_USER_WARNING);
957
        } else {
958
            $downloadBehaviorSource[$defaultDownloadBehaviour] .= ' (' . _t('DMSDocument.DEFAULT', 'default') . ')';
959
        }
960
961
        $fields->add(
962
            OptionsetField::create(
963
                'DownloadBehavior',
964
                _t('DMSDocument.DOWNLOADBEHAVIOUR', 'Download behavior'),
965
                $downloadBehaviorSource,
966
                $defaultDownloadBehaviour
967
            )
968
            ->setDescription(
969
                'How the visitor will view this file. <strong>Open in browser</strong> '
970
                . 'allows files to be opened in a new tab.'
971
            )
972
        );
973
974
        //create upload field to replace document
975
        $uploadField = new DMSUploadField('ReplaceFile', 'Replace file');
976
        $uploadField->setConfig('allowedMaxFileNumber', 1);
977
        $uploadField->setConfig('downloadTemplateName', 'ss-dmsuploadfield-downloadtemplate');
978
        $uploadField->setRecord($this);
979
980
        $gridFieldConfig = GridFieldConfig::create()->addComponents(
981
            new GridFieldToolbarHeader(),
982
            new GridFieldSortableHeader(),
983
            new GridFieldDataColumns(),
984
            new GridFieldPaginator(30),
985
            //new GridFieldEditButton(),
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
986
            new GridFieldDetailForm()
987
        );
988
989
        $gridFieldConfig->getComponentByType('GridFieldDataColumns')
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface GridFieldComponent as the method setDisplayFields() does only exist in the following implementations of said interface: GridFieldDataColumns, GridFieldEditableColumns, GridFieldExternalLink.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
990
            ->setDisplayFields(array(
991
                'Title'=>'Title',
992
                'ClassName'=>'Page Type',
993
                'ID'=>'Page ID'
994
            ))
995
            ->setFieldFormatting(array(
996
                'Title'=>sprintf(
997
                    '<a class=\"cms-panel-link\" href=\"%s/$ID\">$Title</a>',
998
                    singleton('CMSPageEditController')->Link('show')
999
                )
1000
            ));
1001
1002
        $pagesGrid = GridField::create(
1003
            'Pages',
1004
            _t('DMSDocument.RelatedPages', 'Related Pages'),
1005
            $this->Pages(),
1006
            $gridFieldConfig
1007
        );
1008
1009
        $referencesGrid = GridField::create(
1010
            'References',
1011
            _t('DMSDocument.RelatedReferences', 'Related References'),
1012
            $relationList,
1013
            $gridFieldConfig
1014
        );
1015
1016
        if (DMSDocument_versions::$enable_versions) {
1017
            $versionsGridFieldConfig = GridFieldConfig::create()->addComponents(
1018
                new GridFieldToolbarHeader(),
1019
                new GridFieldSortableHeader(),
1020
                new GridFieldDataColumns(),
1021
                new GridFieldPaginator(30)
1022
            );
1023
            $versionsGridFieldConfig->getComponentByType('GridFieldDataColumns')
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface GridFieldComponent as the method setDisplayFields() does only exist in the following implementations of said interface: GridFieldDataColumns, GridFieldEditableColumns, GridFieldExternalLink.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
1024
                ->setDisplayFields(Config::inst()->get('DMSDocument_versions', 'display_fields'))
1025
                ->setFieldCasting(array('LastChanged'=>"Datetime->Ago"))
1026
                ->setFieldFormatting(
1027
                    array(
1028
                        'FilenameWithoutID' => '<a target=\'_blank\' class=\'file-url\' href=\'$Link\'>'
1029
                            . '$FilenameWithoutID</a>'
1030
                    )
1031
                );
1032
1033
            $versionsGrid =  GridField::create(
1034
                'Versions',
1035
                _t('DMSDocument.Versions', 'Versions'),
1036
                $this->getVersions(),
1037
                $versionsGridFieldConfig
1038
            );
1039
            $extraTasks .= '<li class="ss-ui-button" data-panel="find-versions">Versions</li>';
1040
        }
1041
1042
        $fields->add(new LiteralField(
1043
            'BottomTaskSelection',
1044
            '<div id="Actions" class="field actions"><label class="left">Actions</label><ul>'
1045
            . '<li class="ss-ui-button" data-panel="embargo">Embargo</li>'
1046
            . '<li class="ss-ui-button" data-panel="expiry">Expiry</li>'
1047
            . '<li class="ss-ui-button" data-panel="replace">Replace</li>'
1048
            . '<li class="ss-ui-button" data-panel="find-usage">Usage</li>'
1049
            . '<li class="ss-ui-button" data-panel="find-references">References</li>'
1050
            . '<li class="ss-ui-button" data-panel="find-relateddocuments">Related Documents</li>'
1051
            . $extraTasks
1052
            . '</ul></div>'
1053
        ));
1054
1055
        $embargoValue = 'None';
1056
        if ($this->EmbargoedIndefinitely) {
1057
            $embargoValue = 'Indefinitely';
1058
        } elseif ($this->EmbargoedUntilPublished) {
1059
            $embargoValue = 'Published';
1060
        } elseif (!empty($this->EmbargoedUntilDate)) {
1061
            $embargoValue = 'Date';
1062
        }
1063
        $embargo = new OptionsetField(
1064
            'Embargo',
1065
            'Embargo',
1066
            array(
1067
                'None' => 'None',
1068
                'Published' => 'Hide document until page is published',
1069
                'Indefinitely' => 'Hide document indefinitely',
1070
                'Date' => 'Hide until set date'
1071
            ),
1072
            $embargoValue
1073
        );
1074
        $embargoDatetime = DatetimeField::create('EmbargoedUntilDate', '');
1075
        $embargoDatetime->getDateField()
1076
            ->setConfig('showcalendar', true)
1077
            ->setConfig('dateformat', 'dd-MM-yyyy')
1078
            ->setConfig('datavalueformat', 'dd-MM-yyyy');
1079
1080
        $expiryValue = 'None';
1081
        if (!empty($this->ExpireAtDate)) {
1082
            $expiryValue = 'Date';
1083
        }
1084
        $expiry = new OptionsetField(
1085
            'Expiry',
1086
            'Expiry',
1087
            array(
1088
                'None' => 'None',
1089
                'Date' => 'Set document to expire on'
1090
            ),
1091
            $expiryValue
1092
        );
1093
        $expiryDatetime = DatetimeField::create('ExpireAtDate', '');
1094
        $expiryDatetime->getDateField()
1095
            ->setConfig('showcalendar', true)
1096
            ->setConfig('dateformat', 'dd-MM-yyyy')
1097
            ->setConfig('datavalueformat', 'dd-MM-yyyy');
1098
1099
        // This adds all the actions details into a group.
1100
        // Embargo, History, etc to go in here
1101
        // These are toggled on and off via the Actions Buttons above
1102
        // exit('hit');
0 ignored issues
show
Unused Code Comprehensibility introduced by
84% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1103
        $actionsPanel = FieldGroup::create(
1104
            FieldGroup::create($embargo, $embargoDatetime)->addExtraClass('embargo'),
1105
            FieldGroup::create($expiry, $expiryDatetime)->addExtraClass('expiry'),
1106
            FieldGroup::create($uploadField)->addExtraClass('replace'),
1107
            FieldGroup::create($pagesGrid)->addExtraClass('find-usage'),
1108
            FieldGroup::create($referencesGrid)->addExtraClass('find-references'),
1109
            FieldGroup::create($versionsGrid)->addExtraClass('find-versions'),
0 ignored issues
show
Bug introduced by
The variable $versionsGrid does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1110
            FieldGroup::create($this->getRelatedDocumentsGridField())->addExtraClass('find-relateddocuments')
1111
        );
1112
1113
        $actionsPanel->setName("ActionsPanel");
1114
        $actionsPanel->addExtraClass("DMSDocumentActionsPanel");
1115
        $fields->push($actionsPanel);
1116
1117
        $this->addPermissionsFields($fields);
1118
        $this->extend('updateCMSFields', $fields);
1119
1120
        return $fields;
1121
    }
1122
1123
    /**
1124
     * Adds permissions selection fields to the FieldList.
1125
     *
1126
     * @param FieldList $fields
1127
     */
1128
    public function addPermissionsFields($fields)
1129
    {
1130
        $showFields = array(
1131
            'CanViewType'  => '',
1132
            'ViewerGroups' => 'hide',
1133
            'CanEditType'  => '',
1134
            'EditorGroups' => 'hide',
1135
        );
1136
        /** @var SiteTree $siteTree */
1137
        $siteTree = singleton('SiteTree');
1138
        $settingsFields = $siteTree->getSettingsFields();
1139
1140
        foreach ($showFields as $name => $extraCss) {
1141
            $compositeName = "Root.Settings.$name";
1142
            /** @var FormField $field */
1143
            if ($field = $settingsFields->fieldByName($compositeName)) {
1144
                $field->addExtraClass($extraCss);
1145
                $title = str_replace('page', 'document', $field->Title());
1146
                $field->setTitle($title);
1147
1148
                //Remove Inherited source option from DropdownField
1149
                if ($field instanceof DropdownField) {
1150
                    $options = $field->getSource();
1151
                    unset($options['Inherit']);
1152
                    $field->setSource($options);
1153
                }
1154
                $fields->push($field);
1155
            }
1156
        }
1157
1158
        $this->extend('updatePermissionsFields', $fields);
1159
    }
1160
1161
    public function onBeforeWrite()
1162
    {
1163
        parent::onBeforeWrite();
1164
1165
        if (isset($this->Embargo)) {
1166
            //set the embargo options from the OptionSetField created in the getCMSFields method
1167
            //do not write after clearing the embargo (write happens automatically)
1168
            $savedDate = $this->EmbargoedUntilDate;
1169
            $this->clearEmbargo(false); //clear all previous settings and re-apply them on save
1170
1171
            if ($this->Embargo == 'Published') {
0 ignored issues
show
Bug introduced by
The property Embargo does not seem to exist. Did you mean EmbargoedIndefinitely?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
1172
                $this->embargoUntilPublished(false);
1173
            }
1174
            if ($this->Embargo == 'Indefinitely') {
0 ignored issues
show
Bug introduced by
The property Embargo does not seem to exist. Did you mean EmbargoedIndefinitely?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
1175
                $this->embargoIndefinitely(false);
1176
            }
1177
            if ($this->Embargo == 'Date') {
0 ignored issues
show
Bug introduced by
The property Embargo does not seem to exist. Did you mean EmbargoedIndefinitely?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
1178
                $this->embargoUntilDate($savedDate, false);
0 ignored issues
show
Documentation introduced by
$savedDate is of type object<DateTime>|null, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1179
            }
1180
        }
1181
1182
        if (isset($this->Expiry)) {
1183
            if ($this->Expiry == 'Date') {
0 ignored issues
show
Documentation introduced by
The property Expiry does not exist on object<DMSDocument>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1184
                $this->expireAtDate($this->ExpireAtDate, false);
0 ignored issues
show
Documentation introduced by
$this->ExpireAtDate is of type object<DateTime>|null, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1185
            } else {
1186
                $this->clearExpiry(false);
1187
            } //clear all previous settings
1188
        }
1189
    }
1190
1191
    /**
1192
     * Return the relative URL of an icon for the file type, based on the
1193
     * {@link appCategory()} value.
1194
     *
1195
     * Images are searched for in "dms/images/app_icons/".
1196
     *
1197
     * @return string
1198
     */
1199
    public function Icon($ext)
1200
    {
1201
        if (!Director::fileExists(DMS_DIR."/images/app_icons/{$ext}_32.png")) {
1202
            $ext = File::get_app_category($ext);
1203
        }
1204
1205
        if (!Director::fileExists(DMS_DIR."/images/app_icons/{$ext}_32.png")) {
1206
            $ext = "generic";
1207
        }
1208
1209
        return DMS_DIR."/images/app_icons/{$ext}_32.png";
1210
    }
1211
1212
    /**
1213
     * Return the extension of the file associated with the document
1214
     *
1215
     * @return string
1216
     */
1217
    public function getExtension()
1218
    {
1219
        return strtolower(pathinfo($this->Filename, PATHINFO_EXTENSION));
1220
    }
1221
1222
    /**
1223
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be string|false?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
1224
     */
1225
    public function getSize()
1226
    {
1227
        $size = $this->getAbsoluteSize();
1228
        return ($size) ? File::format_size($size) : false;
1229
    }
1230
1231
    /**
1232
     * Return the size of the file associated with the document.
1233
     *
1234
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be integer|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
1235
     */
1236
    public function getAbsoluteSize()
1237
    {
1238
        return file_exists($this->getFullPath()) ? filesize($this->getFullPath()) : null;
1239
    }
1240
1241
    /**
1242
     * An alias to DMSDocument::getSize()
1243
     *
1244
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be string|false?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
1245
     */
1246
    public function getFileSizeFormatted()
1247
    {
1248
        return $this->getSize();
1249
    }
1250
1251
1252
    /**
1253
     * @return FieldList
0 ignored issues
show
Documentation introduced by
Should the return type not be FieldGroup?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
1254
     */
1255
    protected function getFieldsForFile($relationListCount)
1256
    {
1257
        $extension = $this->getExtension();
1258
1259
        $previewField = new LiteralField(
1260
            "ImageFull",
1261
            "<img id='thumbnailImage' class='thumbnail-preview' src='{$this->Icon($extension)}?r="
1262
            . rand(1, 100000) . "' alt='{$this->Title}' />\n"
1263
        );
1264
1265
        //count the number of pages this document is published on
1266
        $publishedOnCount = $this->Pages()->Count();
1267
        $publishedOnValue = "$publishedOnCount pages";
1268
        if ($publishedOnCount == 1) {
1269
            $publishedOnValue = "$publishedOnCount page";
1270
        }
1271
1272
        $relationListCountValue = "$relationListCount pages";
1273
        if ($relationListCount == 1) {
1274
            $relationListCountValue = "$relationListCount page";
1275
        }
1276
1277
        $fields = new FieldGroup(
1278
            $filePreview = CompositeField::create(
1279
                CompositeField::create(
1280
                    $previewField
1281
                )->setName("FilePreviewImage")->addExtraClass('cms-file-info-preview'),
1282
                CompositeField::create(
1283
                    CompositeField::create(
1284
                        new ReadonlyField("ID", "ID number". ':', $this->ID),
1285
                        new ReadonlyField(
1286
                            "FileType",
1287
                            _t('AssetTableField.TYPE', 'File type') . ':',
1288
                            self::get_file_type($extension)
1289
                        ),
1290
                        new ReadonlyField(
1291
                            "Size",
1292
                            _t('AssetTableField.SIZE', 'File size') . ':',
1293
                            $this->getFileSizeFormatted()
1294
                        ),
1295
                        $urlField = new ReadonlyField(
1296
                            'ClickableURL',
1297
                            _t('AssetTableField.URL', 'URL'),
1298
                            sprintf(
1299
                                '<a href="%s" target="_blank" class="file-url">%s</a>',
1300
                                $this->getLink(),
1301
                                $this->getLink()
1302
                            )
1303
                        ),
1304
                        new ReadonlyField("FilenameWithoutIDField", "Filename". ':', $this->getFilenameWithoutID()),
1305
                        new DateField_Disabled(
1306
                            "Created",
1307
                            _t('AssetTableField.CREATED', 'First uploaded') . ':',
1308
                            $this->Created
1309
                        ),
1310
                        new DateField_Disabled(
1311
                            "LastEdited",
1312
                            _t('AssetTableField.LASTEDIT', 'Last changed') . ':',
1313
                            $this->LastEdited
1314
                        ),
1315
                        new DateField_Disabled(
1316
                            "LastChanged",
1317
                            _t('AssetTableField.LASTCHANGED', 'Last replaced') . ':',
1318
                            $this->LastChanged
1319
                        ),
1320
                        new ReadonlyField("PublishedOn", "Published on". ':', $publishedOnValue),
1321
                        new ReadonlyField("ReferencedOn", "Referenced on". ':', $relationListCountValue),
1322
                        new ReadonlyField("ViewCount", "View count". ':', $this->ViewCount)
1323
                    )
1324
                )->setName("FilePreviewData")->addExtraClass('cms-file-info-data')
1325
            )->setName("FilePreview")->addExtraClass('cms-file-info')
1326
        );
1327
1328
        $fields->setName('FileP');
1329
        $urlField->dontEscape = true;
1330
1331
        return $fields;
1332
    }
1333
1334
    /**
1335
     * Takes a file and adds it to the DMSDocument storage, replacing the
1336
     * current file.
1337
     *
1338
     * @param File $file
1339
     *
1340
     * @return $this
1341
     */
1342
    public function ingestFile($file)
1343
    {
1344
        $this->replaceDocument($file);
1345
        $file->delete();
1346
1347
        return $this;
1348
    }
1349
1350
    /**
1351
     * Get a data list of documents related to this document
1352
     *
1353
     * @return DataList
1354
     */
1355
    public function getRelatedDocuments()
1356
    {
1357
        $documents = $this->RelatedDocuments();
0 ignored issues
show
Bug introduced by
The method RelatedDocuments() does not exist on DMSDocument. Did you maybe mean getRelatedDocuments()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
1358
1359
        $this->extend('updateRelatedDocuments', $documents);
1360
1361
        return $documents;
1362
    }
1363
1364
    /**
1365
     * Get a GridField for managing related documents
1366
     *
1367
     * @return GridField
1368
     */
1369
    protected function getRelatedDocumentsGridField()
1370
    {
1371
        $gridField = GridField::create(
1372
            'RelatedDocuments',
1373
            _t('DMSDocument.RELATEDDOCUMENTS', 'Related Documents'),
1374
            $this->RelatedDocuments(),
0 ignored issues
show
Bug introduced by
The method RelatedDocuments() does not exist on DMSDocument. Did you maybe mean getRelatedDocuments()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
1375
            new GridFieldConfig_RelationEditor
1376
        );
1377
1378
        $gridField->getConfig()->removeComponentsByType('GridFieldAddNewButton');
1379
        // Move the autocompleter to the left
1380
        $gridField->getConfig()->removeComponentsByType('GridFieldAddExistingAutocompleter');
1381
        $gridField->getConfig()->addComponent(new GridFieldAddExistingAutocompleter('buttons-before-left'));
1382
1383
        $this->extend('updateRelatedDocumentsGridField', $gridField);
1384
1385
        return $gridField;
1386
    }
1387
1388
    /**
1389
     * Checks at least one group is selected if CanViewType || CanEditType == 'OnlyTheseUsers'
1390
     *
1391
     * @return ValidationResult
1392
     */
1393
    protected function validate()
1394
    {
1395
        $valid = parent::validate();
1396
1397
        if ($this->CanViewType == 'OnlyTheseUsers' && !$this->ViewerGroups()->count()) {
0 ignored issues
show
Documentation Bug introduced by
The method ViewerGroups does not exist on object<DMSDocument>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
1398
            $valid->error("Selecting 'Only these people' from a viewers list needs at least one group selected.");
1399
        }
1400
1401
        if ($this->CanEditType == 'OnlyTheseUsers' && !$this->EditorGroups()->count()) {
0 ignored issues
show
Documentation Bug introduced by
The method EditorGroups does not exist on object<DMSDocument>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
1402
            $valid->error("Selecting 'Only these people' from a editors list needs at least one group selected.");
1403
        }
1404
1405
        return $valid;
1406
    }
1407
1408
1409
}
1410