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 ( 7f1ae9...0c981e )
by Marcus
11s
created

NotifyUsersWorkflowAction::getContextFields()   B

Complexity

Conditions 8
Paths 49

Size

Total Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 31
rs 8.1795
c 0
b 0
f 0
cc 8
nc 49
nop 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 Swift_RfcComplianceException;
19
use Symbiote\AdvancedWorkflow\DataObjects\WorkflowAction;
20
use Symbiote\AdvancedWorkflow\DataObjects\WorkflowInstance;
21
22
/**
23
 * A workflow action that notifies users attached to the workflow path that they have a task awaiting them.
24
 *
25
 * @license    BSD License (http://silverstripe.org/bsd-license/)
26
 * @package    advancedworkflow
27
 * @subpackage actions
28
 */
29
class NotifyUsersWorkflowAction extends WorkflowAction
30
{
31
    /**
32
     * @config
33
     * @var bool Should templates be constrained to just known-safe variables.
34
     */
35
    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...
36
37
    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...
38
        'EmailSubject'  => 'Varchar(100)',
39
        'EmailFrom'     => 'Varchar(50)',
40
        'EmailTemplate' => 'Text'
41
    );
42
43
    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...
44
45
    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...
46
47
    public function getCMSFields()
48
    {
49
        $fields = parent::getCMSFields();
50
51
        $fields->addFieldsToTab('Root.Main', array(
52
            new HeaderField('NotificationEmail', $this->fieldLabel('NotificationEmail')),
53
            new LiteralField('NotificationNote', '<p>' . $this->fieldLabel('NotificationNote') . '</p>'),
54
            new TextField('EmailSubject', $this->fieldLabel('EmailSubject')),
55
            new TextField('EmailFrom', $this->fieldLabel('EmailFrom')),
56
57
            new TextareaField('EmailTemplate', $this->fieldLabel('EmailTemplate')),
58
            new ToggleCompositeField(
59
                'FormattingHelpContainer',
60
                $this->fieldLabel('FormattingHelp'),
61
                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...
62
            )
63
        ));
64
65
        $this->extend('updateNotifyUsersCMSFields', $fields);
66
67
        return $fields;
68
    }
69
70
    public function fieldLabels($relations = true)
71
    {
72
        return array_merge(parent::fieldLabels($relations), array(
73
            'NotificationEmail' => _t('NotifyUsersWorkflowAction.NOTIFICATIONEMAIL', 'Notification Email'),
74
            'NotificationNote'  => _t(
75
                'NotifyUsersWorkflowAction.NOTIFICATIONNOTE',
76
                'All users attached to the workflow will be sent an email when this action is run.'
77
            ),
78
            'EmailSubject'      => _t('NotifyUsersWorkflowAction.EMAILSUBJECT', 'Email subject'),
79
            'EmailFrom'         => _t('NotifyUsersWorkflowAction.EMAILFROM', 'Email from'),
80
            'EmailTemplate'     => _t('NotifyUsersWorkflowAction.EMAILTEMPLATE', 'Email template'),
81
            'FormattingHelp'    => _t('NotifyUsersWorkflowAction.FORMATTINGHELP', 'Formatting Help')
82
        ));
83
    }
84
85
    public function execute(WorkflowInstance $workflow)
86
    {
87
        $members = $workflow->getAssignedMembers();
88
89
        if (!$members || !count($members)) {
90
            return true;
91
        }
92
93
        $member = Security::getCurrentUser();
94
        $initiator = $workflow->Initiator();
95
96
        $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...
97
        $memberFields    = $this->getMemberFields($member);
98
        $initiatorFields = $this->getMemberFields($initiator);
99
100
        $variables = [];
101
102
        foreach ($contextFields as $field => $val) {
103
            $variables["\$Context.$field"] = $val;
104
        }
105
        foreach ($memberFields as $field => $val) {
106
            $variables["\$Member.$field"] = $val;
107
        }
108
        foreach ($initiatorFields as $field => $val) {
109
            $variables["\$Initiator.$field"] = $val;
110
        }
111
112
        $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...
113
        $variables["\$CommentHistory"] = $this->customise([
114
            'PastActions' => $pastActions,
115
            'Now' => DBDatetime::now()
116
        ])->renderWith('Includes/CommentHistory');
117
118
        $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...
119
        $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...
120
121
        if ($this->config()->get('whitelist_template_variables')) {
122
            $item = ArrayData::create([
123
                'Initiator' => ArrayData::create($initiatorFields),
124
                'Member' => ArrayData::create($memberFields),
125
                'Context' => ArrayData::create($contextFields),
126
                'CommentHistory' => $variables["\$CommentHistory"]
127
            ]);
128
        } else {
129
            $item = $workflow->customise([
130
                '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...
131
                'Member' => $member,
132
                'Context' => ArrayData::create($contextFields),
133
                'CommentHistory' => $variables["\$CommentHistory"]
134
            ]);
135
        }
136
137
138
        $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...
139
        $this->extend('updateView', $view);
140
141
        foreach ($members as $member) {
142
            if ($member->Email) {
143
                // We bind in the assignee at this point, as it changes each loop iteration
144
                $assigneeVars = $this->getMemberFields($member);
145
                if (count($assigneeVars)) {
146
                    $item->Assignee = ArrayData::create($assigneeVars);
147
                }
148
149
                $body = $view->process($item);
150
151
                $email = Email::create();
152
                try {
153
                    $email->setTo($member->Email);
154
                } catch (Swift_RfcComplianceException $exception) {
155
                    // If the email address isn't valid we should skip it rather than break
156
                    // the rest of the processing
157
                    continue;
158
                }
159
                $email->setSubject($subject);
160
                $email->setFrom($from);
161
                $email->setBody($body);
162
                $email->send();
163
            }
164
        }
165
166
        return true;
167
    }
168
169
    /**
170
     * @param  DataObject $target
171
     * @return array
172
     */
173
    public function getContextFields(DataObject $target)
174
    {
175
        $result = array();
176
        if (!$target) {
177
            return $result;
178
        }
179
180
        $fields = $target->getSchema()->fieldSpecs($target);
181
        unset($fields['ID']);
182
183
        foreach ($fields as $field => $fieldDesc) {
184
            $result[$field] = $target->$field;
185
        }
186
187
        if ($target instanceof CMSPreviewable) {
188
            $result['CMSLink'] = $target->CMSEditLink();
189
        } elseif ($target->hasMethod('WorkflowLink')) {
190
            $result['CMSLink'] = $target->WorkflowLink();
191
        }
192
        $result['AbsoluteEditLink'] = isset($result['CMSLink']) ? $result['CMSLink'] : '';
193
194
        if ($target->hasMethod('AbsoluteLink')) {
195
            $result['AbsoluteLink'] = $target->AbsoluteLink();
196
        }
197
198
        if ($target->hasMethod('LinkToPendingItems')) {
199
            $result['LinkToPendingItems'] = $target->LinkToPendingItems();
200
        }
201
202
        return $result;
203
    }
204
205
    /**
206
     * Builds an array with the member information
207
     * @param Member $member An optional member to use. If null, will use the current logged in member
208
     * @return array
209
     */
210
    public function getMemberFields(Member $member = null)
211
    {
212
        if (!$member) {
213
            $member = Security::getCurrentUser();
214
        }
215
        $result = array();
216
217
        if ($member) {
218
            foreach ($member->summaryFields() as $field => $title) {
219
                $result[$field] = $member->$field;
220
            }
221
        }
222
223
        if ($member && !array_key_exists('Name', $result)) {
224
            $result['Name'] = $member->getName();
225
        }
226
227
        return $result;
228
    }
229
230
231
    /**
232
     * Returns a basic set of instructions on how email templates are populated with variables.
233
     *
234
     * @return string
235
     */
236
    public function getFormattingHelp()
237
    {
238
        $note = _t(
239
            'NotifyUsersWorkflowAction.FORMATTINGNOTE',
240
            'Notification emails can contain HTML formatting. The following special variables are replaced with their
241
			respective values in the email subject, email from and template/body.'
242
        );
243
        $member = _t(
244
            'NotifyUsersWorkflowAction.MEMBERNOTE',
245
            'These fields will be populated from the member that initiates the notification action. For example,
246
			{$Member.FirstName}.'
247
        );
248
        $initiator = _t(
249
            'NotifyUsersWorkflowAction.INITIATORNOTE',
250
            'These fields will be populated from the member that initiates the workflow request. For example,
251
			{$Initiator.Email}.'
252
        );
253
        $context = _t(
254
            'NotifyUsersWorkflowAction.CONTEXTNOTE',
255
            'Any summary fields from the workflow target will be available. For example, {$Context.Title}.
256
			Additionally, the {$Context.AbsoluteEditLink} variable will contain a link to edit the workflow target in
257
            the CMS (if it is a Page), and {$Context.AbsoluteLink} the frontend link. The {$Context.LinkToPendingItems}
258
            variable will generate a link to the CMS workflow admin, useful for allowing users to enact workflow
259
            transitions, directly from emails.'
260
        );
261
        $fieldName = _t('NotifyUsersWorkflowAction.FIELDNAME', 'Field name');
262
        $commentHistory = _t('NotifyUsersWorkflowAction.COMMENTHISTORY', 'Comment history up to this notification.');
263
264
        $memberFields = implode(', ', array_keys($this->getMemberFields()));
265
266
        return "<p>$note</p>
267
			<p><strong>{\$Member.($memberFields)}</strong><br>$member</p>
268
			<p><strong>{\$Initiator.($memberFields)}</strong><br>$initiator</p>
269
			<p><strong>{\$Context.($fieldName)}</strong><br>$context</p>
270
			<p><strong>{\$CommentHistory}</strong><br>$commentHistory</p>";
271
    }
272
}
273