ContactFormSubmission   A
last analyzed

Complexity

Total Complexity 18

Size/Duplication

Total Lines 166
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 82
dl 0
loc 166
rs 10
c 0
b 0
f 0
wmc 18

13 Methods

Rating   Name   Duplication   Size   Complexity  
A find() 0 3 1
A defineSearchableAttributes() 0 3 1
A getCpEditUrl() 0 3 1
A defineActions() 0 11 1
A defineSources() 0 23 2
A isLocalized() 0 3 1
A getIsEditable() 0 3 1
A hasContent() 0 3 1
A defineDefaultTableAttributes() 0 10 1
A defineTableAttributes() 0 13 1
A defineSortOptions() 0 7 1
A getTableAttributeHtml() 0 17 4
A afterSave() 0 26 2
1
<?php
2
/**
3
 * Craft Contact Form Extensions plugin for Craft CMS 3.x.
4
 *
5
 * Adds extensions to the Craft CMS contact form plugin.
6
 *
7
 * @link      https://rias.be
8
 *
9
 * @copyright Copyright (c) 2018 Rias
10
 */
11
12
namespace rias\contactformextensions\elements;
13
14
use Craft;
15
use craft\base\Element;
16
use craft\elements\actions\Delete;
17
use craft\elements\db\ElementQueryInterface;
18
use craft\helpers\StringHelper;
19
use craft\helpers\UrlHelper;
20
use rias\contactformextensions\elements\db\ContactFormSubmissionQuery;
21
22
/**
23
 *  Element.
24
 *
25
 * Element is the base class for classes representing elements in terms of objects.
26
 *
27
 * @property FieldLayout|null      $fieldLayout           The field layout used by this element
28
 * @property array                 $htmlAttributes        Any attributes that should be included in the element’s DOM representation in the Control Panel
29
 * @property int[]                 $supportedSiteIds      The site IDs this element is available in
30
 * @property string|null           $uriFormat             The URI format used to generate this element’s URL
31
 * @property string|null           $url                   The element’s full URL
32
 * @property \Twig_Markup|null     $link                  An anchor pre-filled with this element’s URL and title
33
 * @property string|null           $ref                   The reference string to this element
34
 * @property string                $indexHtml             The element index HTML
35
 * @property bool                  $isEditable            Whether the current user can edit the element
36
 * @property string|null           $cpEditUrl             The element’s CP edit URL
37
 * @property string|null           $thumbUrl              The URL to the element’s thumbnail, if there is one
38
 * @property string|null           $iconUrl               The URL to the element’s icon image, if there is one
39
 * @property string|null           $status                The element’s status
40
 * @property Element               $next                  The next element relative to this one, from a given set of criteria
41
 * @property Element               $prev                  The previous element relative to this one, from a given set of criteria
42
 * @property Element               $parent                The element’s parent
43
 * @property mixed                 $route                 The route that should be used when the element’s URI is requested
44
 * @property int|null              $structureId           The ID of the structure that the element is associated with, if any
45
 * @property ElementQueryInterface $ancestors             The element’s ancestors
46
 * @property ElementQueryInterface $descendants           The element’s descendants
47
 * @property ElementQueryInterface $children              The element’s children
48
 * @property ElementQueryInterface $siblings              All of the element’s siblings
49
 * @property Element               $prevSibling           The element’s previous sibling
50
 * @property Element               $nextSibling           The element’s next sibling
51
 * @property bool                  $hasDescendants        Whether the element has descendants
52
 * @property int                   $totalDescendants      The total number of descendants that the element has
53
 * @property string                $title                 The element’s title
54
 * @property string|null           $serializedFieldValues Array of the element’s serialized custom field values, indexed by their handles
55
 * @property array                 $fieldParamNamespace   The namespace used by custom field params on the request
56
 * @property string                $contentTable          The name of the table this element’s content is stored in
57
 * @property string                $fieldColumnPrefix     The field column prefix this element’s content uses
58
 * @property string                $fieldContext          The field context this element’s content uses
59
 *
60
 * http://pixelandtonic.com/blog/craft-element-types
61
 *
62
 * @author    Rias
63
 *
64
 * @since     1.0.0
65
 */
66
class ContactFormSubmission extends Element
67
{
68
    // Public Properties
69
    // =========================================================================
70
71
    public $form;
72
    public $fromName;
73
    public $fromEmail;
74
    public $subject;
75
    public $message;
76
77
    public static function hasContent(): bool
78
    {
79
        return true;
80
    }
81
82
    public static function isLocalized(): bool
83
    {
84
        return false;
85
    }
86
87
    public static function find(): ElementQueryInterface
88
    {
89
        return new ContactFormSubmissionQuery(static::class);
90
    }
91
92
    protected static function defineSearchableAttributes(): array
93
    {
94
        return ['form', 'subject', 'fromName', 'fromEmail'];
95
    }
96
97
    public function getIsEditable(): bool
98
    {
99
        return true;
100
    }
101
102
    public function getCpEditUrl()
103
    {
104
        return UrlHelper::cpUrl('contact-form-extensions/submissions/'.$this->id);
105
    }
106
107
    protected static function defineSources(string $context = null): array
108
    {
109
        $forms = array_unique(array_map(function (ContactFormSubmission $submission) {
110
            return $submission->form;
111
        }, self::find()->all()));
112
113
        $sources = [
114
            [
115
                'key'      => '*',
116
                'label'    => Craft::t('contact-form-extensions', 'All submissions'),
117
                'criteria' => [],
118
            ],
119
        ];
120
121
        foreach ($forms as $formHandle) {
122
            $sources[] = [
123
                'key'      => $formHandle,
124
                'label'    => ucfirst($formHandle),
125
                'criteria' => ['form' => $formHandle],
126
            ];
127
        }
128
129
        return $sources;
130
    }
131
132
    protected static function defineActions(string $source = null): array
133
    {
134
        $actions = [];
135
136
        $actions[] = Craft::$app->getElements()->createAction([
137
            'type'                => Delete::class,
138
            'confirmationMessage' => Craft::t('app', 'Are you sure you want to delete the selected entries?'),
139
            'successMessage'      => Craft::t('app', 'Entries deleted.'),
140
        ]);
141
142
        return $actions;
143
    }
144
145
    protected static function defineTableAttributes(): array
146
    {
147
        $attributes = [
148
            'id'          => Craft::t('contact-form-extensions', 'ID'),
149
            'form'        => Craft::t('contact-form-extensions', 'Form'),
150
            'subject'     => Craft::t('contact-form-extensions', 'Subject'),
151
            'fromName'    => Craft::t('contact-form-extensions', 'From Name'),
152
            'fromEmail'   => Craft::t('contact-form-extensions', 'From Email'),
153
            'message'     => Craft::t('contact-form-extensions', 'Message'),
154
            'dateCreated' => Craft::t('contact-form-extensions', 'Date Created'),
155
        ];
156
157
        return $attributes;
158
    }
159
160
    protected static function defineDefaultTableAttributes(string $source): array
161
    {
162
        return [
163
            'id',
164
            'form',
165
            'subject',
166
            'fromName',
167
            'fromEmail',
168
            'message',
169
            'dateCreated',
170
        ];
171
    }
172
173
    public function getTableAttributeHtml(string $attribute): string
174
    {
175
        if ($attribute == 'message') {
176
            $message = (array) json_decode($this->message);
177
            $html = '<ul>';
178
            foreach ($message as $key => $value) {
179
                if (is_string($value)) {
180
                    $shortened = trim(substr($value, 0, 30));
181
                    $html .= "<li><em>{$key}</em>: {$shortened}...</li>";
182
                }
183
            }
184
            $html .= '</ul>';
185
186
            return StringHelper::convertToUtf8($html);
187
        }
188
189
        return parent::getTableAttributeHtml($attribute); // TODO: Change the autogenerated stub
190
    }
191
192
    protected static function defineSortOptions(): array
193
    {
194
        $sortOptions = parent::defineSortOptions();
195
196
        unset($sortOptions['dateCreated']);
197
198
        return $sortOptions;
199
    }
200
201
    /**
202
     * @param bool $isNew
203
     *
204
     * @throws \yii\db\Exception
205
     */
206
    public function afterSave(bool $isNew)
207
    {
208
        if ($isNew) {
209
            Craft::$app->db->createCommand()
210
                ->insert('{{%contactform_submissions}}', [
211
                    'id'        => $this->id,
212
                    'form'      => $this->form,
213
                    'subject'   => $this->subject,
214
                    'fromName'  => $this->fromName,
215
                    'fromEmail' => $this->fromEmail,
216
                    'message'   => $this->message,
217
                ])
218
                ->execute();
219
        } else {
220
            Craft::$app->db->createCommand()
221
                ->update('{{%contactform_submissions}}', [
222
                    'form'      => $this->form,
223
                    'subject'   => $this->subject,
224
                    'fromName'  => $this->fromName,
225
                    'fromEmail' => $this->fromEmail,
226
                    'message'   => $this->message,
227
                ], ['id' => $this->id])
228
                ->execute();
229
        }
230
231
        parent::afterSave($isNew);
232
    }
233
}
234