QueuedJobsAdmin::getEditForm()   B
last analyzed

Complexity

Conditions 4
Paths 2

Size

Total Lines 65
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 65
rs 8.8507
c 0
b 0
f 0
cc 4
eloc 41
nc 2
nop 2

How to fix   Long Method   

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