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 ( 646ea8...4450cc )
by Robbie
13s
created

QueuedJobsAdmin::createjob()   C

Complexity

Conditions 10
Paths 97

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 5.6534
c 0
b 0
f 0
cc 10
eloc 13
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\Core\ClassInfo;
8
use SilverStripe\Forms\DatetimeField;
9
use SilverStripe\Forms\DropdownField;
10
use SilverStripe\Forms\Form;
11
use SilverStripe\Forms\FormAction;
12
use SilverStripe\Forms\GridField\GridField;
13
use SilverStripe\Forms\GridField\GridFieldAddNewButton;
14
use SilverStripe\Forms\GridField\GridFieldConfig_RecordEditor;
15
use SilverStripe\Forms\GridField\GridFieldDataColumns;
16
use SilverStripe\Forms\TextareaField;
17
use SilverStripe\ORM\DataList;
18
use SilverStripe\Security\Member;
19
use SilverStripe\Security\Permission;
20
use Symbiote\QueuedJobs\DataObjects\QueuedJobDescriptor;
21
use Symbiote\QueuedJobs\Forms\GridFieldQueuedJobExecute;
22
use Symbiote\QueuedJobs\Services\AbstractQueuedJob;
23
use Symbiote\QueuedJobs\Services\QueuedJob;
24
use Symbiote\QueuedJobs\Services\QueuedJobService;
25
26
/**
27
 * @author Marcus Nyeholt <[email protected]>
28
 * @license BSD http://silverstripe.org/bsd-license/
29
 */
30
class QueuedJobsAdmin extends ModelAdmin
31
{
32
    /**
33
     * @var string
34
     */
35
    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...
36
37
    /**
38
     * @var string
39
     */
40
    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...
41
42
    /**
43
     * @var string
44
     */
45
    private static $menu_icon = "queuedjobs/images/clipboard.png";
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_icon 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...
46
47
    /**
48
     * @var array
49
     */
50
    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...
51
        QueuedJobDescriptor::class
52
    ];
53
54
    /**
55
     * @var array
56
     */
57
    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...
58
        'jobQueue' => '%$' . QueuedJobService::class,
59
    ];
60
61
    /**
62
     * @var array
63
     */
64
    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...
65
        'EditForm'
66
    ];
67
68
    /**
69
     * European date format
70
     * @var string
71
     */
72
    private static $date_format_european = 'dd/MM/yyyy';
73
74
    /**
75
     * @var QueuedJobService
76
     */
77
    public $jobQueue;
78
79
    /**
80
     * @config The number of seconds to include jobs that have finished
81
     * default: 300 (5 minutes), examples: 3600(1h), 86400(1d)
82
     */
83
    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...
84
85
    /**
86
     * @param int $id
87
     * @param FieldList $fields
88
     * @return Form
89
     */
90
    public function getEditForm($id = null, $fields = null)
91
    {
92
        $form = parent::getEditForm($id, $fields);
93
94
        $filter = $this->jobQueue->getJobListFilter(null, self::config()->max_finished_jobs_age);
95
96
        $list = DataList::create(QueuedJobDescriptor::class);
97
        $list = $list->where($filter)->sort('Created', 'DESC');
98
99
        $gridFieldConfig = GridFieldConfig_RecordEditor::create()
100
            ->addComponent(new GridFieldQueuedJobExecute('execute'))
101
            ->addComponent(new GridFieldQueuedJobExecute('pause', function ($record) {
102
                return $record->JobStatus == QueuedJob::STATUS_WAIT || $record->JobStatus == QueuedJob::STATUS_RUN;
103
            }))
104
            ->addComponent(new GridFieldQueuedJobExecute('resume', function ($record) {
105
                return $record->JobStatus == QueuedJob::STATUS_PAUSED || $record->JobStatus == QueuedJob::STATUS_BROKEN;
106
            }))
107
            ->removeComponentsByType(GridFieldAddNewButton::class);
108
109
110
        // Set messages to HTML display format
111
        $formatting = array(
112
            'Messages' => function ($val, $obj) {
113
                return "<div style='max-width: 300px; max-height: 200px; overflow: auto;'>$obj->Messages</div>";
114
            },
115
        );
116
        $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...
117
            ->setFieldFormatting($formatting);
118
119
        // Replace gridfield
120
        /** @skipUpgrade */
121
        $grid = GridField::create(
122
            QueuedJobDescriptor::class,
123
            _t(__CLASS__ . '.JobsFieldTitle', 'Jobs'),
124
            $list,
125
            $gridFieldConfig
126
        );
127
        $grid->setForm($form);
128
        /** @skipUpgrade */
129
        $form->Fields()->replaceField('QueuedJobDescriptor', $grid);
130
131
        if (Permission::check('ADMIN')) {
132
            $types = ClassInfo::subclassesFor(AbstractQueuedJob::class);
133
            $types = array_combine($types, $types);
134
            unset($types[AbstractQueuedJob::class]);
135
            $jobType = DropdownField::create('JobType', _t(__CLASS__ . '.CREATE_JOB_TYPE', 'Create job of type'), $types);
136
            $jobType->setEmptyString('(select job to create)');
137
            $form->Fields()->push($jobType);
138
139
            $jobParams = TextareaField::create(
140
                'JobParams',
141
                _t(__CLASS__ . '.JOB_TYPE_PARAMS', 'Constructor parameters for job creation (one per line)')
142
            );
143
            $form->Fields()->push($jobParams);
144
145
            $form->Fields()->push(
146
                $dt = DatetimeField::create('JobStart', _t(__CLASS__ . '.START_JOB_TIME', 'Start job at'))
147
            );
148
149
            $actions = $form->Actions();
150
            $actions->push(
151
                FormAction::create('createjob', _t(__CLASS__ . '.CREATE_NEW_JOB', 'Create new job'))
152
                    ->addExtraClass('btn btn-primary')
153
            );
154
        }
155
156
        $this->extend('updateEditForm', $form);
157
158
        return $form;
159
    }
160
161
    /**
162
     * @return string
163
     */
164
    public function Tools()
165
    {
166
        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...
167
    }
168
169
    /**
170
     * @param  array $data
171
     * @param  Form $form
172
     * @return HTTPResponse
173
     */
174
    public function createjob($data, Form $form)
175
    {
176
        if (Permission::check('ADMIN')) {
177
            $jobType = isset($data['JobType']) ? $data['JobType'] : '';
178
            $params = isset($data['JobParams']) ? explode(PHP_EOL, $data['JobParams']) : array();
179
            $time = isset($data['JobStart']) && is_array($data['JobStart']) ? implode(" ", $data['JobStart']) : null;
180
181
            // If the user has select the European date format as their setting then replace '/' with '-' in the date string so PHP
182
            // treats the date as this format.
183
            if (Member::currentUser()->DateFormat == self::$date_format_european) {
0 ignored issues
show
Deprecated Code introduced by
The method SilverStripe\Security\Member::currentUser() has been deprecated with message: 5.0.0 use Security::getCurrentUser()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
184
                $time = str_replace('/', '-', $time);
185
            }
186
187
            if ($jobType && class_exists($jobType)) {
188
                $jobClass = new ReflectionClass($jobType);
189
                $job = $jobClass->newInstanceArgs($params);
190
                if ($this->jobQueue->queueJob($job, $time)) {
191
                    $form->sessionMessage(_t(__CLASS__ . '.QueuedJobSuccess', 'Successfully queued job'), 'success');
192
                }
193
            }
194
        }
195
        return $this->redirectBack();
196
    }
197
}
198