Completed
Pull Request — master (#153)
by Robbie
02:24
created

DMSDocumentSet::validate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 0
1
<?php
2
/**
3
 * A document set is attached to Pages, and contains many DMSDocuments
4
 *
5
 * @property Varchar Title
6
 * @property  Text KeyValuePairs
7
 * @property  Enum SortBy
8
 * @property Enum SortByDirection
9
 */
10
class DMSDocumentSet extends DataObject
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...
11
{
12
    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...
13
        'Title' => 'Varchar(255)',
14
        'KeyValuePairs' => 'Text',
15
        'SortBy' => "Enum('LastEdited,Created,Title')')",
16
        'SortByDirection' => "Enum('DESC,ASC')')",
17
    );
18
19
    private static $has_one = 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 $has_one 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...
20
        'Page' => 'SiteTree',
21
    );
22
23
    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...
24
        'Documents' => 'DMSDocument',
25
    );
26
27
    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...
28
        'Documents' => array(
29
            // Flag indicating if a document was added directly to a set - in which case it is set - or added
30
            // via the query-builder.
31
            'ManuallyAdded' => 'Boolean(1)',
32
        ),
33
    );
34
35
    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...
36
        'Title' => 'Title',
37
        'Documents.Count' => 'No. Documents'
38
    );
39
40
    /**
41
     * Retrieve a list of the documents in this set. An extension hook is provided before the result is returned.
42
     *
43
     * You can attach an extension to this event:
44
     *
45
     * <code>
46
     * public function updateDocuments($document)
47
     * {
48
     *     // do something
49
     * }
50
     * </code>
51
     *
52
     * @return DataList|null
53
     */
54
    public function getDocuments()
55
    {
56
        $documents = $this->Documents();
0 ignored issues
show
Bug introduced by
The method Documents() does not exist on DMSDocumentSet. Did you maybe mean getDocuments()?

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...
57
        $this->extend('updateDocuments', $documents);
58
        return $documents;
59
    }
60
61
    /**
62
     * Put the "documents" list into the main tab instead of its own tab, and replace the default "Add Document" button
63
     * with a customised button for DMS documents
64
     *
65
     * @return FieldList
66
     */
67
    public function getCMSFields()
68
    {
69
        // PHP 5.3 only
70
        $self = $this;
71
        $this->beforeUpdateCMSFields(function (FieldList $fields) use ($self) {
72
            $fields->removeFieldsFromTab(
73
                'Root.Main',
74
                array('KeyValuePairs', 'SortBy', 'SortByDirection')
75
            );
76
            // Don't put the GridField for documents in until the set has been created
77
            if (!$self->isInDB()) {
78
                $fields->addFieldToTab(
79
                    'Root.Main',
80
                    LiteralField::create(
81
                        'GridFieldNotice',
82
                        '<p class="message warning">' . _t(
83
                            'DMSDocumentSet.GRIDFIELD_NOTICE',
84
                            'Managing documents will be available once you have created this document set.'
85
                        ) . '</p>'
86
                    ),
87
                    'Title'
88
                );
89
            } else {
90
                // Document listing
91
                $gridFieldConfig = GridFieldConfig::create()
92
                    ->addComponents(
93
                        new GridFieldButtonRow('before'),
94
                        new GridFieldToolbarHeader(),
95
                        new GridFieldFilterHeader(),
96
                        new GridFieldSortableHeader(),
97
                        new GridFieldDataColumns(),
98
                        new GridFieldEditButton(),
99
                        // Special delete dialog to handle custom behaviour of unlinking and deleting
100
                        new GridFieldDeleteAction(true),
101
                        new GridFieldDetailForm()
102
                    );
103
104
                if (class_exists('GridFieldPaginatorWithShowAll')) {
105
                    $paginatorComponent = new GridFieldPaginatorWithShowAll(15);
106
                } else {
107
                    $paginatorComponent = new GridFieldPaginator(15);
108
                }
109
                $gridFieldConfig->addComponent($paginatorComponent);
110
111
                if (class_exists('GridFieldSortableRows')) {
112
                    $sortableComponent = new GridFieldSortableRows('DocumentSort');
113
                    // setUsePagination method removed from newer version of SortableGridField.
114
                    if (method_exists($sortableComponent, 'setUsePagination')) {
115
                        $sortableComponent->setUsePagination(false)->setForceRedraw(true);
116
                    }
117
                    $gridFieldConfig->addComponent($sortableComponent);
118
                }
119
120
                // Don't show which page this is if we're already editing within a page context
121
                if (Controller::curr() instanceof CMSPageEditController) {
122
                    $fields->removeByName('PageID');
123
                } else {
124
                    $fields->fieldByName('Root.Main.PageID')->setTitle(_t('DMSDocumentSet.SHOWONPAGE', 'Show on page'));
125
                }
126
127
                $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...
128
                    ->setDisplayFields($self->getDocumentDisplayFields())
129
                    ->setFieldCasting(array('LastEdited' => 'Datetime->Ago'))
130
                    ->setFieldFormatting(
131
                        array(
132
                            'FilenameWithoutID' => '<a target=\'_blank\' class=\'file-url\''
133
                                . ' href=\'$Link\'>$FilenameWithoutID</a>',
134
                            'ManuallyAdded' => function ($value) {
135
                                if ($value) {
136
                                    return _t('DMSDocumentSet.MANUAL', 'Manually');
137
                                }
138
                                return _t('DMSDocumentSet.QUERYBUILDER', 'Query Builder');
139
                            }
140
                        )
141
                    );
142
143
                // Override delete functionality with this class
144
                $gridFieldConfig->getComponentByType('GridFieldDetailForm')
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface GridFieldComponent as the method setItemRequestClass() does only exist in the following implementations of said interface: GridFieldAddNewMultiClass, GridFieldDetailForm.

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...
145
                    ->setItemRequestClass('DMSGridFieldDetailForm_ItemRequest');
146
                $gridField = GridField::create(
147
                    'Documents',
148
                    false,
149
                    $self->Documents(),
0 ignored issues
show
Bug introduced by
The method Documents() does not exist on DMSDocumentSet. Did you maybe mean getDocuments()?

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...
150
                    $gridFieldConfig
151
                );
152
                $gridField->setModelClass('DMSDocument');
153
                $gridField->addExtraClass('documents');
154
155
                $gridFieldConfig->addComponent(
156
                    $addNewButton = new DMSGridFieldAddNewButton('buttons-before-left'),
157
                    'GridFieldExportButton'
158
                );
159
                $addNewButton->setDocumentSetId($self->ID);
160
161
                $fields->removeByName('Documents');
162
                $fields->addFieldsToTab(
163
                    'Root.Main',
164
                    array(
165
                        $gridField,
166
                        HiddenField::create('DMSShortcodeHandlerKey', false, DMS::inst()->getShortcodeHandlerKey())
167
                    )
168
                );
169
                $self->addQueryFields($fields);
170
            }
171
        });
172
        $this->addRequirements();
173
        return parent::getCMSFields();
174
    }
175
176
    /**
177
     * Add required CSS and Javascript requirements for managing documents
178
     *
179
     * @return $this
180
     */
181
    protected function addRequirements()
182
    {
183
        // Javascript to customize the grid field for the DMS document (overriding entwine
184
        // in FRAMEWORK_DIR.'/javascript/GridField.js'
185
        Requirements::javascript(DMS_DIR . '/javascript/DMSGridField.js');
186
        Requirements::css(DMS_DIR . '/dist/css/dmsbundle.css');
187
188
        // Javascript for the link editor pop-up in TinyMCE
189
        Requirements::javascript(DMS_DIR . '/javascript/DocumentHtmlEditorFieldToolbar.js');
190
191
        return $this;
192
    }
193
194
    /**
195
     * Adds the query fields to build the document logic to the DMSDocumentSet.
196
     *
197
     * To extend use the following from within an Extension subclass:
198
     *
199
     * <code>
200
     * public function updateQueryFields($result)
201
     * {
202
     *     // Do something here
203
     * }
204
     * </code>
205
     *
206
     * @param FieldList $fields
207
     */
208
    public function addQueryFields($fields)
209
    {
210
        /** @var DMSDocument $doc */
211
        $doc = singleton('DMSDocument');
212
        /** @var FormField $field */
213
        $dmsDocFields = $doc->scaffoldSearchFields(array('fieldClasses' => true));
214
        $membersMap = Member::get()->map('ID', 'Name')->toArray();
215
        asort($membersMap);
216
217
        foreach ($dmsDocFields as $field) {
218
            if ($field instanceof ListboxField) {
219
                $map = ($field->getName() === 'Tags__ID') ? $doc->getAllTagsMap() : $membersMap;
0 ignored issues
show
Documentation Bug introduced by
The method getAllTagsMap 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...
220
                $field->setMultiple(true)->setSource($map);
221
            }
222
        }
223
        $keyValPairs = DMSJsonField::create('KeyValuePairs', $dmsDocFields->toArray());
224
225
        // Now lastly add the sort fields
226
        $sortedBy = FieldGroup::create('SortedBy', array(
227
            DropdownField::create('SortBy', '', array(
228
                'LastEdited'  => 'Last changed',
229
                'Created'     => 'Created',
230
                'Title'       => 'Document title',
231
            ), 'LastEdited'),
232
            DropdownField::create('SortByDirection', '', $this->dbObject('SortByDirection')->enumValues(), 'DESC'),
233
        ));
234
235
        $sortedBy->setTitle(_t('DMSDocumentSet.SORTED_BY', 'Sort the document set by:'));
236
        $fields->addFieldsToTab('Root.QueryBuilder', array($keyValPairs, $sortedBy));
237
        $this->extend('updateQueryFields', $fields);
238
    }
239
240
    public function onBeforeWrite()
241
    {
242
        parent::onBeforeWrite();
243
244
        $this->saveLinkedDocuments();
245
    }
246
247
    /**
248
     * Retrieve a list of the documents in this set. An extension hook is provided before the result is returned.
249
     */
250
    public function saveLinkedDocuments()
251
    {
252
        if (empty($this->KeyValuePairs) || !$this->isChanged('KeyValuePairs')) {
253
            return;
254
        }
255
256
        $keyValuesPair = Convert::json2array($this->KeyValuePairs);
257
258
        /** @var DMSDocument $dmsDoc */
259
        $dmsDoc = singleton('DMSDocument');
260
        $context = $dmsDoc->getDefaultSearchContext();
261
262
        $sortBy = $this->SortBy ? $this->SortBy : 'LastEdited';
263
        $sortByDirection = $this->SortByDirection ? $this->SortByDirection : 'DESC';
264
        $sortedBy = sprintf('%s %s', $sortBy, $sortByDirection);
265
266
        /** @var DataList $documents */
267
        $documents = $context->getResults($keyValuesPair, $sortedBy);
0 ignored issues
show
Bug introduced by
It seems like $keyValuesPair defined by \Convert::json2array($this->KeyValuePairs) on line 256 can also be of type boolean; however, SearchContext::getResults() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
268
        $documents = $this->addEmbargoConditions($documents);
269
        $documents = $this->addQueryBuilderSearchResults($documents);
0 ignored issues
show
Unused Code introduced by
$documents 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...
270
    }
271
272
    /**
273
     * Add embargo date conditions to a search query
274
     *
275
     * @param  DataList $documents
276
     * @return DataList
277
     */
278
    protected function addEmbargoConditions(DataList $documents)
279
    {
280
        $now = SS_Datetime::now()->Rfc2822();
281
282
        return $documents->where(
283
            "\"EmbargoedIndefinitely\" = 0 AND "
284
            . " \"EmbargoedUntilPublished\" = 0 AND "
285
            . "(\"EmbargoedUntilDate\" IS NULL OR "
286
            . "(\"EmbargoedUntilDate\" IS NOT NULL AND '{$now}' >= \"EmbargoedUntilDate\")) AND "
287
            . "\"ExpireAtDate\" IS NULL OR (\"ExpireAtDate\" IS NOT NULL AND '{$now}' < \"ExpireAtDate\")"
288
        );
289
    }
290
291
    /**
292
     * Remove all ManuallyAdded = 0 original results and add in the new documents returned by the search context
293
     *
294
     * @param  DataList $documents
295
     * @return DataList
296
     */
297
    protected function addQueryBuilderSearchResults(DataList $documents)
298
    {
299
        /** @var ManyManyList $originals Documents that belong to just this set. */
300
        $originals = $this->Documents();
0 ignored issues
show
Bug introduced by
The method Documents() does not exist on DMSDocumentSet. Did you maybe mean getDocuments()?

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...
301
        $originals->removeByFilter('"ManuallyAdded" = 0');
302
303
        foreach ($documents as $document) {
304
            $originals->add($document, array('ManuallyAdded' => 0));
305
        }
306
307
        return $originals;
308
    }
309
310
    /**
311
     * Customise the display fields for the documents GridField
312
     *
313
     * @return array
314
     */
315
    public function getDocumentDisplayFields()
316
    {
317
        return array_merge(
318
            (array) DMSDocument::create()->config()->get('display_fields'),
319
            array('ManuallyAdded' => _t('DMSDocumentSet.ADDEDMETHOD', 'Added'))
320
        );
321
    }
322
323
    protected function validate()
324
    {
325
        $result = parent::validate();
326
327
        if (!$this->getTitle()) {
328
            $result->error(_t('DMSDocumentSet.VALIDATION_NO_TITLE', '\'Title\' is required.'));
329
        }
330
        return $result;
331
    }
332
}
333