EmailReminder_DailyMailOut   A
last analyzed

Complexity

Total Complexity 29

Size/Duplication

Total Lines 212
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 13

Importance

Changes 0
Metric Value
wmc 29
lcom 1
cbo 13
dl 0
loc 212
rs 10
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A setVerbose() 0 4 1
A setTestOnly() 0 4 1
A run() 0 5 1
A startSending() 0 6 1
A runOne() 0 5 1
B runAll() 0 31 9
B sendEmail() 0 66 8
A getReplacerObject() 0 13 6
A getParsedContent() 0 9 1
1
<?php
2
3
4
class EmailReminder_DailyMailOut extends BuildTask implements EmailReminder_MailOutInterface
5
{
6
7
8
    /**
9
     * @var int
10
     */
11
    private static $limit = 20;
12
13
    /**
14
     * @var string
15
     */
16
    private static $replacer_class = 'EmailReminder_ReplacerClassBase';
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->Disable) {
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));
161
                // echo $record->renderWith('Email_Reminder_Standard_Template');//$email_body;
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();
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