Completed
Push — master ( 9aaf8b...70bfd9 )
by Simon
01:49
created

PartialSubmissionJob::getMessages()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace Firesphere\PartialUserforms\Jobs;
4
5
use DNADesign\ElementalUserForms\Model\ElementForm;
6
use Firesphere\PartialUserforms\Models\PartialFieldSubmission;
7
use Firesphere\PartialUserforms\Models\PartialFormSubmission;
8
use SilverStripe\Control\Email\Email;
9
use SilverStripe\ORM\ArrayList;
10
use SilverStripe\ORM\DataList;
11
use SilverStripe\ORM\FieldType\DBDatetime;
12
use SilverStripe\SiteConfig\SiteConfig;
13
use SilverStripe\UserForms\Model\UserDefinedForm;
14
use Symbiote\QueuedJobs\Services\AbstractQueuedJob;
15
16
class PartialSubmissionJob extends AbstractQueuedJob
17
{
18
19
    /**
20
     * The generated CSV files
21
     * @var array
22
     */
23
    protected $files = [];
24
25
    protected $config;
26
27
    /**
28
     * @return string
29
     */
30
    public function getTitle()
31
    {
32
        return _t(__CLASS__ . '.Title', 'Export partial submissions to Email');
33
    }
34
35
    /**
36
     * Do some processing yourself!
37
     */
38
    public function process()
39
    {
40
        $this->config = SiteConfig::current_site_config();
41
42
        if (!$this->config->SendDailyEmail || !Email::is_valid_address($this->config->SendEmailTo)) {
43
            $this->addMessage('Can not process without valid email');
44
            return;
45
        }
46
47
        /** @var DataList|PartialFormSubmission[] $exportForms */
48
        $allSubmissions = PartialFormSubmission::get()->filter(['IsSend' => false]);
49
        /** @var ArrayList|UserDefinedForm[]|ElementForm[] $parents */
50
        $userDefinedForms = ArrayList::create();
51
        $this->getParents($allSubmissions, $userDefinedForms);
52
53
        /** @var PartialFormSubmission $form */
54
        foreach ($userDefinedForms as $form) {
55
            $fileName = _t(__CLASS__ . '.Export', 'Export of ') .
56
                $form->Title . ' - ' .
57
                DBDatetime::now()->Format(DBDatetime::ISO_DATETIME);
58
            $file = '/tmp/' . $fileName . '.csv';
59
            $this->files[] = $file;
60
            $this->buildCSV($file, $form);
61
        }
62
63
        /** @var Email $mail */
64
        $mail = Email::create();
65
66
        $mail->setSubject('Partial form submissions of ' . DBDatetime::now()->Format(DBDatetime::ISO_DATETIME));
67
        foreach ($this->files as $file) {
68
            $mail->addAttachment($file);
69
        }
70
        $mail->setTo($this->config->SendMailTo);
71
        $mail->setFrom('[email protected]');
72
        $mail->send();
73
74
        $this->isComplete = true;
75
    }
76
77
    /**
78
     * @param $file
79
     * @param $form
80
     */
81
    protected function buildCSV($file, $form)
82
    {
83
        $resource = fopen($file, 'w+');
84
        /** @var PartialFormSubmission $submissions */
85
        $submissions = PartialFormSubmission::get()->filter(['UserDefinedFormID' => $form->ID]);
86
        $headerFields = $form
87
            ->Fields()
88
            ->exclude(['Name:PartialMatch' => 'EditableFormStep'])
89
            ->column('Title');
90
        fputcsv($resource, $headerFields);
91
92
        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...
93
            $this->processSubmissions($form, $submissions, $resource);
94
        }
95
        fclose($resource);
96
    }
97
98
    /**
99
     * @param $form
100
     * @param $submissions
101
     * @param $submitted
102
     * @param $resource
103
     */
104
    protected function processSubmissions($form, $submissions, $resource)
105
    {
106
        $editableFields = $form->Fields()->map('Name', 'Title')->toArray();
107
        $submitted = [];
108
        $fieldMap = [];
109
        foreach ($submissions as $submission) {
110
            $values = $submission->PartialFields()->map('Name', 'Value')->toArray();
111
            $i = 0;
112
            foreach ($editableFields as $field => $title) {
113
                $submitted[] = '';
114
                $fieldMap[$i]['Name'] = $field;
115
                $fieldMap[$i]['Title'] = $title;
116
                $fieldMap[$i]['ParentClass'] = UserDefinedForm::class;
117
                $fieldMap[$i]['Parent'] = '=>' . UserDefinedForm::class . '.form1';
118
                if (isset($values[$field])) {
119
                    $submitted[] = $values[$field];
120
                }
121
                $i++;
122
            }
123
            fputcsv($resource, $submitted);
124
            $submission->IsSend = true;
125
            $submission->write();
126
        }
127
    }
128
129
    /**
130
     * @param $allSubmissions
131
     * @param $userDefinedForms
132
     */
133
    protected function getParents($allSubmissions, &$userDefinedForms)
134
    {
135
        /** @var PartialFormSubmission $submission */
136
        foreach ($allSubmissions as $submission) {
137
            // Due to having to support Elemental ElementForm, we need to manually get the parent
138
            // It's a bit a pickle, but it works
139
            $parentClass = $submission->ParentClass;
140
            $parent = $parentClass::get()->byID($submission->UserDefinedFormID);
141
            if ($parent &&
142
                $parent->ExportPartialSubmissions &&
143
                !$userDefinedForms->find('ID', $parent->ID)
144
            ) {
145
                $userDefinedForms->push($parent);
146
            }
147
            $submission->destroy();
148
        }
149
    }
150
151
    public function afterComplete()
152
    {
153
        parent::afterComplete();
154
        if ($this->config->CleanupAfterSend) {
155
            /** @var DataList|PartialFormSubmission[] $forms */
156
            $forms = PartialFormSubmission::get()->filter(['IsSend' => true]);
157
            foreach ($forms as $form) {
158
                /** @var DataList|PartialFieldSubmission[] $fields */
159
                $fields = PartialFieldSubmission::get()->filter(['ID' => $form->PartialFields()->column('ID')]);
160
                $fields->removeAll();
161
                $form->delete();
162
                $form->destroy();
163
            }
164
        }
165
//        if ($this->config->)
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
166
    }
167
168
    public function getMessages()
169
    {
170
        return $this->messages;
171
    }
172
}
173