Completed
Pull Request — master (#624)
by Sean
16:58
created

UserDefinedForm_EmailRecipient::canCreate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 5

Duplication

Lines 10
Ratio 90.91 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 10
loc 11
ccs 0
cts 5
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
crap 6
1
<?php
2
3
4
/**
5
 * A Form can have multiply members / emails to email the submission
6
 * to and custom subjects
7
 *
8
 * @package userforms
9
 */
10
class UserDefinedForm_EmailRecipient 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...
11
{
12
13
    private static $db = array(
0 ignored issues
show
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...
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
14
        'EmailAddress' => 'Varchar(200)',
15
        'EmailSubject' => 'Varchar(200)',
16
        'EmailFrom' => 'Varchar(200)',
17
        'EmailReplyTo' => 'Varchar(200)',
18
        'EmailBody' => 'Text',
19
        'EmailBodyHtml' => 'HTMLText',
20
        'EmailTemplate' => 'Varchar',
21
        'SendPlain' => 'Boolean',
22
        'HideFormData' => 'Boolean',
23
        'CustomRulesCondition' => 'Enum("And,Or")'
24
    );
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
        'Form' => 'UserDefinedForm',
28
        'SendEmailFromField' => 'EditableFormField',
29
        'SendEmailToField' => 'EditableFormField',
30
        'SendEmailSubjectField' => 'EditableFormField'
31
    );
32
33
    private static $has_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 $has_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...
34
        'CustomRules' => 'UserDefinedForm_EmailRecipientCondition'
35
    );
36
37
    private static $summary_fields = 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 $summary_fields 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
        'EmailAddress',
39
        'EmailSubject',
40
        'EmailFrom'
41
    );
42
43
    /**
44
     * Setting this to true will allow you to select "risky" fields as
45
     * email recipient, such as free-text entry fields.
46
     *
47
     * It's advisable to leave this off.
48
     *
49
     * @config
50
     * @var bool
51
     */
52
    private static $allow_unbound_recipient_fields = false;
0 ignored issues
show
Unused Code introduced by
The property $allow_unbound_recipient_fields 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...
53
54
    public function summaryFields()
55
    {
56
        $fields = parent::summaryFields();
57
        if (isset($fields['EmailAddress'])) {
58
            $fields['EmailAddress'] = _t('UserDefinedForm.EMAILADDRESS', 'Email');
59
        }
60
        if (isset($fields['EmailSubject'])) {
61
            $fields['EmailSubject'] = _t('UserDefinedForm.EMAILSUBJECT', 'Subject');
62
        }
63
        if (isset($fields['EmailFrom'])) {
64
            $fields['EmailFrom'] = _t('UserDefinedForm.EMAILFROM', 'From');
65
        }
66
        return $fields;
67
    }
68
69
    /**
70
     * Get instance of UserDefinedForm when editing in getCMSFields
71
     *
72
     * @return UserDefinedFrom
73
     */
74 1
    protected function getFormParent()
75
    {
76 1
        $formID = $this->FormID
0 ignored issues
show
Documentation introduced by
The property FormID does not exist on object<UserDefinedForm_EmailRecipient>. 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...
77 1
            ? $this->FormID
0 ignored issues
show
Documentation introduced by
The property FormID does not exist on object<UserDefinedForm_EmailRecipient>. 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...
78 1
            : Session::get('CMSMain.currentPage');
79 1
        return UserDefinedForm::get()->byID($formID);
80
    }
81
82
    public function getTitle()
83
    {
84
        if ($this->EmailAddress) {
0 ignored issues
show
Documentation introduced by
The property EmailAddress does not exist on object<UserDefinedForm_EmailRecipient>. 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...
85
            return $this->EmailAddress;
0 ignored issues
show
Documentation introduced by
The property EmailAddress does not exist on object<UserDefinedForm_EmailRecipient>. 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 ($this->EmailSubject) {
0 ignored issues
show
Documentation introduced by
The property EmailSubject does not exist on object<UserDefinedForm_EmailRecipient>. 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...
88
            return $this->EmailSubject;
0 ignored issues
show
Documentation introduced by
The property EmailSubject does not exist on object<UserDefinedForm_EmailRecipient>. 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...
89
        }
90
        return parent::getTitle();
91
    }
92
93
    /**
94
     * Generate a gridfield config for editing filter rules
95
     *
96
     * @return GridFieldConfig
97
     */
98 1
    protected function getRulesConfig()
99
    {
100 1
        $formFields = $this->getFormParent()->Fields();
101
102 1
        $config = GridFieldConfig::create()
103 1
            ->addComponents(
104 1
                new GridFieldButtonRow('before'),
105 1
                new GridFieldToolbarHeader(),
106 1
                new GridFieldAddNewInlineButton(),
107 1
                new GridFieldDeleteAction(),
108 1
                $columns = new GridFieldEditableColumns()
109
            );
110
111 1
        $columns->setDisplayFields(array(
112
            'ConditionFieldID' => function ($record, $column, $grid) use ($formFields) {
0 ignored issues
show
Unused Code introduced by
The parameter $grid 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...
113
                return DropdownField::create($column, false, $formFields->map('ID', 'Title'));
114 1
            },
115 1
            'ConditionOption' => function ($record, $column, $grid) {
0 ignored issues
show
Unused Code introduced by
The parameter $grid 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...
116
                $options = UserDefinedForm_EmailRecipientCondition::config()->condition_options;
117
                return DropdownField::create($column, false, $options);
118 1
            },
119 1
            'ConditionValue' => function ($record, $column, $grid) {
0 ignored issues
show
Unused Code introduced by
The parameter $grid 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...
120
                return TextField::create($column);
121 1
            }
122
        ));
123
124 1
        return $config;
125
    }
126
127
    /**
128
     * @return FieldList
129
     */
130 1
    public function getCMSFields()
131
    {
132 1
        Requirements::javascript(USERFORMS_DIR . '/javascript/Recipient.js');
133
134
        // Determine optional field values
135 1
        $form = $this->getFormParent();
136
137
        // predefined choices are also candidates
138 1
        $multiOptionFields = EditableMultipleOptionField::get()->filter('ParentID', $form->ID);
139
140
        // if they have email fields then we could send from it
141 1
        $validEmailFromFields = EditableEmailField::get()->filter('ParentID', $form->ID);
142
143
        // For the subject, only one-line entry boxes make sense
144 1
        $validSubjectFields = ArrayList::create(
145 1
            EditableTextField::get()
146 1
                ->filter('ParentID', $form->ID)
147 1
                ->exclude('Rows:GreaterThan', 1)
148 1
                ->toArray()
149
        );
150 1
        $validSubjectFields->merge($multiOptionFields);
151
152
153
        // Check valid email-recipient fields
154 1
        if ($this->config()->allow_unbound_recipient_fields) {
155
            // To address can only be email fields or multi option fields
156
            $validEmailToFields = ArrayList::create($validEmailFromFields->toArray());
157
            $validEmailToFields->merge($multiOptionFields);
158
        } else {
159
            // To address cannot be unbound, so restrict to pre-defined lists
160 1
            $validEmailToFields = $multiOptionFields;
161
        }
162
163
        // Build fieldlist
164 1
        $fields = FieldList::create(Tabset::create('Root')->addExtraClass('EmailRecipientForm'));
165
166
        // Configuration fields
167 1
        $fields->addFieldsToTab('Root.EmailDetails', array(
168
            // Subject
169 1
            FieldGroup::create(
170 1
                TextField::create('EmailSubject', _t('UserDefinedForm.TYPESUBJECT', 'Type subject'))
171 1
                    ->setAttribute('style', 'min-width: 400px;'),
172 1
                DropdownField::create(
173 1
                    'SendEmailSubjectFieldID',
174 1
                    _t('UserDefinedForm.SELECTAFIELDTOSETSUBJECT', '.. or select a field to use as the subject'),
175 1
                    $validSubjectFields->map('ID', 'Title')
176 1
                )->setEmptyString('')
177
            )
178 1
                ->setTitle(_t('UserDefinedForm.EMAILSUBJECT', 'Email subject')),
179
180
            // To
181 1
            FieldGroup::create(
182 1
                TextField::create('EmailAddress', _t('UserDefinedForm.TYPETO', 'Type to address'))
183 1
                    ->setAttribute('style', 'min-width: 400px;'),
184 1
                DropdownField::create(
185 1
                    'SendEmailToFieldID',
186 1
                    _t('UserDefinedForm.ORSELECTAFIELDTOUSEASTO', '.. or select a field to use as the to address'),
187 1
                    $validEmailToFields->map('ID', 'Title')
188 1
                )->setEmptyString(' ')
189
            )
190 1
                ->setTitle(_t('UserDefinedForm.SENDEMAILTO', 'Send email to'))
191 1
                ->setDescription(_t(
192 1
                    'UserDefinedForm.SENDEMAILTO_DESCRIPTION',
193 1
                    'You may enter multiple email addresses as a comma separated list.'
194
                )),
195
196
197
            // From
198 1
            TextField::create('EmailFrom', _t('UserDefinedForm.FROMADDRESS', 'Send email from'))
199 1
                ->setDescription(_t(
200 1
                    'UserDefinedForm.EmailFromContent',
201
                    "The from address allows you to set who the email comes from. On most servers this ".
202
                    "will need to be set to an email address on the same domain name as your site. ".
203
                    "For example on yoursite.com the from address may need to be [email protected]. ".
204 1
                    "You can however, set any email address you wish as the reply to address."
205
                )),
206
207
208
            // Reply-To
209 1
            FieldGroup::create(
210 1
                TextField::create('EmailReplyTo', _t('UserDefinedForm.TYPEREPLY', 'Type reply address'))
211 1
                    ->setAttribute('style', 'min-width: 400px;'),
212 1
                DropdownField::create(
213 1
                    'SendEmailFromFieldID',
214 1
                    _t('UserDefinedForm.ORSELECTAFIELDTOUSEASFROM', '.. or select a field to use as reply to address'),
215 1
                    $validEmailFromFields->map('ID', 'Title')
216 1
                )->setEmptyString(' ')
217
            )
218 1
                ->setTitle(_t('UserDefinedForm.REPLYADDRESS', 'Email for reply to'))
219 1
                ->setDescription(_t(
220 1
                    'UserDefinedForm.REPLYADDRESS_DESCRIPTION',
221 1
                    'The email address which the recipient is able to \'reply\' to.'
222
                ))
223
        ));
224
        
225 1
        $fields->fieldByName('Root.EmailDetails')->setTitle(_t('UserDefinedForm_EmailRecipient.EMAILDETAILSTAB', 'Email Details'));
226
227
        // Only show the preview link if the recipient has been saved.
228 1
        if (!empty($this->EmailTemplate)) {
0 ignored issues
show
Documentation introduced by
The property EmailTemplate does not exist on object<UserDefinedForm_EmailRecipient>. 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...
229
            $preview = sprintf(
230
                '<p><a href="%s" target="_blank" class="ss-ui-button">%s</a></p><em>%s</em>',
231
                "admin/pages/edit/EditForm/field/EmailRecipients/item/{$this->ID}/preview",
232
                _t('UserDefinedForm.PREVIEW_EMAIL', 'Preview email'),
233
                _t('UserDefinedForm.PREVIEW_EMAIL_DESCRIPTION', 'Note: Unsaved changes will not appear in the preview.')
234
            );
235
        } else {
236 1
            $preview = sprintf(
237 1
                '<em>%s</em>',
238 1
                _t(
239 1
                    'UserDefinedForm.PREVIEW_EMAIL_UNAVAILABLE',
240 1
                    'You can preview this email once you have saved the Recipient.'
241
                )
242
            );
243
        }
244
245
        // Email templates
246 1
        $fields->addFieldsToTab('Root.EmailContent', array(
247 1
            CheckboxField::create('HideFormData', _t('UserDefinedForm.HIDEFORMDATA', 'Hide form data from email?')),
248 1
            CheckboxField::create(
249 1
                'SendPlain',
250 1
                _t('UserDefinedForm.SENDPLAIN', 'Send email as plain text? (HTML will be stripped)')
251
            ),
252 1
            DropdownField::create(
253 1
                'EmailTemplate',
254 1
                _t('UserDefinedForm.EMAILTEMPLATE', 'Email template'),
255 1
                $this->getEmailTemplateDropdownValues()
256 1
            )->addExtraClass('toggle-html-only'),
257 1
            HTMLEditorField::create('EmailBodyHtml', _t('UserDefinedForm.EMAILBODYHTML', 'Body'))
258 1
                ->addExtraClass('toggle-html-only'),
259 1
            TextareaField::create('EmailBody', _t('UserDefinedForm.EMAILBODY', 'Body'))
260 1
                ->addExtraClass('toggle-plain-only'),
261 1
            LiteralField::create(
262 1
                'EmailPreview',
263 1
                '<div id="EmailPreview" class="field toggle-html-only">' . $preview . '</div>'
264
            )
265
        ));
266
        
267 1
        $fields->fieldByName('Root.EmailContent')->setTitle(_t('UserDefinedForm_EmailRecipient.EMAILCONTENTTAB', 'Email Content'));
268
269
        // Custom rules for sending this field
270 1
        $grid = new GridField(
271 1
            "CustomRules",
272 1
            _t('EditableFormField.CUSTOMRULES', 'Custom Rules'),
273 1
            $this->CustomRules(),
0 ignored issues
show
Documentation Bug introduced by
The method CustomRules does not exist on object<UserDefinedForm_EmailRecipient>? 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...
274 1
            $this->getRulesConfig()
275
        );
276 1
        $grid->setDescription(_t(
277 1
            'UserDefinedForm.RulesDescription',
278 1
            'Emails will only be sent to the recipient if the custom rules are met. If no rules are defined, this receipient will receive notifications for every submission.'
279
        ));
280 1
        $fields->addFieldsToTab('Root.CustomRules', array(
281 1
            new DropdownField(
282 1
                'CustomRulesCondition',
283 1
                _t('UserDefinedForm.SENDIF', 'Send condition'),
284
                array(
285 1
                    'Or' => _t('UserDefinedForm.SENDIFOR', 'Any conditions are true'),
286 1
                    'And' => _t('UserDefinedForm.SENDIFAND', 'All conditions are true')
287
                )
288
            ),
289 1
            $grid
290
        ));
291
        
292 1
        $fields->fieldByName('Root.CustomRules')->setTitle(_t('UserDefinedForm_EmailRecipient.CUSTOMRULESTAB', 'Custom Rules'));
293
294 1
        $this->extend('updateCMSFields', $fields);
295 1
        return $fields;
296
    }
297
298
    /**
299
     * Return whether a user can create an object of this type
300
     *
301
     * @param Member $member
302
     * @param array $context Virtual parameter to allow context to be passed in to check
0 ignored issues
show
Bug introduced by
There is no parameter named $context. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
303
     * @return bool
304
     */
305 View Code Duplication
    public function canCreate($member = null)
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...
306
    {
307
        // Check parent page
308
        $parent = $this->getCanCreateContext(func_get_args());
309
        if ($parent) {
310
            return $parent->canEdit($member);
311
        }
312
313
        // Fall back to secure admin permissions
314
        return parent::canCreate($member);
315
    }
316
317
    /**
318
     * Helper method to check the parent for this object
319
     *
320
     * @param array $args List of arguments passed to canCreate
321
     * @return SiteTree Parent page instance
322
     */
323 View Code Duplication
    protected function getCanCreateContext($args)
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...
324
    {
325
        // Inspect second parameter to canCreate for a 'Parent' context
326
        if (isset($args[1]['Form'])) {
327
            return $args[1]['Form'];
328
        }
329
        // Hack in currently edited page if context is missing
330
        if (Controller::has_curr() && Controller::curr() instanceof CMSMain) {
331
            return Controller::curr()->currentPage();
332
        }
333
334
        // No page being edited
335
        return null;
336
    }
337
338
    /**
339
     * @param Member
340
     *
341
     * @return boolean
342
     */
343
    public function canView($member = null)
344
    {
345
        return $this->Form()->canView($member);
0 ignored issues
show
Documentation Bug introduced by
The method Form does not exist on object<UserDefinedForm_EmailRecipient>? 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...
346
    }
347
348
    /**
349
     * @param Member
350
     *
351
     * @return boolean
352
     */
353 1
    public function canEdit($member = null)
354
    {
355 1
        return $this->Form()->canEdit($member);
0 ignored issues
show
Documentation Bug introduced by
The method Form does not exist on object<UserDefinedForm_EmailRecipient>? 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...
356
    }
357
358
    /**
359
     * @param Member
360
     *
361
     * @return boolean
362
     */
363 1
    public function canDelete($member = null)
364
    {
365 1
        return $this->canEdit($member);
366
    }
367
368
    /*
369
     * Determine if this recipient may receive notifications for this submission
370
     *
371
     * @param array $data
372
     * @param Form $form
373
     * @return bool
374
     */
375 2
    public function canSend($data, $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...
376
    {
377
        // Skip if no rules configured
378 2
        $customRules = $this->CustomRules();
0 ignored issues
show
Documentation Bug introduced by
The method CustomRules does not exist on object<UserDefinedForm_EmailRecipient>? 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...
379 2
        if (!$customRules->count()) {
380 2
            return true;
381
        }
382
383
        // Check all rules
384 1
        $isAnd = $this->CustomRulesCondition === 'And';
0 ignored issues
show
Documentation introduced by
The property CustomRulesCondition does not exist on object<UserDefinedForm_EmailRecipient>. 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...
385 1
        foreach ($customRules as $customRule) {
386
            /** @var UserDefinedForm_EmailRecipientCondition  $customRule */
387 1
            $matches = $customRule->matches($data);
388 1
            if ($isAnd && !$matches) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $matches of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
389 1
                return false;
390
            }
391 1
            if (!$isAnd && $matches) {
392 1
                return true;
393
            }
394
        }
395
396
        // Once all rules are checked
397 1
        return $isAnd;
398
    }
399
400
    /**
401
     * Make sure the email template saved against the recipient exists on the file system.
402
     *
403
     * @param string
404
     *
405
     * @return boolean
406
     */
407 2
    public function emailTemplateExists($template = '')
408
    {
409 2
        $t = ($template ? $template : $this->EmailTemplate);
0 ignored issues
show
Documentation introduced by
The property EmailTemplate does not exist on object<UserDefinedForm_EmailRecipient>. 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...
410
411 2
        return in_array($t, $this->getEmailTemplateDropdownValues());
412
    }
413
414
    /**
415
     * Get the email body for the current email format
416
     *
417
     * @return string
418
     */
419 2
    public function getEmailBodyContent()
420
    {
421 2
        return $this->SendPlain ? $this->EmailBody : $this->EmailBodyHtml;
0 ignored issues
show
Documentation introduced by
The property SendPlain does not exist on object<UserDefinedForm_EmailRecipient>. 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...
Documentation introduced by
The property EmailBody does not exist on object<UserDefinedForm_EmailRecipient>. 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...
Documentation introduced by
The property EmailBodyHtml does not exist on object<UserDefinedForm_EmailRecipient>. 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...
422
    }
423
424
    /**
425
     * Gets a list of email templates suitable for populating the email template dropdown.
426
     *
427
     * @return array
428
     */
429 4
    public function getEmailTemplateDropdownValues()
430
    {
431 4
        $templates = array();
432
433 4
        $finder = new SS_FileFinder();
434 4
        $finder->setOption('name_regex', '/^.*\.ss$/');
435
436 4
        $found = $finder->find(BASE_PATH . '/' . UserDefinedForm::config()->email_template_directory);
437
438 4
        foreach ($found as $key => $value) {
439 4
            $template = pathinfo($value);
440
441 4
            $templates[$template['filename']] = $template['filename'];
442
        }
443
444 4
        return $templates;
445
    }
446
}
447