Completed
Push — master ( a77c75...bc53bd )
by
unknown
01:34
created

EmailReminder_DailyMailOut::sendEmail()   C

Complexity

Conditions 8
Paths 26

Size

Total Lines 66
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 66
rs 6.7081
c 0
b 0
f 0
cc 8
eloc 44
nc 26
nop 4

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
4
class EmailReminder_DailyMailOut extends BuildTask implements EmailReminder_MailOutInterface
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...
5
{
6
7
8
    /**
9
     * @var int
10
     */
11
    private static $limit = 20;
0 ignored issues
show
Unused Code introduced by
The property $limit 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...
12
13
    /**
14
     * @var string
15
     */
16
    private static $replacer_class = 'EmailReminder_ReplacerClassBase';
0 ignored issues
show
Unused Code introduced by
The property $replacer_class 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
18
19
    protected $verbose = false;
20
21
    protected $testOnly = false;
22
23
    /**
24
     * The object that replaces tags in the subject and content.
25
     * @var EmailReinder_ReplacerClassInterface
26
     */
27
    protected $replacerObject = null;
28
29
30
    public function setVerbose($b)
31
    {
32
        $this->verbose = $b;
33
    }
34
35
    public function setTestOnly($b)
36
    {
37
        $this->testOnly = $b;
38
    }
39
40
    /**
41
     *
42
     * @todo: https://docs.silverstripe.org/en/3.1/developer_guides/extending/injector/ implement
43
     * for email class to be used...
44
     *
45
     * expire date = 08-09
46
     * days before 7
47
     * min: current date + 7 - grace days
48
     * min: current date + 7
49
     *
50
     * expire date = 08-09
51
     * days after 7
52
     * min: current date - 7
53
     * max current date - 7 - grace days
54
     *
55
     * @param  SS_Request $request
56
     */
57
    public function run($request)
58
    {
59
        $this->startSending();
60
        $this->runAll();
61
    }
62
63
    protected function startSending()
64
    {
65
        //CRUCIAL !
66
        //
67
        Email::set_mailer(new EmailReminder_Mailer());
0 ignored issues
show
Deprecated Code introduced by
The method Email::set_mailer() has been deprecated with message: since version 4.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
68
    }
69
70
71
    /**
72
     *
73
     * @param  EmailReminder_NotificationSchedule  $reminder
74
     * @param  string|DataObject  $recordOrEmail
75
     * @param  bool $isTestOnly
76
     */
77
    public function runOne($reminder, $recordOrEmail, $isTestOnly = false, $force = false)
78
    {
79
        $this->startSending();
80
        $this->sendEmail($reminder, $recordOrEmail, $isTestOnly, $force);
81
    }
82
83
    protected function runAll()
84
    {
85
        $reminders = EmailReminder_NotificationSchedule::get();
86
        foreach ($reminders as $reminder) {
87
            if (! $reminder->hasValidFields()) {
88
                continue; // skip if task is not valid
89
            }
90
            if ($reminder->Disabled) {
91
                continue; // skip if task is disable
92
            }
93
94
            // Use StartsWith to match Date and DateTime fields
95
            if ($this->testOnly) {
96
                if ($reminder->SendTestTo) {
97
                    $emails = explode(',', $reminder->SendTestTo);
98
                    foreach ($emails as $key => $email) {
99
                        $this->sendEmail($reminder, $email, $isTestOnly = true);
100
                    }
101
                }
102
            } else {
103
                $limit = Config::inst()->get('EmailReminder_DailyMailOut', 'daily_limit');
104
                $records = $reminder->CurrentRecords();
105
                $records = $records->limit($limit);
106
                if ($records) {
107
                    foreach ($records as $record) {
108
                        $this->sendEmail($reminder, $record, $isTestOnly = false);
109
                    }
110
                }
111
            }
112
        }
113
    }
114
115
116
    protected function sendEmail($reminder, $recordOrEmail, $isTestOnly, $force = false)
117
    {
118
        $filter = array(
119
            'EmailReminder_NotificationScheduleID' => $reminder->ID,
120
        );
121
        if ($recordOrEmail instanceof DataObject) {
122
            $email_field = $reminder->EmailField;
123
            $email = $recordOrEmail->$email_field;
124
            $record = $recordOrEmail;
125
            $filter['ExternalRecordClassName'] = $recordOrEmail->ClassName;
126
            $filter['ExternalRecordID'] = $recordOrEmail->ID;
127
        } else {
128
            $email = strtolower(trim($recordOrEmail));
129
            $record = Injector::inst()->get($reminder->DataObject);
130
        }
131
        $filter['EmailTo'] = $email;
132
        if (Email::validEmailAddress($email)) {
0 ignored issues
show
Deprecated Code introduced by
The method Email::validEmailAddress() has been deprecated with message: 4.0 Use the "is_valid_address" method instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
133
            $send = true;
134
            if(! $force){
135
                $logs = EmailReminder_EmailRecord::get()->filter($filter);
136
                $send = true;
137
                foreach ($logs as $log) {
138
                    if (! $log->canSendAgain()) {
139
                        $send = false;
140
                        break;
141
                    }
142
                }
143
            }
144
            if ($send) {
145
                $log = EmailReminder_EmailRecord::create($filter);
146
147
                $subject = $reminder->EmailSubject;
148
                $email_content = $reminder->Content;
149
                if ($replacerObject = $this->getReplacerObject()) {
150
                    $email_content = $replacerObject->replace($reminder, $record, $email_content);
151
                    $subject = $replacerObject->replace($reminder, $record, $subject);
152
                }
153
                $email_content = $this->getParsedContent($record, $email_content);
154
155
                /* Parse HTML like a template, and translate any internal links */
156
                $data = ArrayData::create(array(
157
                    'Content' => $email_content
158
                ));
159
160
                // $email_body = $record->renderWith(SSViewer::fromString($reminder->Content));
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
161
                // echo $record->renderWith('Email_Reminder_Standard_Template');//$email_body;
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
162
                $email = new Email(
163
                    $reminder->EmailFrom,
164
                    $email,
165
                    $subject
166
                );
167
168
                $email->setTemplate('Email_Reminder_Standard_Template');
169
170
                $email->populateTemplate($data);
171
172
                // $email->send();
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
173
                $log->IsTestOnly = $isTestOnly;
0 ignored issues
show
Documentation introduced by
The property IsTestOnly does not exist on object<EmailReminder_EmailRecord>. Since you implemented __set, maybe consider adding a @property annotation.

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

<?php

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

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

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

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

}

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

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

See also the PhpDoc documentation for @property.

Loading history...
174
                $log->Result = $email->send();
0 ignored issues
show
Documentation introduced by
The property Result does not exist on object<EmailReminder_EmailRecord>. Since you implemented __set, maybe consider adding a @property annotation.

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

<?php

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

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

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

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

}

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

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

See also the PhpDoc documentation for @property.

Loading history...
175
                $log->EmailReminder_NotificationScheduleID = $reminder->ID;
0 ignored issues
show
Documentation introduced by
The property EmailReminder_NotificationScheduleID does not exist on object<EmailReminder_EmailRecord>. Since you implemented __set, maybe consider adding a @property annotation.

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

<?php

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

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

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

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

}

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

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

See also the PhpDoc documentation for @property.

Loading history...
176
                $log->EmailContent = $email->body;
0 ignored issues
show
Documentation introduced by
The property EmailContent does not exist on object<EmailReminder_EmailRecord>. Since you implemented __set, maybe consider adding a @property annotation.

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

<?php

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

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

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

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

}

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

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

See also the PhpDoc documentation for @property.

Loading history...
177
                $log->write();
178
            }
179
        }
180
        return false;
181
    }
182
183
184
    /**
185
     * @return EmailReminder_ReplacerClassInterface | null
186
     */
187
    public function getReplacerObject()
188
    {
189
        if (! $this->replacerObject) {
190
            $replacerClass = Config::inst()->get("EmailReminder_DailyMailOut", "replacer_class");
191
            if ($replacerClass && class_exists($replacerClass)) {
192
                $interfaces = class_implements($replacerClass);
193
                if ($interfaces && in_array('EmailReminder_ReplacerClassInterface', $interfaces)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $interfaces of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
194
                    $this->replacerObject = Injector::inst()->get($replacerClass);
195
                }
196
            }
197
        }
198
        return $this->replacerObject;
199
    }
200
201
202
    /**
203
     *
204
     * @return string
205
     */
206
    public function getParsedContent($record, $content)
207
    {
208
        return ShortcodeParser::get_active()
209
            ->parse(
210
                $record->renderWith(
211
                    SSViewer::fromString($content)
212
                )
213
            );
214
    }
215
}
216