GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — master (#344)
by
unknown
01:55
created

src/Admin/AdvancedWorkflowAdmin.php (1 issue)

strict.coding_against_concrete_implementation

Bug Minor

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace Symbiote\AdvancedWorkflow\Admin;
4
5
use SilverStripe\Admin\ModelAdmin;
6
use SilverStripe\CMS\Controllers\CMSPageEditController;
7
use SilverStripe\Control\HTTPRequest;
8
use SilverStripe\Core\Manifest\ModuleLoader;
9
use SilverStripe\Forms\GridField\GridField;
10
use SilverStripe\Forms\GridField\GridFieldConfig_Base;
11
use SilverStripe\Forms\GridField\GridFieldDataColumns;
12
use SilverStripe\Forms\GridField\GridFieldEditButton;
13
use SilverStripe\Forms\GridField\GridFieldDetailForm;
14
use SilverStripe\Forms\GridField\GridFieldPaginator;
15
use SilverStripe\Forms\FieldList;
16
use SilverStripe\Forms\FormAction;
17
use SilverStripe\Forms\GridField\GridFieldExportButton;
18
use SilverStripe\ORM\ArrayList;
19
use SilverStripe\ORM\DataObject;
20
use SilverStripe\Security\Member;
21
use SilverStripe\Security\Permission;
22
use SilverStripe\View\Requirements;
23
use Symbiote\AdvancedWorkflow\Admin\WorkflowDefinitionItemRequestClass;
24
use Symbiote\AdvancedWorkflow\DataObjects\WorkflowDefinition;
25
use Symbiote\AdvancedWorkflow\Dev\WorkflowBulkLoader;
26
use Symbiote\AdvancedWorkflow\Forms\GridField\GridFieldExportAction;
27
use Symbiote\AdvancedWorkflow\Forms\GridField\GridFieldWorkflowRestrictedEditButton;
28
use Symbiote\AdvancedWorkflow\Services\WorkflowService;
29
30
/**
31
 * @package advancedworkflow
32
 * @todo UI/UX needs looking at for when current user has no pending and/or submitted items, (Current
33
 * implementation is bog-standard <p> text)
34
 */
35
class AdvancedWorkflowAdmin extends ModelAdmin
36
{
37
    private static $menu_title    = 'Workflows';
38
    private static $menu_priority = -1;
39
    private static $url_segment   = 'workflows';
40
    private static $menu_icon_class = 'font-icon-flow-tree';
41
42
    /**
43
     *
44
     * @var array Allowable actions on this controller.
45
     */
46
    private static $allowed_actions = array(
47
        'export',
48
        'ImportForm'
49
    );
50
51
    private static $url_handlers = array(
52
        '$ModelClass/export/$ID!' => 'export',
53
        '$ModelClass/$Action' => 'handleAction',
54
        '' => 'index'
55
    );
56
57
    private static $managed_models = WorkflowDefinition::class;
58
59
    private static $model_importers = array(
60
        'WorkflowDefinition' => WorkflowBulkLoader::class
61
    );
62
63
    private static $dependencies = array(
64
        'workflowService' => '%$' . WorkflowService::class,
65
    );
66
67
    private static $fileEditActions = 'getCMSActions';
68
69
    /**
70
     * Defaults are set in {@link getEditForm()}.
71
     *
72
     * @var array
73
     */
74
    private static $fieldOverrides = array();
75
76
    /**
77
     * @var WorkflowService
78
     */
79
    public $workflowService;
80
81
    /**
82
     * Initialise javascript translation files
83
     *
84
     * @return void
85
     */
86
    protected function init()
87
    {
88
        parent::init();
89
90
        Requirements::add_i18n_javascript('symbiote/silverstripe-advancedworkflow:client/lang');
91
        Requirements::javascript('symbiote/silverstripe-advancedworkflow:client/dist/js/advancedworkflow.js');
92
        Requirements::css('symbiote/silverstripe-advancedworkflow:client/dist/styles/advancedworkflow.css');
93
    }
94
95
    /*
96
     * Shows up to x2 GridFields for Pending and Submitted items, dependent upon the current CMS user and
97
     * that user's permissions on the objects showing in each field.
98
     */
99
    public function getEditForm($id = null, $fields = null)
100
    {
101
        $form = parent::getEditForm($id, $fields);
102
103
        // Show items submitted into a workflow for current user to action
104
        $fieldName = 'PendingObjects';
105
        $pending = $this->userObjects(Member::currentUser(), $fieldName);
106
107
        if ($this->config()->fieldOverrides) {
108
            $displayFields = $this->config()->fieldOverrides;
109
        } else {
110
            $displayFields = array(
111
                'Title'          => _t('AdvancedWorkflowAdmin.Title', 'Title'),
112
                'LastEdited'     => _t('AdvancedWorkflowAdmin.LastEdited', 'Changed'),
113
                'WorkflowTitle'  => _t('AdvancedWorkflowAdmin.WorkflowTitle', 'Effective workflow'),
114
                'WorkflowStatus' => _t('AdvancedWorkflowAdmin.WorkflowStatus', 'Current action'),
115
            );
116
        }
117
118
        // Pending/Submitted items GridField Config
119
        $config = new GridFieldConfig_Base();
120
        $config->addComponent(new GridFieldEditButton());
121
        $config->addComponent(new GridFieldDetailForm());
122
        $config->getComponentByType(GridFieldPaginator::class)->setItemsPerPage(5);
0 ignored issues
show
It seems like you code against a concrete implementation and not the interface SilverStripe\Forms\GridField\GridFieldComponent as the method setItemsPerPage() does only exist in the following implementations of said interface: SilverStripe\Forms\GridField\GridFieldPaginator.

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...
123
        $columns = $config->getComponentByType(GridFieldDataColumns::class);
124
        $columns->setFieldFormatting($this->setFieldFormatting($config));
125
126
        if ($pending->count()) {
127
            $formFieldTop = GridField::create(
128
                $fieldName,
129
                $this->isAdminUser(Member::currentUser())?
130
                    _t(
131
                        'AdvancedWorkflowAdmin.GridFieldTitleAssignedAll',
132
                        'All pending items'
133
                    ):
134
                    _t(
135
                        'AdvancedWorkflowAdmin.GridFieldTitleAssignedYour',
136
                        'Your pending items'
137
                    ),
138
                $pending,
139
                $config
140
            );
141
142
            $dataColumns = $formFieldTop->getConfig()->getComponentByType(GridFieldDataColumns::class);
143
            $dataColumns->setDisplayFields($displayFields);
144
145
            $formFieldTop->setForm($form);
146
            $form->Fields()->insertBefore($formFieldTop, WorkflowDefinition::class);
147
        }
148
149
        // Show items submitted into a workflow by current user
150
        $fieldName = 'SubmittedObjects';
151
        $submitted = $this->userObjects(Member::currentUser(), $fieldName);
152
        if ($submitted->count()) {
153
            $formFieldBottom = GridField::create(
154
                $fieldName,
155
                $this->isAdminUser(Member::currentUser())?
156
                    _t(
157
                        'AdvancedWorkflowAdmin.GridFieldTitleSubmittedAll',
158
                        'All submitted items'
159
                    ):
160
                    _t(
161
                        'AdvancedWorkflowAdmin.GridFieldTitleSubmittedYour',
162
                        'Your submitted items'
163
                    ),
164
                $submitted,
165
                $config
166
            );
167
168
            $dataColumns = $formFieldBottom->getConfig()->getComponentByType(GridFieldDataColumns::class);
169
            $dataColumns->setDisplayFields($displayFields);
170
171
            $formFieldBottom->setForm($form);
172
            $formFieldBottom->getConfig()->removeComponentsByType(GridFieldEditButton::class);
173
            $formFieldBottom->getConfig()->addComponent(new GridFieldWorkflowRestrictedEditButton());
174
            $form->Fields()->insertBefore($formFieldBottom, WorkflowDefinition::class);
175
        }
176
177
        $grid = $form->Fields()->dataFieldByName(WorkflowDefinition::class);
178
        if ($grid) {
179
            $grid->getConfig()->getComponentByType(GridFieldDetailForm::class)
180
                ->setItemEditFormCallback(function ($form) {
181
                    $record = $form->getRecord();
182
                    if ($record) {
183
                        $record->updateAdminActions($form->Actions());
184
                    }
185
                });
186
187
            $grid->getConfig()->getComponentByType(GridFieldDetailForm::class)
188
                ->setItemRequestClass(WorkflowDefinitionItemRequestClass::class);
189
            $grid->getConfig()->addComponent(new GridFieldExportAction());
190
            $grid->getConfig()->removeComponentsByType(GridFieldExportButton::class);
191
        }
192
193
        return $form;
194
    }
195
196
    /*
197
     * @param Member $user
198
     * @return boolean
199
     */
200
    public function isAdminUser(Member $user)
201
    {
202
        if (Permission::checkMember($user, 'ADMIN')) {
203
            return true;
204
        }
205
        return false;
206
    }
207
208
    /*
209
     * By default, we implement GridField_ColumnProvider to allow users to click through to the PagesAdmin.
210
     * We would also like a "Quick View", that allows users to quickly make a decision on a given workflow-bound
211
     * content-object
212
     */
213
    public function columns()
214
    {
215
        $fields = array(
216
            'Title' => array(
217
                'link' => function ($value, $item) {
218
                    $pageAdminLink = singleton(CMSPageEditController::class)->Link('show');
219
                    return sprintf('<a href="%s/%s">%s</a>', $pageAdminLink, $item->Link, $value);
220
                }
221
            ),
222
            'WorkflowStatus' => array(
223
                'text' => function ($value, $item) {
224
                    return $item->WorkflowCurrentAction;
225
                }
226
            )
227
        );
228
        return $fields;
229
    }
230
231
    /*
232
     * Discreet method used by both intro gridfields to format the target object's links and clickable text
233
     *
234
     * @param GridFieldConfig $config
235
     * @return array $fieldFormatting
236
     */
237
    public function setFieldFormatting(&$config)
238
    {
239
        $fieldFormatting = array();
240
        // Parse the column information
241
        foreach ($this->columns() as $source => $info) {
242
            if (isset($info['link']) && $info['link']) {
243
                $fieldFormatting[$source] = '<a href=\"$ObjectRecordLink\">$value</a>';
244
            }
245
            if (isset($info['text']) && $info['text']) {
246
                $fieldFormatting[$source] = $info['text'];
247
            }
248
        }
249
        return $fieldFormatting;
250
    }
251
252
    /**
253
     * Get WorkflowInstance Target objects to show for users in initial gridfield(s)
254
     *
255
     * @param Member $member
256
     * @param string $fieldName The name of the gridfield that determines which dataset to return
257
     * @return DataList
258
     * @todo Add the ability to see embargo/expiry dates in report-gridfields at-a-glance if QueuedJobs module installed
259
     */
260
    public function userObjects(Member $user, $fieldName)
261
    {
262
        $list = new ArrayList();
263
        $userWorkflowInstances = $this->getFieldDependentData($user, $fieldName);
264
        foreach ($userWorkflowInstances as $instance) {
265
            if (!$instance->TargetID || !$instance->DefinitionID) {
266
                continue;
267
            }
268
            // @todo can we use $this->getDefinitionFor() to fetch the "Parent" definition of $instance? Maybe
269
            // define $this->workflowParent()
270
            $effectiveWorkflow = DataObject::get_by_id(WorkflowDefinition::class, $instance->DefinitionID);
271
            $target = $instance->getTarget();
272
            if (!is_object($effectiveWorkflow) || !$target) {
273
                continue;
274
            }
275
            $instance->setField('WorkflowTitle', $effectiveWorkflow->getField('Title'));
276
            $instance->setField('WorkflowCurrentAction', $instance->getCurrentAction());
277
            // Note the order of property-setting here, somehow $instance->Title is overwritten by the Target
278
            // Title property..
279
            $instance->setField('Title', $target->getField('Title'));
280
            $instance->setField('LastEdited', $target->getField('LastEdited'));
281
            if (method_exists($target, 'CMSEditLink')) {
282
                $instance->setField('ObjectRecordLink', $target->CMSEditLink());
283
            }
284
285
            $list->push($instance);
286
        }
287
        return $list;
288
    }
289
290
    /*
291
     * Return content-object data depending on which gridfeld is calling for it
292
     *
293
     * @param Member $user
294
     * @param string $fieldName
295
     */
296
    public function getFieldDependentData(Member $user, $fieldName)
297
    {
298
        if ($fieldName == 'PendingObjects') {
299
            return $this->workflowService->userPendingItems($user);
300
        }
301
        if ($fieldName == 'SubmittedObjects') {
302
            return $this->workflowService->userSubmittedItems($user);
303
        }
304
    }
305
306
    /**
307
     * Spits out an exported version of the selected WorkflowDefinition for download.
308
     *
309
     * @param HTTPRequest $request
310
     * @return HTTPResponse
311
     */
312
    public function export(HTTPRequest $request)
313
    {
314
        $url = explode('/', $request->getURL());
315
        $definitionID = end($url);
316
        if ($definitionID && is_numeric($definitionID)) {
317
            $exporter = new WorkflowDefinitionExporter($definitionID);
318
            $exportFilename = WorkflowDefinitionExporter::$export_filename_prefix.'-'.$definitionID.'.yml';
319
            $exportBody = $exporter->export();
320
            $fileData = array(
321
                'name' => $exportFilename,
322
                'mime' => 'text/x-yaml',
323
                'body' => $exportBody,
324
                'size' => $exporter->getExportSize($exportBody)
325
            );
326
            return $exporter->sendFile($fileData);
327
        }
328
    }
329
330
    /**
331
     * Required so we can simply change the visible label of the "Import" button and lose some redundant form-fields.
332
     *
333
     * @return Form
334
     */
335
    public function ImportForm()
336
    {
337
        $form = parent::ImportForm();
338
        if (!$form) {
339
            return;
340
        }
341
342
        $form->unsetAllActions();
343
        $newActionList = new FieldList(array(
344
            new FormAction('import', _t('AdvancedWorkflowAdmin.IMPORT', 'Import workflow'))
345
        ));
346
        $form->Fields()->fieldByName('_CsvFile')->getValidator()->setAllowedExtensions(array('yml', 'yaml'));
347
        $form->Fields()->removeByName('EmptyBeforeImport');
348
        $form->setActions($newActionList);
349
350
        return $form;
351
    }
352
}
353