Completed
Pull Request — master (#159)
by Robbie
02:23
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
            'DocumentSort' => 'Int'
33
        ),
34
    );
35
36
    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...
37
        'Title' => 'Title',
38
        'Documents.Count' => 'No. Documents'
39
    );
40
41
    /**
42
     * Retrieve a list of the documents in this set. An extension hook is provided before the result is returned.
43
     *
44
     * You can attach an extension to this event:
45
     *
46
     * <code>
47
     * public function updateDocuments($document)
48
     * {
49
     *     // do something
50
     * }
51
     * </code>
52
     *
53
     * @return DataList|null
54
     */
55
    public function getDocuments()
56
    {
57
        $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...
58
        $this->extend('updateDocuments', $documents);
59
        return $documents;
60
    }
61
62
    /**
63
     * Put the "documents" list into the main tab instead of its own tab, and replace the default "Add Document" button
64
     * with a customised button for DMS documents
65
     *
66
     * @return FieldList
67
     */
68
    public function getCMSFields()
69
    {
70
        // PHP 5.3 only
71
        $self = $this;
72
        $this->beforeUpdateCMSFields(function (FieldList $fields) use ($self) {
73
            $fields->removeFieldsFromTab(
74
                'Root.Main',
75
                array('KeyValuePairs', 'SortBy', 'SortByDirection')
76
            );
77
            // Don't put the GridField for documents in until the set has been created
78
            if (!$self->isInDB()) {
79
                $fields->addFieldToTab(
80
                    'Root.Main',
81
                    LiteralField::create(
82
                        'GridFieldNotice',
83
                        '<p class="message warning">' . _t(
84
                            'DMSDocumentSet.GRIDFIELD_NOTICE',
85
                            'Managing documents will be available once you have created this document set.'
86
                        ) . '</p>'
87
                    ),
88
                    'Title'
89
                );
90
            } else {
91
                $fields->removeByName('DocumentSetSort');
92
93
                // Document listing
94
                $gridFieldConfig = GridFieldConfig::create()
95
                    ->addComponents(
96
                        new GridFieldButtonRow('before'),
97
                        new GridFieldToolbarHeader(),
98
                        new GridFieldFilterHeader(),
99
                        new GridFieldSortableHeader(),
100
                        new GridFieldDataColumns(),
101
                        new GridFieldEditButton(),
102
                        // Special delete dialog to handle custom behaviour of unlinking and deleting
103
                        new GridFieldDeleteAction(true),
104
                        new GridFieldDetailForm()
105
                    );
106
107
                if (class_exists('GridFieldPaginatorWithShowAll')) {
108
                    $paginatorComponent = new GridFieldPaginatorWithShowAll(15);
109
                } else {
110
                    $paginatorComponent = new GridFieldPaginator(15);
111
                }
112
                $gridFieldConfig->addComponent($paginatorComponent);
113
114
                if (class_exists('GridFieldSortableRows')) {
115
                    $gridFieldConfig->addComponent(new GridFieldSortableRows('DocumentSort'));
116
                }
117
118
                // Don't show which page this is if we're already editing within a page context
119
                if (Controller::curr() instanceof CMSPageEditController) {
120
                    $fields->removeByName('PageID');
121
                } else {
122
                    $fields->fieldByName('Root.Main.PageID')->setTitle(_t('DMSDocumentSet.SHOWONPAGE', 'Show on page'));
123
                }
124
125
                $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...
126
                    ->setDisplayFields($self->getDocumentDisplayFields())
127
                    ->setFieldCasting(array('LastEdited' => 'Datetime->Ago'))
128
                    ->setFieldFormatting(
129
                        array(
130
                            'FilenameWithoutID' => '<a target=\'_blank\' class=\'file-url\''
131
                                . ' href=\'$Link\'>$FilenameWithoutID</a>',
132
                            'ManuallyAdded' => function ($value) {
133
                                if ($value) {
134
                                    return _t('DMSDocumentSet.MANUAL', 'Manually');
135
                                }
136
                                return _t('DMSDocumentSet.QUERYBUILDER', 'Query Builder');
137
                            }
138
                        )
139
                    );
140
141
                // Override delete functionality with this class
142
                $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...
143
                    ->setItemRequestClass('DMSGridFieldDetailForm_ItemRequest');
144
                $gridField = GridField::create(
145
                    'Documents',
146
                    false,
147
                    $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...
148
                    $gridFieldConfig
149
                );
150
                $gridField->setModelClass('DMSDocument');
151
                $gridField->addExtraClass('documents');
152
153
                $gridFieldConfig->addComponent(
154
                    $addNewButton = new DMSGridFieldAddNewButton('buttons-before-left'),
155
                    'GridFieldExportButton'
156
                );
157
                $addNewButton->setDocumentSetId($self->ID);
158
159
                $fields->removeByName('Documents');
160
                $fields->addFieldsToTab(
161
                    'Root.Main',
162
                    array(
163
                        $gridField,
164
                        HiddenField::create('DMSShortcodeHandlerKey', false, DMS::inst()->getShortcodeHandlerKey())
165
                    )
166
                );
167
                $self->addQueryFields($fields);
168
            }
169
        });
170
        $this->addRequirements();
171
        return parent::getCMSFields();
172
    }
173
174
    /**
175
     * Add required CSS and Javascript requirements for managing documents
176
     *
177
     * @return $this
178
     */
179
    protected function addRequirements()
180
    {
181
        // Javascript to customize the grid field for the DMS document (overriding entwine
182
        // in FRAMEWORK_DIR.'/javascript/GridField.js'
183
        Requirements::javascript(DMS_DIR . '/javascript/DMSGridField.js');
184
        Requirements::css(DMS_DIR . '/dist/css/dmsbundle.css');
185
186
        // Javascript for the link editor pop-up in TinyMCE
187
        Requirements::javascript(DMS_DIR . '/javascript/DocumentHtmlEditorFieldToolbar.js');
188
189
        return $this;
190
    }
191
192
    /**
193
     * Adds the query fields to build the document logic to the DMSDocumentSet.
194
     *
195
     * To extend use the following from within an Extension subclass:
196
     *
197
     * <code>
198
     * public function updateQueryFields($result)
199
     * {
200
     *     // Do something here
201
     * }
202
     * </code>
203
     *
204
     * @param FieldList $fields
205
     */
206
    public function addQueryFields($fields)
207
    {
208
        /** @var DMSDocument $doc */
209
        $doc = singleton('DMSDocument');
210
        /** @var FormField $field */
211
        $dmsDocFields = $doc->scaffoldSearchFields(array('fieldClasses' => true));
212
        $membersMap = Member::get()->map('ID', 'Name')->toArray();
213
        asort($membersMap);
214
215
        foreach ($dmsDocFields as $field) {
216
            if ($field instanceof ListboxField) {
217
                $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...
218
                $field->setMultiple(true)->setSource($map);
219
            }
220
        }
221
        $keyValPairs = DMSJsonField::create('KeyValuePairs', $dmsDocFields->toArray());
222
223
        // Now lastly add the sort fields
224
        $sortedBy = FieldGroup::create('SortedBy', array(
225
            DropdownField::create('SortBy', '', array(
226
                'LastEdited'  => 'Last changed',
227
                'Created'     => 'Created',
228
                'Title'       => 'Document title',
229
            ), 'LastEdited'),
230
            DropdownField::create('SortByDirection', '', $this->dbObject('SortByDirection')->enumValues(), 'DESC'),
231
        ));
232
233
        $sortedBy->setTitle(_t('DMSDocumentSet.SORTED_BY', 'Sort the document set by:'));
234
        $fields->addFieldsToTab('Root.QueryBuilder', array($keyValPairs, $sortedBy));
235
        $this->extend('updateQueryFields', $fields);
236
    }
237
238
    public function onBeforeWrite()
239
    {
240
        parent::onBeforeWrite();
241
242
        $this->saveLinkedDocuments();
243
    }
244
245
    /**
246
     * Retrieve a list of the documents in this set. An extension hook is provided before the result is returned.
247
     */
248
    public function saveLinkedDocuments()
249
    {
250
        if (empty($this->KeyValuePairs) || !$this->isChanged('KeyValuePairs')) {
251
            return;
252
        }
253
254
        $keyValuesPair = Convert::json2array($this->KeyValuePairs);
255
256
        /** @var DMSDocument $dmsDoc */
257
        $dmsDoc = singleton('DMSDocument');
258
        $context = $dmsDoc->getDefaultSearchContext();
259
260
        $sortBy = $this->SortBy ? $this->SortBy : 'LastEdited';
261
        $sortByDirection = $this->SortByDirection ? $this->SortByDirection : 'DESC';
262
        $sortedBy = sprintf('%s %s', $sortBy, $sortByDirection);
263
264
        /** @var DataList $documents */
265
        $documents = $context->getResults($keyValuesPair, $sortedBy);
0 ignored issues
show
Bug introduced by
It seems like $keyValuesPair defined by \Convert::json2array($this->KeyValuePairs) on line 254 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...
266
        $documents = $this->addEmbargoConditions($documents);
267
        $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...
268
    }
269
270
    /**
271
     * Add embargo date conditions to a search query
272
     *
273
     * @param  DataList $documents
274
     * @return DataList
275
     */
276
    protected function addEmbargoConditions(DataList $documents)
277
    {
278
        $now = SS_Datetime::now()->Rfc2822();
279
280
        return $documents->where(
281
            "\"EmbargoedIndefinitely\" = 0 AND "
282
            . " \"EmbargoedUntilPublished\" = 0 AND "
283
            . "(\"EmbargoedUntilDate\" IS NULL OR "
284
            . "(\"EmbargoedUntilDate\" IS NOT NULL AND '{$now}' >= \"EmbargoedUntilDate\")) AND "
285
            . "\"ExpireAtDate\" IS NULL OR (\"ExpireAtDate\" IS NOT NULL AND '{$now}' < \"ExpireAtDate\")"
286
        );
287
    }
288
289
    /**
290
     * Remove all ManuallyAdded = 0 original results and add in the new documents returned by the search context
291
     *
292
     * @param  DataList $documents
293
     * @return DataList
294
     */
295
    protected function addQueryBuilderSearchResults(DataList $documents)
296
    {
297
        /** @var ManyManyList $originals Documents that belong to just this set. */
298
        $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...
299
        $originals->removeByFilter('"ManuallyAdded" = 0');
300
301
        foreach ($documents as $document) {
302
            $originals->add($document, array('ManuallyAdded' => 0));
303
        }
304
305
        return $originals;
306
    }
307
308
    /**
309
     * Customise the display fields for the documents GridField
310
     *
311
     * @return array
312
     */
313
    public function getDocumentDisplayFields()
314
    {
315
        return array_merge(
316
            (array) DMSDocument::create()->config()->get('display_fields'),
317
            array('ManuallyAdded' => _t('DMSDocumentSet.ADDEDMETHOD', 'Added'))
318
        );
319
    }
320
321
    protected function validate()
322
    {
323
        $result = parent::validate();
324
325
        if (!$this->getTitle()) {
326
            $result->error(_t('DMSDocumentSet.VALIDATION_NO_TITLE', '\'Title\' is required.'));
327
        }
328
        return $result;
329
    }
330
}
331