Completed
Pull Request — master (#109)
by Robbie
07:12
created

QueuedJobsAdmin::getEditForm()   B

Complexity

Conditions 4
Paths 2

Size

Total Lines 66
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 66
rs 8.8291
c 0
b 0
f 0
cc 4
eloc 42
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 SilverStripe\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 SilverStripe\QueuedJobs\Forms\GridFieldQueuedJobExecute;
17
use SilverStripe\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('SilverStripe\\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' => '%$SilverStripe\\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
     * @param int $id
67
     * @param FieldList $fields
68
     * @return Form
69
     */
70
    public function getEditForm($id = null, $fields = null)
71
    {
72
        $form = parent::getEditForm($id, $fields);
73
74
        $filter = $this->jobQueue->getJobListFilter(null, 300);
75
76
        $list = DataList::create('SilverStripe\\QueuedJobs\\DataObjects\\QueuedJobDescriptor');
77
        $list = $list->where($filter)->sort('Created', 'DESC');
78
79
        $gridFieldConfig = GridFieldConfig_RecordEditor::create()
80
            ->addComponent(new GridFieldQueuedJobExecute('execute'))
81
            ->addComponent(new GridFieldQueuedJobExecute('pause', function ($record) {
82
                return $record->JobStatus == QueuedJob::STATUS_WAIT || $record->JobStatus == QueuedJob::STATUS_RUN;
83
            }))
84
            ->addComponent(new GridFieldQueuedJobExecute('resume', function ($record) {
85
                return $record->JobStatus == QueuedJob::STATUS_PAUSED || $record->JobStatus == QueuedJob::STATUS_BROKEN;
86
            }))
87
            ->removeComponentsByType('SilverStripe\\Forms\\GridField\\GridFieldAddNewButton');
88
89
90
        // Set messages to HTML display format
91
        $formatting = array(
92
            'Messages' => function ($val, $obj) {
93
                return "<div style='max-width: 300px; max-height: 200px; overflow: auto;'>$obj->Messages</div>";
94
            },
95
        );
96
        $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...
97
            ->setFieldFormatting($formatting);
98
99
        // Replace gridfield
100
        $grid = new GridField(
101
            'SilverStripe\\QueuedJobs\\DataObjects\\QueuedJobDescriptor',
102
            _t('QueuedJobs.JobsFieldTitle', 'Jobs'),
103
            $list,
104
            $gridFieldConfig
105
        );
106
        $grid->setForm($form);
107
        $form->Fields()->replaceField('SilverStripe\\QueuedJobs\\DataObjects\\QueuedJobDescriptor', $grid);
108
109
        if (Permission::check('ADMIN')) {
110
            $types = ClassInfo::subclassesFor('SilverStripe\\QueuedJobs\\Services\\AbstractQueuedJob');
111
            $types = array_combine($types, $types);
112
            unset($types['SilverStripe\\QueuedJobs\\Services\\AbstractQueuedJob']);
113
            $jobType = DropdownField::create('JobType', _t('QueuedJobs.CREATE_JOB_TYPE', 'Create job of type'), $types);
114
            $jobType->setEmptyString('(select job to create)');
115
            $form->Fields()->push($jobType);
116
117
            $jobParams = TextareaField::create(
118
                'JobParams',
119
                _t('QueuedJobs.JOB_TYPE_PARAMS', 'Constructor parameters for job creation (one per line)')
120
            );
121
            $form->Fields()->push($jobParams);
122
123
            $form->Fields()->push(
124
                $dt = DatetimeField::create('JobStart', _t('QueuedJobs.START_JOB_TIME', 'Start job at'))
125
            );
126
            $dt->getDateField()->setConfig('showcalendar', true);
127
128
            $actions = $form->Actions();
129
            $actions->push(FormAction::create('createjob', _t('QueuedJobs.CREATE_NEW_JOB', 'Create new job')));
130
        }
131
132
        $this->extend('updateEditForm', $form);
133
134
        return $form;
135
    }
136
137
    /**
138
     * @return string
139
     */
140
    public function Tools()
141
    {
142
        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...
143
    }
144
145
    /**
146
     * @param  array $data
147
     * @param  Form $form
148
     * @return HTTPResponse
149
     */
150
    public function createjob($data, Form $form)
0 ignored issues
show
Unused Code introduced by
The parameter $form is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
151
    {
152
        if (Permission::check('ADMIN')) {
153
            $jobType = isset($data['JobType']) ? $data['JobType'] : '';
154
            $params = isset($data['JobParams']) ? explode(PHP_EOL, $data['JobParams']) : array();
155
            $time = isset($data['JobStart']) ? $data['JobStart'] : null;
156
157
            if ($jobType && class_exists($jobType)) {
158
                $jobClass = new ReflectionClass($jobType);
159
                $job = $jobClass->newInstanceArgs($params);
160
                $this->jobQueue->queueJob($job, $time);
161
            }
162
        }
163
        return $this->getResponseNegotiator()->respond($this->getRequest());
164
    }
165
}
166