WorkflowTransition   A
last analyzed

Complexity

Total Complexity 31

Size/Duplication

Total Lines 237
Duplicated Lines 4.64 %

Coupling/Cohesion

Components 2
Dependencies 14
Metric Value
wmc 31
lcom 2
cbo 14
dl 11
loc 237
rs 9.8

14 Methods

Rating   Name   Duplication   Size   Complexity  
A isValid() 0 3 1
A validate() 0 4 1
A numChildren() 0 3 1
A canCreate() 0 3 1
A canEdit() 0 3 1
A canDelete() 0 3 1
A extendedRequiredFieldsNotSame() 0 17 4
A onBeforeWrite() 0 7 2
B getCMSFields() 0 56 8
A fieldLabels() 0 8 1
A getValidator() 0 5 1
A summaryFields() 0 5 1
B canExecute() 0 18 6
A getAssignedMembers() 11 11 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * A workflow transition.
4
 *
5
 * When used within the context of a workflow, the transition will have its
6
 * "isValid()" method call. This must return true or false to indicate whether
7
 * this transition is valid for the state of the workflow that it a part of.
8
 *
9
 * Therefore, any logic around whether the workflow can proceed should be
10
 * managed within this method.
11
 *
12
 * @author  [email protected]
13
 * @license BSD License (http://silverstripe.org/bsd-license/)
14
 * @package advancedworkflow
15
 */
16
class WorkflowTransition extends DataObject {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
17
18
	private static $db = 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 $db 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...
19
		'Title' 	=> 'Varchar(128)',
20
		'Sort'  	=> 'Int',
21
		'Type' 		=> "Enum('Active, Passive', 'Active')"
22
	);
23
24
	private static $default_sort = 'Sort';
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 $default_sort 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...
25
26
	private static $has_one = 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 $has_one 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...
27
		'Action' => 'WorkflowAction',
28
		'NextAction' => 'WorkflowAction',
29
	);
30
31
	private static $many_many = 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 $many_many 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...
32
		'Users'  => 'Member',
33
		'Groups' => 'Group'
34
	);
35
36
	public static $icon = 'advancedworkflow/images/transition.png';
37
38
	/**
39
	 *
40
	 * @var array $extendedMethodReturn A basic extended validation routine method return format
41
	 */
42
	public static $extendedMethodReturn = array(
43
		'fieldName'	=>null,
44
		'fieldField'=>null,
45
		'fieldMsg'	=>null,
46
		'fieldValid'=>true
47
	);
48
49
	/**
50
	 * Returns true if it is valid for this transition to be followed given the
51
	 * current state of a workflow.
52
	 *
53
	 * @param  WorkflowInstance $workflow
54
	 * @return bool
55
	 */
56
	public function isValid(WorkflowInstance $workflow) {
0 ignored issues
show
Unused Code introduced by
The parameter $workflow 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...
57
		return true;
58
	}
59
60
	/**
61
	 * Before saving, make sure we're not in an infinite loop
62
	 */
63
	public function onBeforeWrite() {
64
		if(!$this->Sort) {
0 ignored issues
show
Documentation introduced by
The property Sort does not exist on object<WorkflowTransition>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
65
			$this->Sort = DB::query('SELECT MAX("Sort") + 1 FROM "WorkflowTransition"')->value();
0 ignored issues
show
Documentation introduced by
The property Sort does not exist on object<WorkflowTransition>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
66
		}
67
68
		parent::onBeforeWrite();
69
	}
70
71
	public function validate() {
72
		$result = parent::validate();
73
		return $result;
74
	}
75
76
	/* CMS FUNCTIONS */
77
78
	public function getCMSFields() {
0 ignored issues
show
Coding Style introduced by
getCMSFields uses the super-global variable $_REQUEST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
79
		$fields = new FieldList(new TabSet('Root'));
80
		$fields->addFieldToTab('Root.Main', new TextField('Title', $this->fieldLabel('Title')));
81
82
		$filter = '';
83
84
		$reqParent = isset($_REQUEST['ParentID']) ? (int) $_REQUEST['ParentID'] : 0;
85
		$attachTo = $this->ActionID ? $this->ActionID : $reqParent;
0 ignored issues
show
Documentation introduced by
The property ActionID does not exist on object<WorkflowTransition>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
86
87
		if ($attachTo) {
88
			$action = DataObject::get_by_id('WorkflowAction', $attachTo);
89
			if ($action && $action->ID) {
90
				$filter = '"WorkflowDefID" = '.((int) $action->WorkflowDefID);
91
			}
92
		}
93
94
		$actions = DataObject::get('WorkflowAction', $filter);
95
		$options = array();
96
		if ($actions) {
97
			$options = $actions->map();
98
		}
99
100
		$defaultAction = $action?$action->ID:"";
0 ignored issues
show
Bug introduced by
The variable $action does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
101
102
		$typeOptions = array(
103
			'Active' => _t('WorkflowTransition.Active', 'Active'),
104
			'Passive' => _t('WorkflowTransition.Passive', 'Passive'),
105
		);
106
107
		$fields->addFieldToTab('Root.Main', new DropdownField(
108
			'ActionID',
109
			$this->fieldLabel('ActionID'),
110
			$options, $defaultAction));
111
		$fields->addFieldToTab('Root.Main', $nextActionDropdownField = new DropdownField(
112
			'NextActionID',
113
			$this->fieldLabel('NextActionID'),
114
			$options));
115
		$nextActionDropdownField->setEmptyString(_t('WorkflowTransition.SELECTONE', '(Select one)'));
116
		$fields->addFieldToTab('Root.Main', new DropdownField(
117
			'Type',
118
			_t('WorkflowTransition.TYPE', 'Type'),
119
			$typeOptions
120
		));
121
122
		$members = Member::get();
123
		$fields->findOrMakeTab(
124
			'Root.RestrictToUsers',
125
			_t('WorkflowTransition.TabTitle', 'Restrict to users')
126
		);
127
		$fields->addFieldToTab('Root.RestrictToUsers', new CheckboxSetField('Users', _t('WorkflowDefinition.USERS', 'Restrict to Users'), $members));
128
		$fields->addFieldToTab('Root.RestrictToUsers', new TreeMultiselectField('Groups', _t('WorkflowDefinition.GROUPS', 'Restrict to Groups'), 'Group'));
129
130
		$this->extend('updateCMSFields', $fields);
131
132
		return $fields;
133
	}
134
135
	public function fieldLabels($includerelations = true) {
136
		$labels = parent::fieldLabels($includerelations);
137
		$labels['Title'] = _t('WorkflowAction.TITLE', 'Title');
138
		$labels['ActionID'] = _t('WorkflowTransition.ACTION', 'Action');
139
		$labels['NextActionID'] = _t('WorkflowTransition.NEXT_ACTION', 'Next Action');
140
141
		return $labels;
142
	}
143
144
	public function getValidator() {
145
		$required = new AWRequiredFields('Title', 'ActionID', 'NextActionID');
146
		$required->setCaller($this);
147
		return $required;
148
	}
149
150
	public function numChildren() {
151
		return 0;
152
	}
153
154
	public function summaryFields() {
155
		return array(
156
			'Title' => $this->fieldLabel('Title')
157
		);
158
	}
159
160
161
	/**
162
	 * Check if the current user can execute this transition
163
	 *
164
	 * @return bool
165
	 **/
166
	public function canExecute(WorkflowInstance $workflow){
167
		$return = true;
168
		$members = $this->getAssignedMembers();
169
170
		// If not admin, check if the member is in the list of assigned members
171
		if(!Permission::check('ADMIN') && $members->exists()){
172
			if(!$members->find('ID', Member::currentUserID())) {
173
				$return = false;
174
			}
175
		}
176
177
		if($return) {
178
			$extended = $this->extend('extendCanExecute', $workflow);
179
			if($extended) $return = min($extended);
0 ignored issues
show
Bug Best Practice introduced by
The expression $extended of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
180
		}
181
182
		return $return !== false;
183
	}
184
185
	/**
186
	 * Allows users who have permission to create a WorkflowDefinition, to create actions on it too.
187
	 *
188
	 * @param  Member $member
189
	 * @return bool
190
	 */
191
	public function canCreate($member = null) {
192
		return $this->Action()->WorkflowDef()->canCreate($member);
0 ignored issues
show
Bug introduced by
The method Action() does not exist on WorkflowTransition. Did you maybe mean getCMSActions()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
193
	}
194
195
	/**
196
	 * @param  Member $member
197
	 * @return bool
198
	 */
199
	public function canEdit($member = null) {
200
		return $this->canCreate($member);
201
	}
202
203
	/**
204
	 * @param  Member $member
205
	 * @return bool
206
	 */
207
	public function canDelete($member = null) {
208
		return $this->canCreate($member);
209
	}
210
211
	/**
212
	 * Returns a set of all Members that are assigned to this transition, either directly or via a group.
213
	 *
214
	 * @return ArrayList
215
	 */
216 View Code Duplication
	public function getAssignedMembers() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
217
		$members = ArrayList::create($this->Users()->toArray());
0 ignored issues
show
Documentation Bug introduced by
The method Users does not exist on object<WorkflowTransition>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
218
		$groups  = $this->Groups();
0 ignored issues
show
Documentation Bug introduced by
The method Groups does not exist on object<WorkflowTransition>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
219
220
		foreach($groups as $group) {
221
			$members->merge($group->Members());
222
		}
223
224
		$members->removeDuplicates();
225
		return $members;
226
	}
227
228
	/*
229
	 * A simple field same-value checker.
230
	 *
231
	 * @param array $data
232
	 * @return array
233
	 * @see {@link AWRequiredFields}
234
	 */
235
	public function extendedRequiredFieldsNotSame($data=null) {
236
		$check = array('ActionID','NextActionID');
237
		foreach($check as $fieldName) {
238
			if(!isset($data[$fieldName])) {
239
				return self::$extendedMethodReturn;
240
			}
241
		}
242
		// Have we found some identical values?
243
		if($data[$check[0]] == $data[$check[1]]) {
244
			self::$extendedMethodReturn['fieldName'] = $check[0]; // Used to display to the user, so the first of the array is fine
245
			self::$extendedMethodReturn['fieldValid'] = false;
246
			self::$extendedMethodReturn['fieldMsg'] = _t(
247
				'WorkflowTransition.TRANSITIONLOOP',
248
				'A transition cannot lead back to its parent action.');
249
		}
250
		return self::$extendedMethodReturn;
251
	}
252
}