Completed
Push — master ( eb5fdd...29242b )
by Simon
01:46
created

PartialSubmissionJob   A

Complexity

Total Complexity 35

Size/Duplication

Total Lines 262
Duplicated Lines 3.82 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 35
c 3
b 0
f 0
lcom 1
cbo 11
dl 10
loc 262
rs 9

14 Methods

Rating   Name   Duplication   Size   Complexity  
A getTitle() 0 4 1
B process() 0 32 4
B validateEmails() 0 19 5
B getParents() 0 25 5
A buildCSV() 0 16 2
A processSubmissions() 0 19 4
A afterComplete() 0 15 4
A cleanupSubmissions() 0 12 2
A createNewJob() 0 8 1
A getTomorrow() 10 10 1
A getMessages() 0 4 1
A getAddresses() 0 4 1
A addAddress() 0 6 2
A sendEmail() 0 13 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Firesphere\PartialUserforms\Jobs;
4
5
use DateInterval;
6
use DateTime;
7
use DNADesign\ElementalUserForms\Model\ElementForm;
8
use Firesphere\PartialUserforms\Models\PartialFieldSubmission;
9
use Firesphere\PartialUserforms\Models\PartialFormSubmission;
10
use SilverStripe\Control\Email\Email;
11
use SilverStripe\Core\Injector\Injector;
12
use SilverStripe\Dev\Debug;
13
use SilverStripe\ORM\ArrayList;
14
use SilverStripe\ORM\DataList;
15
use SilverStripe\ORM\FieldType\DBDatetime;
16
use SilverStripe\SiteConfig\SiteConfig;
17
use SilverStripe\UserForms\Model\UserDefinedForm;
18
use Symbiote\QueuedJobs\Services\AbstractQueuedJob;
19
use Symbiote\QueuedJobs\Services\QueuedJobService;
20
21
/**
22
 * Class PartialSubmissionJob
23
 * @package Firesphere\PartialUserforms\Jobs
24
 */
25
class PartialSubmissionJob extends AbstractQueuedJob
26
{
27
28
    /**
29
     * The generated CSV files
30
     * @var array
31
     */
32
    protected $files = [];
33
34
    /**
35
     * @var SiteConfig
36
     */
37
    protected $config;
38
39
    /**
40
     * @var array
41
     */
42
    protected $addresses;
43
44
45
    /**
46
     * @return string
47
     */
48
    public function getTitle()
49
    {
50
        return _t(__CLASS__ . '.Title', 'Export partial submissions to Email');
51
    }
52
53
    /**
54
     * Do some processing yourself!
55
     */
56
    public function process()
57
    {
58
        $this->config = SiteConfig::current_site_config();
59
        Debug::dump($this->config);
60
        $this->validateEmails();
61
62
        if (!$this->config->SendDailyEmail ||
63
            !count($this->addresses)
64
        ) {
65
            $this->addMessage(_t(__CLASS__ . '.EmailError', 'Can not process without valid email'));
66
            $this->isComplete = true;
67
68
            return;
69
        }
70
71
        $userDefinedForms = $this->getParents();
72
73
        /** @var UserDefinedForm $form */
74
        foreach ($userDefinedForms as $form) {
75
            $fileName = _t(__CLASS__ . '.Export', 'Export of ') .
76
                $form->Title . ' - ' .
77
                DBDatetime::now()->Format(DBDatetime::ISO_DATETIME);
78
            $file = '/tmp/' . $fileName . '.csv';
79
            $this->files[] = $file;
80
            $this->buildCSV($file, $form);
81
        }
82
83
        $this->sendEmail();
84
85
86
        $this->isComplete = true;
87
    }
88
89
    /**
90
     * Only add valid email addresses
91
     */
92
    protected function validateEmails()
93
    {
94
        $email = $this->config->SendMailTo;
95
        $result = Email::is_valid_address($email);
96
        if ($result) {
97
            $this->addresses[] = $email;
98
        }
99
        if (strpos($email, ',') !== false) {
100
            $emails = explode(',', $email);
101
            foreach ($emails as $address) {
102
                $result = Email::is_valid_address(trim($address));
103
                if ($result) {
104
                    $this->addresses[] = trim($address);
105
                } else {
106
                    $this->addMessage($address . _t(__CLASS__ . '.invalidMail', ' is not a valid email address'));
107
                }
108
            }
109
        }
110
    }
111
112
    /**
113
     * @return ArrayList
114
     */
115
    protected function getParents()
116
    {
117
        /** @var DataList|PartialFormSubmission[] $exportForms */
118
        $allSubmissions = PartialFormSubmission::get()->filter(['IsSend' => false]);
119
        /** @var ArrayList|UserDefinedForm[]|ElementForm[] $parents */
120
        $userDefinedForms = ArrayList::create();
121
122
        /** @var PartialFormSubmission $submission */
123
        /** @noinspection ForeachSourceInspection */
124
        foreach ($allSubmissions as $submission) {
125
            // Due to having to support Elemental ElementForm, we need to manually get the parent
126
            // It's a bit a pickle, but it works
127
            $parentClass = $submission->ParentClass;
128
            $parent = $parentClass::get()->byID($submission->UserDefinedFormID);
129
            if ($parent &&
130
                $parent->ExportPartialSubmissions &&
131
                !$userDefinedForms->find('ID', $parent->ID)
132
            ) {
133
                $userDefinedForms->push($parent);
134
            }
135
            $submission->destroy();
136
        }
137
138
        return $userDefinedForms;
139
    }
140
141
    /**
142
     * @param $file
143
     * @param $form
144
     */
145
    protected function buildCSV($file, $form)
146
    {
147
        $resource = fopen($file, 'w+');
148
        /** @var PartialFormSubmission $submissions */
149
        $submissions = PartialFormSubmission::get()->filter(['UserDefinedFormID' => $form->ID]);
150
        $headerFields = $form
151
            ->Fields()
152
            ->exclude(['Name:PartialMatch' => 'EditableFormStep'])
153
            ->column('Title');
154
        fputcsv($resource, $headerFields);
155
156
        if ($submissions->count()) {
0 ignored issues
show
Documentation Bug introduced by
The method count does not exist on object<Firesphere\Partia...\PartialFormSubmission>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
157
            $this->processSubmissions($form, $submissions, $resource);
158
        }
159
        fclose($resource);
160
    }
161
162
    /**
163
     * @param $form
164
     * @param $submissions
165
     * @param $resource
166
     */
167
    protected function processSubmissions($form, $submissions, $resource)
168
    {
169
        $editableFields = $form->Fields()->map('Name', 'Title')->toArray();
170
        $submitted = [];
171
        foreach ($submissions as $submission) {
172
            $values = $submission->PartialFields()->map('Name', 'Value')->toArray();
173
            $i = 0;
174
            foreach ($editableFields as $field => $title) {
175
                $submitted[] = '';
176
                if (isset($values[$field])) {
177
                    $submitted[] = $values[$field];
178
                }
179
                $i++;
180
            }
181
            fputcsv($resource, $submitted);
182
            $submission->IsSend = true;
183
            $submission->write();
184
        }
185
    }
186
187
    /**
188
     * @throws \Exception
189
     */
190
    public function afterComplete()
191
    {
192
        // Remove the files created in the process
193
        foreach ($this->files as $file) {
194
            unlink($file);
195
        }
196
197
        parent::afterComplete();
198
        if ($this->config->CleanupAfterSend) {
199
            $this->cleanupSubmissions();
200
        }
201
        if ($this->config->SendDailyEmail) {
202
            $this->createNewJob();
203
        }
204
    }
205
206
    /**
207
     * Remove submissions that have been sent out
208
     */
209
    protected function cleanupSubmissions()
210
    {
211
        /** @var DataList|PartialFormSubmission[] $forms */
212
        $forms = PartialFormSubmission::get()->filter(['IsSend' => true]);
213
        foreach ($forms as $form) {
214
            /** @var DataList|PartialFieldSubmission[] $fields */
215
            $fields = PartialFieldSubmission::get()->filter(['ID' => $form->PartialFields()->column('ID')]);
216
            $fields->removeAll();
217
            $form->delete();
218
            $form->destroy();
219
        }
220
    }
221
222
    /**
223
     * Create a new queued job for tomorrow
224
     * @throws \Exception
225
     */
226
    protected function createNewJob()
227
    {
228
        $job = new self();
229
        /** @var QueuedJobService $queuedJob */
230
        $queuedJob = Injector::inst()->get(QueuedJobService::class);
231
        $tomorrow = $this->getTomorrow();
232
        $queuedJob->queueJob($job, $tomorrow);
233
    }
234
235
    /**
236
     * @return DBDatetime|static
237
     * @throws \Exception
238
     */
239 View Code Duplication
    protected function getTomorrow()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
240
    {
241
        $dateTime = new DateTime(DBDatetime::now());
242
        $interval = new DateInterval('P1D');
243
        $tomorrow = $dateTime->add($interval);
244
        $dbDateTime = DBDatetime::create();
245
        $dbDateTime->setValue($tomorrow->format('Y-m-d 00:00:00'));
246
247
        return $dbDateTime;
248
    }
249
250
    /**
251
     * @return array
252
     */
253
    public function getMessages()
254
    {
255
        return $this->messages;
256
    }
257
258
    /**
259
     * @return array
260
     */
261
    public function getAddresses()
262
    {
263
        return $this->addresses;
264
    }
265
266
    public function addAddress($address)
267
    {
268
        if (Email::is_valid_address($address)) {
269
            $this->addresses[] = $address;
270
        }
271
    }
272
273
    protected function sendEmail()
274
    {
275
        /** @var Email $mail */
276
        $mail = Email::create();
277
        $mail->setSubject('Partial form submissions of ' . DBDatetime::now()->Format(DBDatetime::ISO_DATETIME));
278
        foreach ($this->files as $file) {
279
            $mail->addAttachment($file);
280
        }
281
282
        $mail->setFrom('[email protected]');
283
        $mail->setTo($this->addresses);
284
        $mail->setBody('Please see attached CSV files');
285
    }
286
}
287