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.

QueuedJobsAdmin   A
last analyzed

Complexity

Total Complexity 18

Size/Duplication

Total Lines 184
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 16

Importance

Changes 0
Metric Value
wmc 18
lcom 1
cbo 16
dl 0
loc 184
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
B getEditForm() 0 81 6
A Tools() 0 4 1
B createjob() 0 28 11
1
<?php
2
3
namespace Symbiote\QueuedJobs\Controllers;
4
5
use ReflectionClass;
6
use SilverStripe\Admin\ModelAdmin;
7
use SilverStripe\Control\HTTPResponse;
8
use SilverStripe\Core\ClassInfo;
9
use SilverStripe\Forms\DatetimeField;
10
use SilverStripe\Forms\DropdownField;
11
use SilverStripe\Forms\FieldList;
12
use SilverStripe\Forms\Form;
13
use SilverStripe\Forms\FormAction;
14
use SilverStripe\Forms\GridField\GridField;
15
use SilverStripe\Forms\GridField\GridFieldAddNewButton;
16
use SilverStripe\Forms\GridField\GridFieldConfig_RecordEditor;
17
use SilverStripe\Forms\GridField\GridFieldDataColumns;
18
use SilverStripe\Forms\GridField\GridFieldPageCount;
19
use SilverStripe\Forms\GridField\GridFieldToolbarHeader;
20
use SilverStripe\Forms\TextareaField;
21
use SilverStripe\Security\Permission;
22
use SilverStripe\Security\Security;
23
use Symbiote\QueuedJobs\DataObjects\QueuedJobDescriptor;
24
use Symbiote\QueuedJobs\Forms\GridFieldQueuedJobExecute;
25
use Symbiote\QueuedJobs\Services\AbstractQueuedJob;
26
use Symbiote\QueuedJobs\Services\QueuedJob;
27
use Symbiote\QueuedJobs\Services\QueuedJobService;
28
29
/**
30
 * @author Marcus Nyeholt <[email protected]>
31
 * @license BSD http://silverstripe.org/bsd-license/
32
 */
33
class QueuedJobsAdmin extends ModelAdmin
34
{
35
    /**
36
     * @var string
37
     */
38
    private static $url_segment = 'queuedjobs';
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...
39
40
    /**
41
     * @var string
42
     */
43
    private static $menu_title = 'Jobs';
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...
44
45
    /**
46
     * @var string
47
     */
48
    private static $menu_icon_class = 'font-icon-checklist';
49
50
    /**
51
     * @var array
52
     */
53
    private static $managed_models = [
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...
54
        QueuedJobDescriptor::class
55
    ];
56
57
    /**
58
     * @var array
59
     */
60
    private static $dependencies = [
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...
61
        'jobQueue' => '%$' . QueuedJobService::class,
62
    ];
63
64
    /**
65
     * @var array
66
     */
67
    private static $allowed_actions = [
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...
68
        'EditForm'
69
    ];
70
71
    /**
72
     * European date format
73
     * @var string
74
     */
75
    private static $date_format_european = 'dd/MM/yyyy';
76
77
    /**
78
     * @var QueuedJobService
79
     */
80
    public $jobQueue;
81
82
    /**
83
     * @config The number of seconds to include jobs that have finished
84
     * default: 7200 (2 hours), examples: 3600(1h), 86400(1d)
85
     */
86
    private static $max_finished_jobs_age = 7200;
87
88
    /**
89
     * @param int $id
90
     * @param FieldList $fields
91
     * @return Form
92
     */
93
    public function getEditForm($id = null, $fields = null)
94
    {
95
        $form = parent::getEditForm($id, $fields);
96
97
        $filter = $this->jobQueue->getJobListFilter(null, self::config()->max_finished_jobs_age);
98
99
        $list = QueuedJobDescriptor::get()->where($filter)->sort('Created', 'DESC');
100
101
        $gridFieldConfig = GridFieldConfig_RecordEditor::create()
102
            ->addComponent(new GridFieldQueuedJobExecute('execute'))
103
            ->addComponent(new GridFieldQueuedJobExecute('pause', function ($record) {
104
                return $record->JobStatus == QueuedJob::STATUS_WAIT || $record->JobStatus == QueuedJob::STATUS_RUN;
105
            }))
106
            ->addComponent(new GridFieldQueuedJobExecute('resume', function ($record) {
107
                return $record->JobStatus == QueuedJob::STATUS_PAUSED || $record->JobStatus == QueuedJob::STATUS_BROKEN;
108
            }))
109
            ->removeComponentsByType([
110
                GridFieldAddNewButton::class,
111
                GridFieldPageCount::class,
112
                GridFieldToolbarHeader::class,
113
            ]);
114
115
        // Set messages to HTML display format
116
        $formatting = array(
117
            'Messages' => function ($val, $obj) {
118
                return "<div style='max-width: 300px; max-height: 200px; overflow: auto;'>$obj->Messages</div>";
119
            },
120
        );
121
        $gridFieldConfig->getComponentByType(GridFieldDataColumns::class)
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface SilverStripe\Forms\GridField\GridFieldComponent as the method setFieldFormatting() does only exist in the following implementations of said interface: SilverStripe\Forms\GridField\GridFieldDataColumns.

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
            ->setFieldFormatting($formatting);
123
124
        // Replace gridfield
125
        /** @skipUpgrade */
126
        $grid = GridField::create(
127
            'QueuedJobDescriptor',
128
            '',
129
            $list,
130
            $gridFieldConfig
131
        );
132
        $grid->setForm($form);
133
        /** @skipUpgrade */
134
        $form->Fields()->replaceField($this->sanitiseClassName(QueuedJobDescriptor::class), $grid);
135
136
        if (Permission::check('ADMIN')) {
137
            $types = ClassInfo::subclassesFor(AbstractQueuedJob::class);
138
            $types = array_combine($types, $types);
139
            foreach ($types as $class) {
140
                $reflection = new ReflectionClass($class);
141
                if (!$reflection->isInstantiable()) {
142
                    unset($types[$class]);
143
                }
144
            }
145
            $jobType = DropdownField::create(
146
                'JobType',
147
                _t(__CLASS__ . '.CREATE_JOB_TYPE', 'Create job of type'),
148
                $types
149
            );
150
            $jobType->setEmptyString('(select job to create)');
151
            $form->Fields()->push($jobType);
152
153
            $jobParams = TextareaField::create(
154
                'JobParams',
155
                _t(__CLASS__ . '.JOB_TYPE_PARAMS', 'Constructor parameters for job creation (one per line)')
156
            );
157
            $form->Fields()->push($jobParams);
158
159
            $form->Fields()->push(
160
                $dt = DatetimeField::create('JobStart', _t(__CLASS__ . '.START_JOB_TIME', 'Start job at'))
161
            );
162
163
            $actions = $form->Actions();
164
            $actions->push(
165
                FormAction::create('createjob', _t(__CLASS__ . '.CREATE_NEW_JOB', 'Create new job'))
166
                    ->addExtraClass('btn btn-primary')
167
            );
168
        }
169
170
        $this->extend('updateEditForm', $form);
171
172
        return $form;
173
    }
174
175
    /**
176
     * @return string
177
     */
178
    public function Tools()
179
    {
180
        return '';
0 ignored issues
show
Bug Best Practice introduced by
The return type of return ''; (string) is incompatible with the return type of the parent method SilverStripe\Admin\LeftAndMain::Tools of type SilverStripe\ORM\FieldType\DBHTMLText|false.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
181
    }
182
183
    /**
184
     * @param  array $data
185
     * @param  Form $form
186
     * @return HTTPResponse
187
     */
188
    public function createjob($data, Form $form)
189
    {
190
        if (Permission::check('ADMIN')) {
191
            $jobType = isset($data['JobType']) ? $data['JobType'] : '';
192
            $params = isset($data['JobParams']) ? explode(PHP_EOL, $data['JobParams']) : array();
193
194
            if (isset($data['JobStart'])) {
195
                $time = is_array($data['JobStart']) ? implode(' ', $data['JobStart']) : $data['JobStart'];
196
            } else {
197
                $time = null;
198
            }
199
200
            // If the user has select the European date format as their setting then replace '/' with '-' in the
201
            // date string so PHP treats the date as this format.
202
            if (Security::getCurrentUser()->DateFormat == self::$date_format_european) {
203
                $time = str_replace('/', '-', $time);
204
            }
205
206
            if ($jobType && class_exists($jobType) && is_subclass_of($jobType, QueuedJob::class)) {
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of might return inconsistent results on some PHP versions if \Symbiote\QueuedJobs\Services\QueuedJob::class can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
207
                $jobClass = new ReflectionClass($jobType);
208
                $job = $jobClass->newInstanceArgs($params);
209
                if ($this->jobQueue->queueJob($job, $time)) {
210
                    $form->sessionMessage(_t(__CLASS__ . '.QueuedJobSuccess', 'Successfully queued job'), 'success');
211
                }
212
            }
213
        }
214
        return $this->redirectBack();
215
    }
216
}
217