Completed
Pull Request — master (#119)
by Franco
02:20
created

DMSDocumentSet::addQueryFields()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 31
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 31
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 19
nc 3
nop 1
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
13
    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...
14
        'Title' => 'Varchar(255)',
15
        'KeyValuePairs' => 'Text',
16
        'SortBy' => "Enum('LastEdited,Created,Title')')",
17
        'SortByDirection' => "Enum('DESC,ASC')')",
18
    );
19
20
    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...
21
        'Page' => 'SiteTree',
22
    );
23
24
    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...
25
        'Documents' => 'DMSDocument',
26
    );
27
28
    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...
29
        'Documents' => array(
30
            'BelongsToSet' => 'Boolean(1)',// Whether or not this is a set or a Query Builder document
31
        ),
32
    );
33
34
    /**
35
     * Retrieve a list of the documents in this set. An extension hook is provided before the result is returned.
36
     *
37
     * You can attach an extension to this event:
38
     *
39
     * <code>
40
     * public function updateDocuments($document)
41
     * {
42
     *     // do something
43
     * }
44
     * </code>
45
     *
46
     * @return DataList|null
47
     */
48
    public function getDocuments()
49
    {
50
        $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...
51
        $this->extend('updateDocuments', $documents);
52
        return $documents;
53
    }
54
55
    /**
56
     * Put the "documents" list into the main tab instead of its own tab, and replace the default "Add Document" button
57
     * with a customised button for DMS documents
58
     *
59
     * @return FieldList
60
     */
61
    public function getCMSFields()
62
    {
63
        // PHP 5.3 only
64
        $self = $this;
65
        $this->beforeUpdateCMSFields(function (FieldList $fields) use ($self) {
66
            $fields->removeFieldsFromTab(
67
                'Root.Main',
68
                array('KeyValuePairs', 'SortBy', 'SortByDirection')
69
            );
70
            // Don't put the GridField for documents in until the set has been created
71
            if (!$self->isInDB()) {
72
                $fields->addFieldToTab(
73
                    'Root.Main',
74
                    LiteralField::create(
75
                        'GridFieldNotice',
76
                        '<p class="message warning">' . _t(
77
                            'DMSDocumentSet.GRIDFIELD_NOTICE',
78
                            'Managing documents will be available once you have created this document set.'
79
                        ) . '</p>'
80
                    ),
81
                    'Title'
82
                );
83
            } else {
84
                // Document listing
85
                $gridFieldConfig = GridFieldConfig::create()
86
                    ->addComponents(
87
                        new GridFieldToolbarHeader(),
88
                        new GridFieldFilterHeader(),
89
                        new GridFieldSortableHeader(),
90
                        new GridFieldDataColumns(),
91
                        new GridFieldEditButton(),
92
                        // Special delete dialog to handle custom behaviour of unlinking and deleting
93
                        new DMSGridFieldDeleteAction(),
94
                        new GridFieldDetailForm()
95
                    );
96
97
                if (class_exists('GridFieldPaginatorWithShowAll')) {
98
                    $paginatorComponent = new GridFieldPaginatorWithShowAll(15);
99
                } else {
100
                    $paginatorComponent = new GridFieldPaginator(15);
101
                }
102
                $gridFieldConfig->addComponent($paginatorComponent);
103
104
                if (class_exists('GridFieldSortableRows')) {
105
                    $sortableComponent = new GridFieldSortableRows('DocumentSort');
106
                    // setUsePagination method removed from newer version of SortableGridField.
107
                    if (method_exists($sortableComponent, 'setUsePagination')) {
108
                        $sortableComponent->setUsePagination(false)->setForceRedraw(true);
109
                    }
110
                    $gridFieldConfig->addComponent($sortableComponent);
111
                }
112
113
                // HACK: Create a singleton of DMSDocument to ensure extensions are applied before we try to get display fields.
114
                singleton('DMSDocument');
115
                $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...
116
                    ->setDisplayFields(Config::inst()->get('DMSDocument', 'display_fields'))
117
                    ->setFieldCasting(array('LastEdited' => 'Datetime->Ago'))
118
                    ->setFieldFormatting(
119
                        array(
120
                            'FilenameWithoutID' => '<a target=\'_blank\' class=\'file-url\' href=\'$Link\'>$FilenameWithoutID</a>',
121
                        )
122
                    );
123
124
                // Override delete functionality with this class
125
                $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...
126
                    ->setItemRequestClass('DMSGridFieldDetailForm_ItemRequest');
127
                $gridField = GridField::create(
128
                    'Documents',
129
                    false,
130
                    $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...
131
                    $gridFieldConfig
132
                );
133
                $gridField->setModelClass('DMSDocument');
134
                $gridField->addExtraClass('documents');
135
136
                $gridFieldConfig->addComponent(
137
                    $addNewButton = new DMSGridFieldAddNewButton,
138
                    'GridFieldExportButton'
139
                );
140
                $addNewButton->setDocumentSetId($self->ID);
141
142
                $fields->removeByName('Documents');
143
                $fields->addFieldToTab('Root.Main', $gridField);
144
                $self->addQueryFields($fields);
145
            }
146
        });
147
        $this->addRequirements();
148
        return parent::getCMSFields();
149
    }
150
151
    /**
152
     * Add required CSS and Javascript requirements for managing documents
153
     *
154
     * @return $this
155
     */
156
    protected function addRequirements()
157
    {
158
        // Javascript to customize the grid field for the DMS document (overriding entwine
159
        // in FRAMEWORK_DIR.'/javascript/GridField.js'
160
        Requirements::javascript(DMS_DIR . '/javascript/DMSGridField.js');
161
        Requirements::css(DMS_DIR . '/dist/css/dmsbundle.css');
162
163
        // Javascript for the link editor pop-up in TinyMCE
164
        Requirements::javascript(DMS_DIR . '/javascript/DocumentHtmlEditorFieldToolbar.js');
165
166
        return $this;
167
    }
168
169
    /**
170
     * Adds the query fields to build the document logic to the DMSDocumentSet.
171
     *
172
     * To extend use the following from within an Extension subclass:
173
     *
174
     * <code>
175
     * public function updateQueryFields($result)
176
     * {
177
     *     // Do something here
178
     * }
179
     * </code>
180
     *
181
     * @param FieldList $fields
182
     */
183
    public function addQueryFields($fields)
184
    {
185
        /** @var DMSDocument $doc */
186
        $doc = singleton('DMSDocument');
187
        /** @var FormField $field */
188
        $dmsDocFields = $doc->scaffoldSearchFields(array('fieldClasses' => true));
189
        $membersMap = Member::get()->map('ID', 'Name')->toArray();
190
        asort($membersMap);
191
        foreach ($dmsDocFields as $field) {
192
            // Apply field customisations where necessary
193
            if (in_array($field->getName(), array('CreatedByID', 'LastEditedByID', 'LastEditedByID'))) {
194
                /** @var ListboxField $field */
195
                $field->setMultiple(true)->setSource($membersMap);
196
            }
197
        }
198
        $keyValPairs = new JsonField('KeyValuePairs', $dmsDocFields->toArray());
199
200
        // Now lastly add the sort fields
201
        $sortedBy = new FieldGroup('SortedBy', array(
202
                new DropdownField('SortBy', '', array(
203
                    'LastEdited'  => 'Last changed',
204
                    'Created'     => 'Created',
205
                    'Title'       => 'Document title',
206
                ), 'LastEdited'),
207
                new DropdownField('SortByDirection', '', $this->dbObject('SortByDirection')->enumValues(), 'DESC'),
208
            ));
209
210
        $sortedBy->setTitle("Sort the document set by:");
211
        $fields->addFieldsToTab('Root.QueryBuilder', array($keyValPairs, $sortedBy));
212
        $this->extend('updateQueryFields', $fields);
213
    }
214
215
    public function onBeforeWrite()
216
    {
217
        parent::onBeforeWrite();
218
219
        $this->saveLinkedDocuments();
220
    }
221
222
    /**
223
     * Retrieve a list of the documents in this set. An extension hook is provided before the result is returned.
224
     *
225
     * @return ArrayList|null
226
     */
227
    public function saveLinkedDocuments()
228
    {
229
        // Documents that belong to just this set.
230
        /** @var ManyManyList $originals */
231
        $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...
232
        if (!(empty($this->KeyValuePairs)) && $this->isChanged('KeyValuePairs')) {
233
            $keyValuesPair = Convert::json2array($this->KeyValuePairs);
234
            /** @var DMSDocument $dmsDoc */
235
            $dmsDoc = singleton('DMSDocument');
236
            $context = $dmsDoc->getDefaultSearchContext();
237
238
            $sortBy = $this->SortBy ? $this->SortBy : 'LastEdited';
239
            $sortByDirection = $this->SortByDirection ? $this->SortByDirection : 'DESC';
240
            $sortedBy = sprintf('%s %s', $sortBy, $sortByDirection);
241
            /** @var DataList $documents */
242
            $documents = $context->getResults($keyValuesPair, $sortedBy);
0 ignored issues
show
Bug introduced by
It seems like $keyValuesPair defined by \Convert::json2array($this->KeyValuePairs) on line 233 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...
243
            $now = SS_Datetime::now()->Rfc2822();
244
            $documents = $documents->where(
245
                "\"EmbargoedIndefinitely\" = 0 AND ".
246
                " \"EmbargoedUntilPublished\" = 0 AND ".
247
                "(\"EmbargoedUntilDate\" IS NULL OR " .
248
                "(\"EmbargoedUntilDate\" IS NOT NULL AND '{$now}' >= \"EmbargoedUntilDate\")) AND " .
249
                "\"ExpireAtDate\" IS NULL OR (\"ExpireAtDate\" IS NOT NULL AND '{$now}' < \"ExpireAtDate\")"
250
            );
251
252
            // Remove all BelongsToSet as the rules have changed
253
            $originals->removeByFilter('"BelongsToSet" = 0');
254
            foreach ($documents as $document) {
255
                $originals->add($document, array('BelongsToSet' => 0));
256
            }
257
        }
258
    }
259
}
260