Passed
Push — master ( 99ec44...efff6a )
by Thomas
02:16
created

EmailTemplatesAdmin::getEmailingById()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace LeKoala\EmailTemplates\Admin;
4
5
use Exception;
6
use SilverStripe\Admin\ModelAdmin;
7
use SilverStripe\Control\Director;
8
use SilverStripe\View\Requirements;
9
use SilverStripe\Control\HTTPResponse;
10
use LeKoala\EmailTemplates\Models\Emailing;
11
use LeKoala\EmailTemplates\Models\SentEmail;
12
use LeKoala\EmailTemplates\Helpers\FluentHelper;
13
use LeKoala\EmailTemplates\Models\EmailTemplate;
14
use SilverStripe\Security\Member;
15
16
/**
17
 * Manage your email templates
18
 *
19
 * @author lekoala
20
 */
21
class EmailTemplatesAdmin extends ModelAdmin
22
{
23
24
    private static $managed_models = array(
0 ignored issues
show
introduced by
The private property $managed_models is not used, and could be removed.
Loading history...
25
        EmailTemplate::class,
26
        SentEmail::class,
27
        Emailing::class,
28
    );
29
    private static $url_segment = 'email-templates';
0 ignored issues
show
introduced by
The private property $url_segment is not used, and could be removed.
Loading history...
30
    private static $menu_title = 'Emails';
0 ignored issues
show
introduced by
The private property $menu_title is not used, and could be removed.
Loading history...
31
    private static $menu_icon = 'lekoala/silverstripe-email-templates:images/mail.png';
0 ignored issues
show
introduced by
The private property $menu_icon is not used, and could be removed.
Loading history...
32
    private static $allowed_actions = array(
0 ignored issues
show
introduced by
The private property $allowed_actions is not used, and could be removed.
Loading history...
33
        'ImportForm',
34
        'SearchForm',
35
        'PreviewEmail',
36
        'PreviewEmailing',
37
        'SendEmailing',
38
        'ViewSentEmail',
39
        'SendTestEmailTemplate',
40
    );
41
42
    public function subsiteCMSShowInMenu()
43
    {
44
        return true;
45
    }
46
47
    public function getList()
48
    {
49
        $list = parent::getList();
50
        return $list;
51
    }
52
53
    /**
54
     * Called by EmailTemplate
55
     *
56
     * @return string
57
     */
58
    public function SendEmailing()
59
    {
60
        $id = (int) $this->getRequest()->getVar('id');
61
62
        /* @var $Emailing Emailing */
63
        $Emailing = self::getEmailingById($id);
64
        $emails = $Emailing->getEmailsByLocales();
65
66
        $errors = 0;
67
        $messages = [];
68
        foreach ($emails as $locale => $emails) {
69
            foreach ($emails as $email) {
70
                $res = null;
71
                $msg = null;
72
                // Wrap with withLocale to make sure any environment variable (urls, etc) are properly set when sending
73
                FluentHelper::withLocale($locale, function () use ($email, &$res, &$msg) {
74
                    try {
75
                        $res = $email->send();
76
                    } catch (Exception $ex) {
77
                        $res = false;
78
                        $msg = $ex->getMessage();
79
                    }
80
                });
81
                if (!$res) {
82
                    $errors++;
83
                    $messages[] = $msg;
84
                }
85
            }
86
        }
87
88
        if ($errors == 0) {
89
            $Emailing->LastSent = date('Y-m-d H:i:s');
0 ignored issues
show
Bug Best Practice introduced by
The property LastSent does not exist on LeKoala\EmailTemplates\Models\Emailing. Since you implemented __set, consider adding a @property annotation.
Loading history...
90
            $Emailing->write();
91
            $message = _t('EmailTemplatesAdmin.EMAILING_SENT', 'Emailing sent');
92
        } else {
93
            $message =  _t('EmailTemplatesAdmin.EMAILING_ERROR', 'There was an error sending email');
94
            $message .= ": " . implode(", ", $messages);
95
        }
96
97
        if (Director::is_ajax()) {
98
            $this->getResponse()->addHeader('X-Status', rawurlencode($message));
99
            if ($errors > 0) {
100
                // $this->getResponse()->setStatusCode(400);
101
            }
102
            return $this->getResponse();
103
        }
104
105
        return $message;
106
    }
107
108
    /**
109
     * Called by EmailTemplate::previewTab
110
     *
111
     * @return string
112
     */
113
    public function PreviewEmail()
114
    {
115
        // Prevent CMS styles to interfere with preview
116
        Requirements::clear();
117
118
        $id = (int) $this->getRequest()->getVar('id');
119
120
        $EmailTemplate = self::getEmailTemplateById($id);
121
        $html = $EmailTemplate->renderTemplate(true);
122
123
        Requirements::restore();
124
125
        return $html;
126
    }
127
128
    /**
129
     * Called by Emailing::previewTab
130
     *
131
     * @return string
132
     */
133
    public function PreviewEmailing()
134
    {
135
        // Prevent CMS styles to interfere with preview
136
        Requirements::clear();
137
138
        $id = (int) $this->getRequest()->getVar('id');
139
140
        $Emailing = self::getEmailingById($id);
141
        $html = $Emailing->renderTemplate(true);
0 ignored issues
show
Unused Code introduced by
The call to LeKoala\EmailTemplates\M...iling::renderTemplate() has too many arguments starting with true. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

141
        /** @scrutinizer ignore-call */ 
142
        $html = $Emailing->renderTemplate(true);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
142
143
        Requirements::restore();
144
145
        return $html;
146
    }
147
148
    public function SendTestEmailTemplate()
149
    {
150
        $id = (int) $this->getRequest()->getVar('id');
151
        $to = (string) $this->getRequest()->getVar('to');
152
153
        if (!$to) {
154
            die("Please set a [email protected]");
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
155
        }
156
157
        $member = Member::get()->filter('Email', $to)->first();
158
159
        $emailTemplate = self::getEmailTemplateById($id);
160
161
        $email = $emailTemplate->getEmail();
162
163
        d($email);
0 ignored issues
show
Bug introduced by
The function d was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

163
        /** @scrutinizer ignore-call */ 
164
        d($email);
Loading history...
164
        $emailTemplate->setPreviewData($email);
165
        if ($member) {
0 ignored issues
show
introduced by
$member is of type SilverStripe\ORM\DataObject, thus it always evaluated to true.
Loading history...
166
            $email->setToMember($member);
167
            $email->addData("Member", $member);
168
        } else {
169
            $email->setTo($to);
170
        }
171
        $result = $email->send();
172
173
        print_r($result);
174
        die();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
175
    }
176
177
    /**
178
     * Called by SentEmail
179
     *
180
     * @return string
181
     */
182
    public function ViewSentEmail()
183
    {
184
        // Prevent CMS styles to interfere with preview
185
        Requirements::clear();
186
187
        $id = (int) $this->getRequest()->getVar('id');
188
189
        $SentEmail = self::getSentEmailById($id);
190
        $html = $SentEmail->Body;
0 ignored issues
show
Bug Best Practice introduced by
The property Body does not exist on LeKoala\EmailTemplates\Models\EmailTemplate. Since you implemented __get, consider adding a @property annotation.
Loading history...
191
192
        Requirements::restore();
193
194
        return $html;
195
    }
196
197
    /**
198
     * @param int $id
199
     * @return Emailing
200
     */
201
    protected static function getEmailingById($id)
202
    {
203
        return Emailing::get()->byID($id);
204
    }
205
206
    /**
207
     * @param int $id
208
     * @return EmailTemplate
209
     */
210
    protected static function getEmailTemplateById($id)
211
    {
212
        return EmailTemplate::get()->byID($id);
213
    }
214
215
    /**
216
     * @param int $id
217
     * @return EmailTemplate
218
     */
219
    protected static function getSentEmailById($id)
220
    {
221
        return SentEmail::get()->byID($id);
222
    }
223
}
224