Passed
Pull Request — master (#47)
by Rafael
04:41
created

EmailTemplatesController::copy()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 33
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 4.0629

Importance

Changes 0
Metric Value
cc 4
eloc 19
nc 6
nop 1
dl 0
loc 33
ccs 16
cts 19
cp 0.8421
crap 4.0629
rs 9.6333
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gewaer\Api\Controllers;
6
7
use Gewaer\Models\EmailTemplates;
8
use Gewaer\Models\Users;
9
use Gewaer\Exception\NotFoundHttpException;
10
use Gewaer\Exception\UnprocessableEntityHttpException;
11
use Phalcon\Security\Random;
12
use Phalcon\Http\Response;
13
14
/**
15
 * Class LanguagesController
16
 *
17
 * @package Gewaer\Api\Controllers
18
 *
19
 * @property Users $userData
20
 * @property Request $request
21
 * @property Config $config
22
 * @property \Baka\Mail\Message $mail
23
 * @property Apps $app
24
 *
25
 */
26
class EmailTemplatesController extends BaseController
27
{
28
    /*
29
     * fields we accept to create
30
     *
31
     * @var array
32
     */
33
    protected $createFields = ['users_id', 'companies_id', 'apps_id', 'name', 'template'];
34
35
    /*
36
     * fields we accept to create
37
     *
38
     * @var array
39
     */
40
    protected $updateFields = ['users_id', 'companies_id', 'apps_id', 'name', 'template'];
41
42
    /**
43
     * set objects
44
     *
45
     * @return void
46
     */
47 2
    public function onConstruct()
48
    {
49 2
        $this->model = new EmailTemplates();
50 2
        $this->additionalSearchFields = [
51 2
            ['is_deleted', ':', '0'],
52 2
            ['companies_id', ':', '0|' . $this->userData->currentCompanyId()],
53
        ];
54 2
    }
55
56
    /**
57
     * Add a new by copying a specific email template based on
58
     *
59
     * @method POST
60
     * @url /v1/data
61
     * @param integer $id
62
     * @return \Phalcon\Http\Response
63
     */
64 1
    public function copy(int $id): Response
65
    {
66 1
        $request = $this->request->getPost();
67
68 1
        if (empty($request)) {
69
            $request = $this->request->getJsonRawBody(true);
70
        }
71
72
        //Find email template based on the basic parameters
73 1
        $existingEmailTemplate = $this->model::findFirst([
74 1
            'conditions' => 'id = ?0 and companies_id in (?1,?2) and apps_id in (?3,?4) and is_deleted = 0',
75 1
            'bind' => [$id, $this->userData->currentCompanyId(), 0, $this->app->getId(), 0]
76
        ]);
77
78 1
        if (!is_object($existingEmailTemplate)) {
79
            throw new NotFoundHttpException('Email Template not found');
80
        }
81
82 1
        $random = new Random();
83 1
        $randomInstance = $random->base58();
84
85 1
        $request['users_id'] = $existingEmailTemplate->users_id;
86 1
        $request['companies_id'] = $this->userData->currentCompanyId();
87 1
        $request['apps_id'] = $this->app->getId();
88 1
        $request['name'] = $existingEmailTemplate->name . '-' . $randomInstance;
89 1
        $request['template'] = $existingEmailTemplate->template;
90
91
        //try to save all the fields we allow
92 1
        if ($this->model->save($request, $this->createFields)) {
93 1
            return $this->response($this->model->toArray());
94
        } else {
95
            //if not thorw exception
96
            throw new UnprocessableEntityHttpException((string) current($this->model->getMessages()));
97
        }
98
    }
99
100
    /**
101
     * Send test email to specific recipient
102
     * @param string $email
103
     * @return Response
104
     */
105
    public function sendTestEmail(): Response
106
    {
107
        $request = $this->request->getPost();
108
109
        if (empty($request)) {
110
            $request = $this->request->getJsonRawBody(true);
111
        }
112
113
        $emailRecipients = explode(',', $request['emails']);
114
115
        foreach ($emailRecipients as $emailRecipient) {
116
            $userExists = Users::findFirst([
117
                'conditions' => 'email = ?0 and is_deleted = 0',
118
                'bind' => [$emailRecipient]
119
            ]);
120
121
            if (!is_object($userExists)) {
122
                throw new NotFoundHttpException('Email recipient not found');
123
            }
124
125
            $subject = _('Test Email Template');
126
            $this->mail
127
                ->to((string)$userExists->email)
128
                ->subject($subject)
129
                ->content($request['template'])
130
                ->sendNow();
131
        }
132
133
        return $this->response('Test email sent');
134
    }
135
}
136