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 ( 522a3e...28edb0 )
by Robbie
8s
created

NotifyUsersWorkflowAction   B

Complexity

Total Complexity 23

Size/Duplication

Total Lines 222
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 16

Importance

Changes 0
Metric Value
wmc 23
lcom 1
cbo 16
dl 0
loc 222
rs 8.4614
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getCMSFields() 0 22 1
A fieldLabels() 0 14 1
C execute() 0 71 9
B getContextFields() 0 22 5
B getMemberFields() 0 19 6
B getFormattingHelp() 0 35 1
1
<?php
2
3
namespace Symbiote\AdvancedWorkflow\Actions;
4
5
use SilverStripe\Control\Email\Email;
6
use SilverStripe\Forms\HeaderField;
7
use SilverStripe\Forms\LiteralField;
8
use SilverStripe\Forms\TextareaField;
9
use SilverStripe\Forms\TextField;
10
use SilverStripe\Forms\ToggleCompositeField;
11
use SilverStripe\ORM\CMSPreviewable;
12
use SilverStripe\ORM\DataObject;
13
use SilverStripe\ORM\FieldType\DBDatetime;
14
use SilverStripe\Security\Member;
15
use SilverStripe\Security\Security;
16
use SilverStripe\View\ArrayData;
17
use SilverStripe\View\SSViewer;
18
use Symbiote\AdvancedWorkflow\DataObjects\WorkflowAction;
19
use Symbiote\AdvancedWorkflow\DataObjects\WorkflowInstance;
20
21
/**
22
 * A workflow action that notifies users attached to the workflow path that they have a task awaiting them.
23
 *
24
 * @license    BSD License (http://silverstripe.org/bsd-license/)
25
 * @package    advancedworkflow
26
 * @subpackage actions
27
 */
28
class NotifyUsersWorkflowAction extends WorkflowAction
29
{
30
    /**
31
     * @config
32
     * @var bool Should templates be constrained to just known-safe variables.
33
     */
34
    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...
35
36
    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...
37
        'EmailSubject'  => 'Varchar(100)',
38
        'EmailFrom'     => 'Varchar(50)',
39
        'EmailTemplate' => 'Text'
40
    );
41
42
    private static $icon = 'symbiote/silverstripe-advancedworkflow:images/notify.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 $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...
43
44
    private static $table_name = 'NotifyUsersWorkflowAction';
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 $table_name 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
    public function getCMSFields()
47
    {
48
        $fields = parent::getCMSFields();
49
50
        $fields->addFieldsToTab('Root.Main', array(
51
            new HeaderField('NotificationEmail', $this->fieldLabel('NotificationEmail')),
52
            new LiteralField('NotificationNote', '<p>' . $this->fieldLabel('NotificationNote') . '</p>'),
53
            new TextField('EmailSubject', $this->fieldLabel('EmailSubject')),
54
            new TextField('EmailFrom', $this->fieldLabel('EmailFrom')),
55
56
            new TextareaField('EmailTemplate', $this->fieldLabel('EmailTemplate')),
57
            new ToggleCompositeField(
58
                'FormattingHelpContainer',
59
                $this->fieldLabel('FormattingHelp'),
60
                new LiteralField('FormattingHelp', $this->getFormattingHelp())
0 ignored issues
show
Documentation introduced by
new \SilverStripe\Forms\...s->getFormattingHelp()) is of type object<SilverStripe\Forms\LiteralField>, but the function expects a array|object<SilverStripe\Forms\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...
61
            )
62
        ));
63
64
        $this->extend('updateNotifyUsersCMSFields', $fields);
65
66
        return $fields;
67
    }
68
69
    public function fieldLabels($relations = true)
70
    {
71
        return array_merge(parent::fieldLabels($relations), array(
72
            'NotificationEmail' => _t('NotifyUsersWorkflowAction.NOTIFICATIONEMAIL', 'Notification Email'),
73
            'NotificationNote'  => _t(
74
                'NotifyUsersWorkflowAction.NOTIFICATIONNOTE',
75
                'All users attached to the workflow will be sent an email when this action is run.'
76
            ),
77
            'EmailSubject'      => _t('NotifyUsersWorkflowAction.EMAILSUBJECT', 'Email subject'),
78
            'EmailFrom'         => _t('NotifyUsersWorkflowAction.EMAILFROM', 'Email from'),
79
            'EmailTemplate'     => _t('NotifyUsersWorkflowAction.EMAILTEMPLATE', 'Email template'),
80
            'FormattingHelp'    => _t('NotifyUsersWorkflowAction.FORMATTINGHELP', 'Formatting Help')
81
        ));
82
    }
83
84
    public function execute(WorkflowInstance $workflow)
85
    {
86
        $members = $workflow->getAssignedMembers();
87
88
        if (!$members || !count($members)) {
89
            return true;
90
        }
91
92
        $member = Security::getCurrentUser();
93
        $initiator = $workflow->Initiator();
94
95
        $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...
96
        $memberFields    = $this->getMemberFields($member);
97
        $initiatorFields = $this->getMemberFields($initiator);
98
99
        $variables = array();
100
101
        foreach ($contextFields as $field => $val) {
102
            $variables["\$Context.$field"] = $val;
103
        }
104
        foreach ($memberFields as $field => $val) {
105
            $variables["\$Member.$field"] = $val;
106
        }
107
        foreach ($initiatorFields as $field => $val) {
108
            $variables["\$Initiator.$field"] = $val;
109
        }
110
111
        $pastActions = $workflow->Actions()->sort('Created DESC');
0 ignored issues
show
Bug introduced by
The method Actions() does not exist on Symbiote\AdvancedWorkflo...bjects\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...
112
        $variables["\$CommentHistory"] = $this->customise(array(
113
            'PastActions'=>$pastActions,
114
            'Now'=>DBDatetime::now()
115
        ))->renderWith('Includes/CommentHistory');
116
117
        $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<Symbiote\Advanced...ifyUsersWorkflowAction>. 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...
118
        $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<Symbiote\Advanced...ifyUsersWorkflowAction>. 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...
119
120
        if ($this->config()->whitelist_template_variables) {
121
            $item = new ArrayData(array(
122
                'Initiator' => new ArrayData($initiatorFields),
123
                'Member' => new ArrayData($memberFields),
124
                'Context' => new ArrayData($contextFields),
125
                'CommentHistory' => $variables["\$CommentHistory"]
126
            ));
127
        } else {
128
            $item = $workflow->customise(array(
129
                'Items' => $workflow->Actions(),
0 ignored issues
show
Bug introduced by
The method Actions() does not exist on Symbiote\AdvancedWorkflo...bjects\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...
130
                'Member' => $member,
131
                'Context' => new ArrayData($contextFields),
132
                'CommentHistory' => $variables["\$CommentHistory"]
133
            ));
134
        }
135
136
137
        $view = SSViewer::fromString($this->EmailTemplate);
0 ignored issues
show
Documentation introduced by
The property EmailTemplate does not exist on object<Symbiote\Advanced...ifyUsersWorkflowAction>. 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...
138
        $this->extend('updateView', $view);
139
140
        $body = $view->process($item);
141
142
        foreach ($members as $member) {
143
            if ($member->Email) {
144
                $email = new Email;
145
                $email->setTo($member->Email);
146
                $email->setSubject($subject);
147
                $email->setFrom($from);
148
                $email->setBody($body);
149
                $email->send();
150
            }
151
        }
152
153
        return true;
154
    }
155
156
    /**
157
     * @param  DataObject $target
158
     * @return array
159
     */
160
    public function getContextFields(DataObject $target)
161
    {
162
        $result = array();
163
        if (!$target) {
164
            return $result;
165
        }
166
167
        $fields = $target->getSchema()->fieldSpecs($target);
168
        unset($fields['ID']);
169
170
        foreach ($fields as $field => $fieldDesc) {
171
            $result[$field] = $target->$field;
172
        }
173
174
        if ($target instanceof CMSPreviewable) {
175
            $result['CMSLink'] = $target->CMSEditLink();
176
        } elseif ($target->hasMethod('WorkflowLink')) {
177
            $result['CMSLink'] = $target->WorkflowLink();
178
        }
179
180
        return $result;
181
    }
182
183
    /**
184
     * Builds an array with the member information
185
     * @param Member $member An optional member to use. If null, will use the current logged in member
186
     * @return array
187
     */
188
    public function getMemberFields(Member $member = null)
189
    {
190
        if (!$member) {
191
            $member = Security::getCurrentUser();
192
        }
193
        $result = array();
194
195
        if ($member) {
196
            foreach ($member->summaryFields() as $field => $title) {
197
                $result[$field] = $member->$field;
198
            }
199
        }
200
201
        if ($member && !array_key_exists('Name', $result)) {
202
            $result['Name'] = $member->getName();
203
        }
204
205
        return $result;
206
    }
207
208
209
    /**
210
     * Returns a basic set of instructions on how email templates are populated with variables.
211
     *
212
     * @return string
213
     */
214
    public function getFormattingHelp()
215
    {
216
        $note = _t(
217
            'NotifyUsersWorkflowAction.FORMATTINGNOTE',
218
            'Notification emails can contain HTML formatting. The following special variables are replaced with their
219
			respective values in the email subject, email from and template/body.'
220
        );
221
        $member = _t(
222
            'NotifyUsersWorkflowAction.MEMBERNOTE',
223
            'These fields will be populated from the member that initiates the notification action. For example,
224
			{$Member.FirstName}.'
225
        );
226
        $initiator = _t(
227
            'NotifyUsersWorkflowAction.INITIATORNOTE',
228
            'These fields will be populated from the member that initiates the workflow request. For example,
229
			{$Initiator.Email}.'
230
        );
231
        $context = _t(
232
            'NotifyUsersWorkflowAction.CONTEXTNOTE',
233
            'Any summary fields from the workflow target will be available. For example, {$Context.Title}.
234
			Additionally, the {$Context.AbsoluteEditLink} variable will contain a link to edit the workflow target in
235
			the CMS (if it is a Page), and the {$Context.LinkToPendingItems} variable will generate a link to the CMS\''
236
            . 'workflow admin, useful for allowing users to enact workflow transitions, directly from emails.'
237
        );
238
        $fieldName = _t('NotifyUsersWorkflowAction.FIELDNAME', 'Field name');
239
        $commentHistory = _t('NotifyUsersWorkflowAction.COMMENTHISTORY', 'Comment history up to this notification.');
240
241
        $memberFields = implode(', ', array_keys($this->getMemberFields()));
242
243
        return "<p>$note</p>
244
			<p><strong>{\$Member.($memberFields)}</strong><br>$member</p>
245
			<p><strong>{\$Initiator.($memberFields)}</strong><br>$initiator</p>
246
			<p><strong>{\$Context.($fieldName)}</strong><br>$context</p>
247
			<p><strong>{\$CommentHistory}</strong><br>$commentHistory</p>";
248
    }
249
}
250