Completed
Pull Request — master (#119)
by Franco
17:38 queued 01:48
created

DMSDocumentSet   C

Complexity

Total Complexity 17

Size/Duplication

Total Lines 258
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 28

Importance

Changes 0
Metric Value
wmc 17
lcom 1
cbo 28
dl 0
loc 258
rs 5
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getDocuments() 0 6 1
B getCMSFields() 0 87 5
A addRequirements() 0 12 1
B addQueryFields() 0 35 3
A onBeforeWrite() 0 5 1
B saveLinkedDocuments() 0 32 6
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
    /**
14
     * This gets switched up during testing to mock the DMSDocument
15
     *
16
     * @var varchar
17
     */
18
    public static $linked_document_type = 'DMSDocument';
19
20
    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...
21
        'Title' => 'Varchar(255)',
22
        'KeyValuePairs' => 'Text',
23
        "SortBy" => "Enum('LastEdited,LastChanged,Created,Title')')",
24
        "SortByDirection" => "Enum('DESC,ASC')')",
25
    );
26
27
    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...
28
        'Page' => 'SiteTree',
29
    );
30
31
    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...
32
        'Documents' => 'DMSDocument',
33
    );
34
35
    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...
36
        'Documents' => array(
37
            'BelongsToSet' => 'Boolean(1)',// Whether or not this is a set or a Query Builder document
38
        ),
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
            // Don't put the GridField for documents in until the set has been created
74
            if (!$self->isInDB()) {
75
                $fields->addFieldToTab(
76
                    'Root.Main',
77
                    LiteralField::create(
78
                        'GridFieldNotice',
79
                        '<p class="message warning">' . _t(
80
                            'DMSDocumentSet.GRIDFIELD_NOTICE',
81
                            'Managing documents will be available once you have created this document set.'
82
                        ) . '</p>'
83
                    ),
84
                    'Title'
85
                );
86
                return;
87
            }
88
89
            // Document listing
90
            $gridFieldConfig = GridFieldConfig::create()
91
                ->addComponents(
92
                    new GridFieldToolbarHeader(),
93
                    new GridFieldFilterHeader(),
94
                    new GridFieldSortableHeader(),
95
                    // new GridFieldOrderableRows('DocumentSort'),
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% 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...
96
                    new GridFieldDataColumns(),
97
                    new GridFieldEditButton(),
98
                    // Special delete dialog to handle custom behaviour of unlinking and deleting
99
                    new DMSGridFieldDeleteAction(),
100
                    new GridFieldDetailForm()
101
                );
102
103
            if (class_exists('GridFieldPaginatorWithShowAll')) {
104
                $paginatorComponent = new GridFieldPaginatorWithShowAll(15);
105
            } else {
106
                $paginatorComponent = new GridFieldPaginator(15);
107
            }
108
            $gridFieldConfig->addComponent($paginatorComponent);
109
110
            if (class_exists('GridFieldSortableRows')) {
111
                $sortableComponent = new GridFieldSortableRows('DocumentSort');
112
                // setUsePagenation method removed from newer version of SortableGridField.
113
                if (method_exists($sortableComponent, 'setUsePagination')) {
114
                    $sortableComponent->setUsePagination(false)->setForceRedraw(true);
115
                }
116
                $gridFieldConfig->addComponent($sortableComponent);
117
            }
118
119
            // HACK: Create a singleton of DMSDocument to ensure extensions are applied before we try to get display fields.
120
            singleton(DMSDocumentSet::$linked_document_type);
121
            $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...
122
                ->setDisplayFields(Config::inst()->get('DMSDocument', 'display_fields'))
123
                ->setFieldCasting(array('LastChanged' => 'Datetime->Ago'))
124
                ->setFieldFormatting(
125
                    array(
126
                        'FilenameWithoutID' => '<a target=\'_blank\' class=\'file-url\' href=\'$Link\'>$FilenameWithoutID</a>',
127
                    )
128
                );
129
130
            // Override delete functionality with this class
131
            $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...
132
                ->setItemRequestClass('DMSGridFieldDetailForm_ItemRequest');
133
            $gridField = GridField::create(
134
                'Documents',
135
                false,
136
                $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...
137
                $gridFieldConfig
138
            );
139
            $gridField->setModelClass('DMSDocument');
140
            $gridField->addExtraClass('documents');
141
142
            $gridFieldConfig->addComponent(
143
                $addNewButton = new DMSGridFieldAddNewButton,
144
                'GridFieldExportButton'
145
            );
146
            $addNewButton->setDocumentSetId($self->ID);
147
148
            $fields->removeByName('Documents');
149
            $fields->addFieldToTab('Root.Main', $gridField);
150
            $self->addQueryFields($fields);
151
        });
152
        $this->addRequirements();
153
        return parent::getCMSFields();
154
    }
155
156
    /**
157
     * Add required CSS and Javascript requirements for managing documents
158
     *
159
     * @return $this
160
     */
161
    protected function addRequirements()
162
    {
163
        // Javascript to customize the grid field for the DMS document (overriding entwine
164
        // in FRAMEWORK_DIR.'/javascript/GridField.js'
165
        Requirements::javascript(DMS_DIR . '/javascript/DMSGridField.js');
166
        Requirements::css(DMS_DIR . '/css/DMSMainCMS.css');
167
168
        // Javascript for the link editor pop-up in TinyMCE
169
        Requirements::javascript(DMS_DIR . '/javascript/DocumentHtmlEditorFieldToolbar.js');
170
171
        return $this;
172
    }
173
174
    /**
175
     * Adds the query fields to build the document logic to the DMSDocumentSet.
176
     *
177
     * To extend use the following from within an Extension subclass:
178
     *
179
     * <code>
180
     * public function updateQueryFields($result)
181
     * {
182
     *     // Do something here
183
     * }
184
     * </code>
185
     *
186
     * @param FieldList $fields
187
     */
188
    public function addQueryFields($fields)
189
    {
190
        /** @var DMSDocument $doc */
191
        $doc = singleton(DMSDocumentSet::$linked_document_type);
192
        $fields->removeByName(array('SortByDirection', 'SortBy'));
193
194
        /** @var FormField $field */
195
        $dmsDocFields = $doc->scaffoldSearchFields(array('fieldClasses' => true));
196
        $membersMap = Member::get()->map('ID', 'Name')->toArray();
197
        asort($membersMap);
198
        foreach ($dmsDocFields as $field) {
199
            // Apply field customisations where necessary
200
            if (in_array($field->getName(), array('CreatedByID', 'LastChangedByID', 'LastEditedByID'))) {
201
                /** @var ListboxField $field */
202
                $field->setMultiple(true)->setSource($membersMap);
203
            }
204
        }
205
        $keyValPairs = new JsonField('KeyValuePairs', $dmsDocFields->toArray());
206
207
        // Now lastly add the sort fields
208
        $sortedBy = new FieldGroup("SortedBy", array(
209
                new DropdownField("SortBy", '', array(
210
                    'LastEdited'  => "Last changed",
211
                    'LastChanged' => "Last replaced",
212
                    'Created'     => "Created",
213
                    'Title'       => "Document title",
214
                ), 'LastEdited'),
215
                new DropdownField("SortByDirection", '', $this->dbObject("SortByDirection")->enumValues(), "DESC"),
216
            ));
217
218
        $sortedBy->setTitle("Sort the document set by:");
219
        $fields->addFieldsToTab('Root.QueryBuilder', $keyValPairs);
0 ignored issues
show
Documentation introduced by
$keyValPairs is of type object<JsonField>, but the function expects a array.

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...
220
        $fields->addFieldToTab('Root.QueryBuilder', $sortedBy);
221
        $this->extend('updateQueryFields', $fields);
222
    }
223
224
    public function onBeforeWrite(){
225
        parent::onBeforeWrite();
226
227
        $this->saveLinkedDocuments();
228
    }
229
230
    /**
231
     * Retrieve a list of the documents in this set. An extension hook is provided before the result is returned.
232
     *
233
     * @return ArrayList|null
234
     */
235
    public function saveLinkedDocuments()
236
    {
237
        // Documents that belong to just this set.
238
        /** @var ManyManyList $originals */
239
        $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...
240
        if (!(empty($this->KeyValuePairs)) && $this->isChanged('KeyValuePairs')) {
241
242
            $keyValuesPair = Convert::json2array($this->KeyValuePairs);
243
            /** @var DMSDocument $dmsDoc */
244
            $dmsDoc = singleton(DMSDocumentSet::$linked_document_type);
245
            $context = $dmsDoc->getDefaultSearchContext();
246
247
            $sortBy = $this->SortBy ? $this->SortBy : 'LastEdited';
248
            $sortByDirection = $this->SortByDirection ? $this->SortByDirection : 'DESC';
249
            $sortedBy = sprintf('%s %s', $sortBy, $sortByDirection);
250
            /** @var DataList $documents */
251
            $documents = $context->getResults($keyValuesPair, $sortedBy);
0 ignored issues
show
Bug introduced by
It seems like $keyValuesPair defined by \Convert::json2array($this->KeyValuePairs) on line 242 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...
252
            $now = SS_Datetime::now()->Rfc2822();
253
            $documents = $documents->where(
254
                "\"EmbargoedIndefinitely\" = 0 AND ".
255
                " \"EmbargoedUntilPublished\" = 0 AND ".
256
                "(\"EmbargoedUntilDate\" IS NULL OR " .
257
                "(\"EmbargoedUntilDate\" IS NOT NULL AND '{$now}' >= \"EmbargoedUntilDate\")) AND " .
258
                "\"ExpireAtDate\" IS NULL OR (\"ExpireAtDate\" IS NOT NULL AND '{$now}' < \"ExpireAtDate\")");
259
260
            // Remove all BelongsToSet as the rules have changed
261
            $originals->removeByFilter('"BelongsToSet" = 0');
262
            foreach ($documents as $document) {
263
                $originals->add($document, array('BelongsToSet' => 0));
264
            }
265
        }
266
    }
267
}
268