Completed
Push — master ( 773b09...eef4b8 )
by Damian
02:27
created

NotifyUsersWorkflowAction   A

Complexity

Total Complexity 23

Size/Duplication

Total Lines 192
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 14

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 23
c 1
b 0
f 0
lcom 1
cbo 14
dl 0
loc 192
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getCMSFields() 0 18 1
A fieldLabels() 0 11 1
C execute() 0 65 9
B getContextFields() 0 19 5
B getMemberFields() 0 16 6
B getFormattingHelp() 0 26 1
1
<?php
2
/**
3
 * A workflow action that notifies users attached to the workflow path that they have a task awaiting them.
4
 *
5
 * @license    BSD License (http://silverstripe.org/bsd-license/)
6
 * @package    advancedworkflow
7
 * @subpackage actions
8
 */
9
class NotifyUsersWorkflowAction extends WorkflowAction {
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...
10
11
	/**
12
	 * @var bool Should templates be constrained to just known-safe variables.
13
	 */
14
	private static $whitelist_template_variables = false;
0 ignored issues
show
Unused Code introduced by
The property $whitelist_template_variables 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...
15
16
	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...
17
		'EmailSubject'			=> 'Varchar(100)',
18
		'EmailFrom'				=> 'Varchar(50)',
19
		'EmailTemplate'			=> 'Text'
20
	);
21
22
	public static $icon = 'advancedworkflow/images/notify.png';
23
24
	public function getCMSFields() {
25
		$fields = parent::getCMSFields();
26
27
		$fields->addFieldsToTab('Root.Main', array(
28
			new HeaderField('NotificationEmail', $this->fieldLabel('NotificationEmail')),
29
			new LiteralField('NotificationNote', '<p>' . $this->fieldLabel('NotificationNote') . '</p>'),
30
			new TextField('EmailSubject', $this->fieldLabel('EmailSubject')),
31
			new TextField('EmailFrom', $this->fieldLabel('EmailFrom')),
32
33
			new TextareaField('EmailTemplate', $this->fieldLabel('EmailTemplate')),
34
			new ToggleCompositeField('FormattingHelpContainer',
35
				$this->fieldLabel('FormattingHelp'), new LiteralField('FormattingHelp', $this->getFormattingHelp()))
0 ignored issues
show
Documentation introduced by
new \LiteralField('Forma...s->getFormattingHelp()) is of type object<LiteralField>, but the function expects a array|object<FieldList>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
36
		));
37
38
		$this->extend('updateNotifyUsersCMSFields', $fields);
39
40
		return $fields;
41
	}
42
43
	public function fieldLabels($relations = true) {
44
		return array_merge(parent::fieldLabels($relations), array(
45
			'NotificationEmail' => _t('NotifyUsersWorkflowAction.NOTIFICATIONEMAIL', 'Notification Email'),
46
			'NotificationNote'  => _t('NotifyUsersWorkflowAction.NOTIFICATIONNOTE',
47
				'All users attached to the workflow will be sent an email when this action is run.'),
48
			'EmailSubject'      => _t('NotifyUsersWorkflowAction.EMAILSUBJECT', 'Email subject'),
49
			'EmailFrom'         => _t('NotifyUsersWorkflowAction.EMAILFROM', 'Email from'),
50
			'EmailTemplate'     => _t('NotifyUsersWorkflowAction.EMAILTEMPLATE', 'Email template'),
51
			'FormattingHelp'    => _t('NotifyUsersWorkflowAction.FORMATTINGHELP', 'Formatting Help')
52
		));
53
	}
54
55
	public function execute(WorkflowInstance $workflow) {
56
		$members = $workflow->getAssignedMembers();
57
58
		if(!$members || !count($members)) {
59
			return true;
60
		}
61
62
		$member = Member::currentUser();
63
		$initiator = $workflow->Initiator();
64
65
		$contextFields   = $this->getContextFields($workflow->getTarget());
0 ignored issues
show
Bug introduced by
It seems like $workflow->getTarget() can be null; however, getContextFields() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
66
		$memberFields    = $this->getMemberFields($member);
0 ignored issues
show
Bug introduced by
It seems like $member defined by \Member::currentUser() on line 62 can also be of type object<DataObject>; however, NotifyUsersWorkflowAction::getMemberFields() does only seem to accept null|object<Member>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
67
		$initiatorFields = $this->getMemberFields($initiator);
68
69
		$variables = array();
70
		
71
		foreach($contextFields as $field => $val) $variables["\$Context.$field"] = $val;
72
		foreach($memberFields as $field => $val)  $variables["\$Member.$field"] = $val;
73
		foreach($initiatorFields as $field => $val)  $variables["\$Initiator.$field"] = $val;
74
75
		$pastActions = $workflow->Actions()->sort('Created DESC');
0 ignored issues
show
Bug introduced by
The method Actions() does not exist on WorkflowInstance. Did you maybe mean getFrontEndWorkflowActions()?

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...
76
		$variables["\$CommentHistory"] = $this->customise(array(
77
			'PastActions'=>$pastActions,
78
			'Now'=>SS_Datetime::now()
79
		))->renderWith('CommentHistory');
80
81
		$from = str_replace(array_keys($variables), array_values($variables), $this->EmailFrom);
0 ignored issues
show
Documentation introduced by
The property EmailFrom does not exist on object<NotifyUsersWorkflowAction>. 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...
82
		$subject = str_replace(array_keys($variables), array_values($variables), $this->EmailSubject);
0 ignored issues
show
Documentation introduced by
The property EmailSubject does not exist on object<NotifyUsersWorkflowAction>. 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...
83
84
		if ($this->config()->whitelist_template_variables) {
85
			$item = new ArrayData(array(
86
				'Initiator' => new ArrayData($initiatorFields),
87
				'Member' => new ArrayData($memberFields),
88
				'Context' => new ArrayData($contextFields),
89
				'CommentHistory' => $variables["\$CommentHistory"]
90
			));
91
		}
92
		else {
93
			$item = $workflow->customise(array(
94
				'Items' => $workflow->Actions(),
0 ignored issues
show
Bug introduced by
The method Actions() does not exist on WorkflowInstance. Did you maybe mean getFrontEndWorkflowActions()?

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...
95
				'Member' => $member,
96
				'Context' => new ArrayData($contextFields),
97
				'CommentHistory' => $variables["\$CommentHistory"]
98
			));
99
		}
100
101
		
102
		$view = SSViewer::fromString($this->EmailTemplate);
0 ignored issues
show
Documentation introduced by
The property EmailTemplate does not exist on object<NotifyUsersWorkflowAction>. 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...
103
		$this->extend('updateView', $view);
104
105
		$body = $view->process($item);
106
107
		foreach($members as $member) {
108
			if($member->Email) {
109
				$email = new Email;
110
				$email->setTo($member->Email);
111
				$email->setSubject($subject);
112
				$email->setFrom($from);
113
				$email->setBody($body);
114
				$email->send();
115
			}
116
		}
117
118
		return true;
119
	}
120
121
	/**
122
	 * @param  DataObject $target
123
	 * @return array
124
	 */
125
	public function getContextFields(DataObject $target) {
126
		$result = array();
127
		if (!$target) {
128
			return $result;
129
		}
130
		$fields = $target->inheritedDatabaseFields();
131
132
		foreach($fields as $field => $fieldDesc) {
133
			$result[$field] = $target->$field;
134
		}
135
136
		if($target instanceof CMSPreviewable) {
137
			$result['CMSLink'] = $target->CMSEditLink();
138
		} else if ($target->hasMethod('WorkflowLink')) {
139
			$result['CMSLink'] = $target->WorkflowLink();
140
		}
141
142
		return $result;
143
	}
144
145
	/**
146
	 * Builds an array with the member information
147
	 * @param Member $member An optional member to use. If null, will use the current logged in member
148
	 * @return array
149
	 */
150
	public function getMemberFields(Member $member = null) {
151
		if (!$member){
152
			$member = Member::currentUser();
153
		}
154
		$result = array();
155
156
		if($member) foreach($member->summaryFields() as $field => $title) {
157
			$result[$field] = $member->$field;
158
		}
159
160
		if($member && !array_key_exists('Name', $result)) {
161
			$result['Name'] = $member->getName();
162
		}
163
164
		return $result;
165
	}
166
	
167
168
	/**
169
	 * Returns a basic set of instructions on how email templates are populated with variables.
170
	 *
171
	 * @return string
172
	 */
173
	public function getFormattingHelp() {
174
		$note = _t('NotifyUsersWorkflowAction.FORMATTINGNOTE',
175
			'Notification emails can contain HTML formatting. The following special variables are replaced with their
176
			respective values in the email subject, email from and template/body.');
177
		$member = _t('NotifyUsersWorkflowAction.MEMBERNOTE',
178
			'These fields will be populated from the member that initiates the notification action. For example,
179
			{$Member.FirstName}.');
180
		$initiator = _t('NotifyUsersWorkflowAction.INITIATORNOTE',
181
			'These fields will be populated from the member that initiates the workflow request. For example,
182
			{$Initiator.Email}.');
183
		$context = _t('NotifyUsersWorkflowAction.CONTEXTNOTE',
184
			'Any summary fields from the workflow target will be available. For example, {$Context.Title}.
185
			Additionally, the {$Context.AbsoluteEditLink} variable will contain a link to edit the workflow target in
186
			the CMS (if it is a Page), and the {$Context.LinkToPendingItems} variable will generate a link to the CMS\' workflow admin,
187
			useful for allowing users to enact workflow transitions, directly from emails.');
188
		$fieldName = _t('NotifyUsersWorkflowAction.FIELDNAME', 'Field name');
189
		$commentHistory = _t('NotifyUsersWorkflowAction.COMMENTHISTORY', 'Comment history up to this notification.');
190
191
		$memberFields = implode(', ', array_keys($this->getMemberFields()));
192
193
		return "<p>$note</p>
194
			<p><strong>{\$Member.($memberFields)}</strong><br>$member</p>
195
			<p><strong>{\$Initiator.($memberFields)}</strong><br>$initiator</p>
196
			<p><strong>{\$Context.($fieldName)}</strong><br>$context</p>
197
			<p><strong>{\$CommentHistory}</strong><br>$commentHistory</p>";
198
	}
199
200
}
201