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
Push — master ( 6956e2...9a55f0 )
by
unknown
02:08
created

QueuedJobsAdmin::createjob()   B

Complexity

Conditions 11
Paths 97

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 7.3166
c 0
b 0
f 0
cc 11
nc 97
nop 2

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\TextareaField;
19
use SilverStripe\ORM\DataList;
20
use SilverStripe\Security\Permission;
21
use SilverStripe\Security\Security;
22
use Symbiote\QueuedJobs\DataObjects\QueuedJobDescriptor;
23
use Symbiote\QueuedJobs\Forms\GridFieldQueuedJobExecute;
24
use Symbiote\QueuedJobs\Services\AbstractQueuedJob;
25
use Symbiote\QueuedJobs\Services\QueuedJob;
26
use Symbiote\QueuedJobs\Services\QueuedJobService;
27
28
/**
29
 * @author Marcus Nyeholt <[email protected]>
30
 * @license BSD http://silverstripe.org/bsd-license/
31
 */
32
class QueuedJobsAdmin extends ModelAdmin
33
{
34
    /**
35
     * @var string
36
     */
37
    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...
Unused Code introduced by
The property $url_segment 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...
38
39
    /**
40
     * @var string
41
     */
42
    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...
Unused Code introduced by
The property $menu_title 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...
43
44
    /**
45
     * @var string
46
     */
47
    private static $menu_icon_class = 'font-icon-checklist';
0 ignored issues
show
Unused Code introduced by
The property $menu_icon_class 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...
48
49
    /**
50
     * @var array
51
     */
52
    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...
Unused Code introduced by
The property $managed_models 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...
53
        QueuedJobDescriptor::class
54
    ];
55
56
    /**
57
     * @var array
58
     */
59
    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...
Unused Code introduced by
The property $dependencies 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...
60
        'jobQueue' => '%$' . QueuedJobService::class,
61
    ];
62
63
    /**
64
     * @var array
65
     */
66
    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...
Unused Code introduced by
The property $allowed_actions 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...
67
        'EditForm'
68
    ];
69
70
    /**
71
     * European date format
72
     * @var string
73
     */
74
    private static $date_format_european = 'dd/MM/yyyy';
75
76
    /**
77
     * @var QueuedJobService
78
     */
79
    public $jobQueue;
80
81
    /**
82
     * @config The number of seconds to include jobs that have finished
83
     * default: 300 (5 minutes), examples: 3600(1h), 86400(1d)
84
     */
85
    private static $max_finished_jobs_age = 300;
0 ignored issues
show
Unused Code introduced by
The property $max_finished_jobs_age 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...
86
87
    /**
88
     * @param int $id
89
     * @param FieldList $fields
90
     * @return Form
91
     */
92
    public function getEditForm($id = null, $fields = null)
93
    {
94
        $form = parent::getEditForm($id, $fields);
95
96
        $filter = $this->jobQueue->getJobListFilter(null, self::config()->max_finished_jobs_age);
97
98
        $list = DataList::create(QueuedJobDescriptor::class);
99
        $list = $list->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(GridFieldAddNewButton::class);
110
111
        // Set messages to HTML display format
112
        $formatting = array(
113
            'Messages' => function ($val, $obj) {
114
                return "<div style='max-width: 300px; max-height: 200px; overflow: auto;'>$obj->Messages</div>";
115
            },
116
        );
117
        $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...
118
            ->setFieldFormatting($formatting);
119
120
        // Replace gridfield
121
        /** @skipUpgrade */
122
        $grid = GridField::create(
123
            'QueuedJobDescriptor',
124
            _t(__CLASS__ . '.JobsFieldTitle', 'Jobs'),
125
            $list,
126
            $gridFieldConfig
127
        );
128
        $grid->setForm($form);
129
        /** @skipUpgrade */
130
        $form->Fields()->replaceField($this->sanitiseClassName(QueuedJobDescriptor::class), $grid);
131
132
        if (Permission::check('ADMIN')) {
133
            $types = ClassInfo::subclassesFor(AbstractQueuedJob::class);
134
            $types = array_combine($types, $types);
135
            foreach ($types as $class) {
136
                $reflection = new ReflectionClass($class);
137
                if (!$reflection->isInstantiable()) {
138
                    unset($types[$class]);
139
                }
140
            }
141
            $jobType = DropdownField::create('JobType', _t(__CLASS__ . '.CREATE_JOB_TYPE', 'Create job of type'), $types);
142
            $jobType->setEmptyString('(select job to create)');
143
            $form->Fields()->push($jobType);
144
145
            $jobParams = TextareaField::create(
146
                'JobParams',
147
                _t(__CLASS__ . '.JOB_TYPE_PARAMS', 'Constructor parameters for job creation (one per line)')
148
            );
149
            $form->Fields()->push($jobParams);
150
151
            $form->Fields()->push(
152
                $dt = DatetimeField::create('JobStart', _t(__CLASS__ . '.START_JOB_TIME', 'Start job at'))
153
            );
154
155
            $actions = $form->Actions();
156
            $actions->push(
157
                FormAction::create('createjob', _t(__CLASS__ . '.CREATE_NEW_JOB', 'Create new job'))
158
                    ->addExtraClass('btn btn-primary')
159
            );
160
        }
161
162
        $this->extend('updateEditForm', $form);
163
164
        return $form;
165
    }
166
167
    /**
168
     * @return string
169
     */
170
    public function Tools()
171
    {
172
        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...
173
    }
174
175
    /**
176
     * @param  array $data
177
     * @param  Form $form
178
     * @return HTTPResponse
179
     */
180
    public function createjob($data, Form $form)
181
    {
182
        if (Permission::check('ADMIN')) {
183
            $jobType = isset($data['JobType']) ? $data['JobType'] : '';
184
            $params = isset($data['JobParams']) ? explode(PHP_EOL, $data['JobParams']) : array();
185
            $time = isset($data['JobStart']) && is_array($data['JobStart']) ? implode(" ", $data['JobStart']) : null;
186
187
            // If the user has select the European date format as their setting then replace '/' with '-' in the date string so PHP
188
            // treats the date as this format.
189
            if (Security::getCurrentUser()->DateFormat == self::$date_format_european) {
190
                $time = str_replace('/', '-', $time);
191
            }
192
193
            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...
194
                $jobClass = new ReflectionClass($jobType);
195
                $job = $jobClass->newInstanceArgs($params);
196
                if ($this->jobQueue->queueJob($job, $time)) {
197
                    $form->sessionMessage(_t(__CLASS__ . '.QueuedJobSuccess', 'Successfully queued job'), 'success');
198
                }
199
            }
200
        }
201
        return $this->redirectBack();
202
    }
203
}
204