Completed
Push — master ( 7f78e2...8137fc )
by
unknown
01:34
created

EmailReminder_DailyMailOut::startSending()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
4
class EmailReminder_DailyMailOut extends BuildTask
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...
Coding Style introduced by
Expected 0 spaces between "BuildTask" and comma; 1 found
Loading history...
5
    implements EmailReminder_MailOutInterface
0 ignored issues
show
Coding Style introduced by
The implements keyword must be on the same line as the class name
Loading history...
6
{
7
8
9
    /**
10
     * @var int
11
     */
12
    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...
13
14
    /**
15
     * @var string
16
     */
17
    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...
18
19
20
    protected $verbose = false;
21
22
    protected $testOnly = false;
23
24
    /**
25
     * The object that replaces tags in the subject and content.
26
     * @var EmailReinder_ReplacerClassInterface
27
     */
28
    protected $replacerObject = null;
29
30
31
    public function setVerbose($b)
32
    {
33
        $this->verbose = $b;
34
    }
35
36
    public function setTestOnly($b)
37
    {
38
        $this->testOnly = $b;
39
    }
40
41
    /**
42
     *
43
     * @todo: https://docs.silverstripe.org/en/3.1/developer_guides/extending/injector/ implement
44
     * for email class to be used...
45
     *
46
     * expire date = 08-09
47
     * days before 7
48
     * min: current date + 7 - grace days
49
     * min: current date + 7
50
     *
51
     * expire date = 08-09
52
     * days after 7
53
     * min: current date - 7
54
     * max current date - 7 - grace days
55
     *
56
     * @param  SS_Request $request
57
     */
58
    public function run($request)
59
    {
60
        $this->startSending();
61
        $this->runAll();
62
    }
63
64
    protected function startSending()
65
    {
66
        //CRUCIAL !
67
        //
68
        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...
69
    }
70
71
72
    /**
73
     *
74
     * @param  EmailReminder_NotificationSchedule  $reminder
75
     * @param  string|DataObject  $recordOrEmail
76
     * @param  bool $isTestOnly
77
     */
78
    public function runOne($reminder, $recordOrEmail, $isTestOnly = false)
79
    {
80
        $this->startSending();
81
        $this->sendEmail($reminder, $recordOrEmail, $isTestOnly);
82
    }
83
84
    protected function runAll()
85
    {
86
        $reminders = EmailReminder_NotificationSchedule::get();
87
        foreach ($reminders as $reminder) {
88
            if (! $reminder->hasValidFields()) {
89
                continue; // skip if task is not valid
90
            }
91
            if ($reminder->Disabled) {
92
                continue; // skip if task is disable
93
            }
94
95
            // Use StartsWith to match Date and DateTime fields
96
            if ($this->testOnly) {
97
                if ($reminder->SendTestTo) {
98
                    $emails = explode(',', $reminder->SendTestTo);
99
                    foreach ($emails as $key => $email) {
100
                        $this->sendEmail($reminder, $email, $isTestOnly = true);
101
                    }
102
                }
103
            } else {
104
                $limit = Config::inst()->get('EmailReminder_DailyMailOut', 'daily_limit');
105
                $records = $reminder->CurrentRecords();
106
                $records = $records->limit($limit);
107
                if ($records) {
108
                    foreach ($records as $record) {
109
                        $this->sendEmail($reminder, $record, $isTestOnly = false);
110
                    }
111
                }
112
            }
113
        }
114
    }
115
116
117
    protected function sendEmail($reminder, $recordOrEmail, $isTestOnly)
118
    {
119
        $filter = array(
120
            'EmailReminder_NotificationScheduleID' => $reminder->ID,
121
        );
122
        if ($recordOrEmail instanceof DataObject) {
123
            $email_field = $reminder->EmailField;
124
            $email = $recordOrEmail->$email_field;
125
            $record = $recordOrEmail;
126
            $filter['ExternalRecordClassName'] = $recordOrEmail->ClassName;
127
            $filter['ExternalRecordID'] = $recordOrEmail->ID;
128
        } else {
129
            $email = strtolower(trim($recordOrEmail));
130
            $record = Injector::inst()->get($reminder->DataObject);
131
        }
132
        $filter['EmailTo'] = $email;
133
        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...
134
            $send = true;
0 ignored issues
show
Unused Code introduced by
$send is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
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
            if ($send) {
144
                $log = EmailReminder_EmailRecord::create($filter);
145
146
                $subject = $reminder->EmailSubject;
147
                $email_content = $reminder->Content;
148
                if ($replacerObject = $this->getReplacerObject()) {
149
                    $email_content = $replacerObject->replace($reminder, $record, $email_content);
150
                    $subject = $replacerObject->replace($reminder, $record, $subject);
151
                }
152
                $email_content = $this->getParsedContent($record, $email_content);
153
154
                /* Parse HTML like a template, and translate any internal links */
155
                $data = ArrayData::create(array(
156
                    'Content' => $email_content
157
                ));
158
159
                // $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...
160
                // 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...
161
                $email = new Email(
162
                    $reminder->EmailFrom,
163
                    $email,
164
                    $subject
165
                );
166
167
                $email->setTemplate('Email_Reminder_Standard_Template');
168
169
                $email->populateTemplate($data);
170
171
                // $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...
172
                $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...
173
                $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...
174
                $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...
175
                $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...
176
                $log->write();
177
            }
178
        }
179
        return false;
180
    }
181
182
183
    /**
184
     * @return EmailReminder_ReplacerClassInterface | null
185
     */
186
    public function getReplacerObject()
187
    {
188
        if (! $this->replacerObject) {
189
            $replacerClass = Config::inst()->get("EmailReminder_DailyMailOut", "replacer_class");
190
            if ($replacerClass && class_exists($replacerClass)) {
191
                $interfaces = class_implements($replacerClass);
192
                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...
193
                    $this->replacerObject = Injector::inst()->get($replacerClass);
194
                }
195
            }
196
        }
197
        return $this->replacerObject;
198
    }
199
200
201
    /**
202
     *
203
     * @return string
204
     */
205
    public function getParsedContent($record, $content)
206
    {
207
        return ShortcodeParser::get_active()
208
            ->parse(
209
                $record->renderWith(
210
                    SSViewer::fromString($content)
211
                )
212
            );
213
    }
214
}
215