Completed
Push — develop ( 1630dd...e24163 )
by Bob Olde
03:54
created

AuditLogElementType::modifyElementsQuery()   C

Complexity

Conditions 8
Paths 128

Size

Total Lines 55
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 8
Bugs 5 Features 1
Metric Value
c 8
b 5
f 1
dl 0
loc 55
rs 6.6291
cc 8
eloc 25
nc 128
nop 2

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Craft;
4
5
/**
6
 * Audit Log Element Type.
7
 *
8
 * Makes the log behave as an Element Type
9
 *
10
 * @author    Bob Olde Hampsink <[email protected]>
11
 * @copyright Copyright (c) 2015, Bob Olde Hampsink
12
 * @license   MIT
13
 *
14
 * @link      http://github.com/boboldehampsink
15
 */
16
class AuditLogElementType extends BaseElementType
17
{
18
    /**
19
     * The name of the Element Type.
20
     *
21
     * @return string
22
     */
23
    public function getName()
24
    {
25
        return Craft::t('Audit Log');
26
    }
27
28
    /**
29
     * Return true so we have a status select menu.
30
     *
31
     * @return bool
32
     */
33
    public function hasStatuses()
34
    {
35
        return true;
36
    }
37
38
    /**
39
     * Define statuses.
40
     *
41
     * @return array
42
     */
43
    public function getStatuses()
44
    {
45
        return array(
46
            AuditLogModel::CREATED => Craft::t('Created'),
47
            AuditLogModel::MODIFIED => Craft::t('Modified'),
48
            AuditLogModel::DELETED => Craft::t('Deleted'),
49
        );
50
    }
51
52
    /**
53
     * Define available table column names.
54
     *
55
     * @return array
56
     */
57
    public function defineAvailableTableAttributes()
58
    {
59
        // Define default attributes
60
        $attributes = array(
61
            'type' => array('label' => Craft::t('Type')),
62
            'user' => array('label' => Craft::t('User')),
63
            'origin' => array('label' => Craft::t('Origin')),
64
            'dateUpdated' => array('label' => Craft::t('Modified')),
65
        );
66
67
        // Allow plugins to modify the attributes
68
        $pluginAttributes = craft()->plugins->call('defineAdditionalAuditLogTableAttributes', array(), true);
69
        foreach ($pluginAttributes as $thisPluginAttributes) {
70
            $attributes = array_merge($attributes, $thisPluginAttributes);
71
        }
72
73
        // Set changes at last
74
        $attributes['changes'] = array('label' => Craft::t('Changes'));
75
76
        // Return the attributes
77
        return $attributes;
78
    }
79
80
    /**
81
     * Returns the default table attributes.
82
     *
83
     * @param string $source
84
     *
85
     * @return array
86
     */
87
    public function getDefaultTableAttributes($source = null)
88
    {
89
        return array('type', 'user', 'origin', 'dateUpdated', 'changes');
90
    }
91
92
    /**
93
     * Return table attribute html.
94
     *
95
     * @param BaseElementModel $element
96
     * @param string           $attribute
97
     *
98
     * @return string
99
     */
100
    public function getTableAttributeHtml(BaseElementModel $element, $attribute)
101
    {
102
        // First give plugins a chance to set this
103
        $pluginAttributeHtml = craft()->plugins->callFirst('getAuditLogTableAttributeHtml', array($element, $attribute), true);
104
105
        // Check if that had a valid result
106
        if ($pluginAttributeHtml) {
107
            return $pluginAttributeHtml;
108
        }
109
110
        // Modify custom attributes
111
        switch ($attribute) {
112
113
            // Format dates
114
            case 'dateCreated':
115
            case 'dateUpdated':
116
                return craft()->dateFormatter->formatDateTime($element->$attribute);
117
118
            // Return clickable user link
119
            case 'user':
120
                $user = $element->getUser();
121
122
                return $user ? '<a href="'.$user->getCpEditUrl().'">'.$user.'</a>' : Craft::t('Guest');
123
124
            // Return clickable event origin
125
            case 'origin':
126
                return '<a href="'.preg_replace('/'.craft()->config->get('cpTrigger').'\//', '', UrlHelper::getUrl($element->origin), 1).'">'.$element->origin.'</a>';
127
128
            // Return view changes button
129
            case 'changes':
130
                return '<a class="btn" href="'.UrlHelper::getCpUrl('auditlog/'.$element->id).'">'.Craft::t('View').'</a>';
131
132
            // Default behavior
133
            default:
134
                return $element->$attribute;
135
        }
136
    }
137
138
    /**
139
     * Define criteria.
140
     *
141
     * @return array
142
     */
143
    public function defineCriteriaAttributes()
144
    {
145
        return array(
146
            'type' => AttributeType::String,
147
            'userId' => AttributeType::Number,
148
            'origin' => AttributeType::String,
149
            'modified' => AttributeType::DateTime,
150
            'before' => AttributeType::String,
151
            'after' => AttributeType::String,
152
            'status' => AttributeType::String,
153
            'from' => AttributeType::DateTime,
154
            'to' => AttributeType::DateTime,
155
            'order' => array(AttributeType::String, 'default' => 'auditlog.id desc'),
156
        );
157
    }
158
159
    /**
160
     * Cancel the elements query.
161
     *
162
     * @param DbCommand            $query
163
     * @param ElementCriteriaModel $criteria
164
     *
165
     * @return bool
166
     */
167
    public function modifyElementsQuery(DbCommand $query, ElementCriteriaModel $criteria)
168
    {
169
        // Default query
170
        $query
171
            ->select('auditlog.id, auditlog.type, auditlog.userId, auditlog.origin, auditlog.before, auditlog.after, auditlog.status, auditlog.dateCreated, auditlog.dateUpdated')
172
            ->from('auditlog auditlog');
173
174
        // Reset default element type query parts
175
        $query->setJoin('');
176
        $query->setWhere('1=1');
177
        $query->setGroup('');
178
        unset($query->params[':locale']);
179
        unset($query->params[':elementsid1']);
180
181
        // Check for specific id
182
        if (!empty($criteria->id)) {
183
            $query->andWhere(DbHelper::parseParam('auditlog.id', $criteria->id, $query->params));
184
        }
185
186
        // Check type
187
        if (!empty($criteria->type)) {
188
            $query->andWhere(DbHelper::parseParam('auditlog.type', $criteria->type, $query->params));
189
        }
190
191
        // Check user id
192
        if (!empty($criteria->userId)) {
193
            $query->andWhere(DbHelper::parseParam('auditlog.userId', $criteria->userId, $query->params));
194
        }
195
196
        // Check origin
197
        if (!empty($criteria->origin)) {
198
            $query->andWhere(DbHelper::parseParam('auditlog.origin', $criteria->origin, $query->params));
199
        }
200
201
        // Check before
202
        if (!empty($criteria->before)) {
203
            $query->andWhere(DbHelper::parseParam('auditlog.before', $criteria->before, $query->params));
204
        }
205
206
        // Check after
207
        if (!empty($criteria->after)) {
208
            $query->andWhere(DbHelper::parseParam('auditlog.after', $criteria->after, $query->params));
209
        }
210
211
        // Check for status
212
        if (!empty($criteria->status)) {
213
            $query->andWhere(DbHelper::parseParam('auditlog.status', $criteria->status, $query->params));
214
        }
215
216
        // Dates
217
        $this->applyDateCriteria($criteria, $query);
218
219
        // Search
220
        $this->applySearchCriteria($criteria, $query);
221
    }
222
223
    /**
224
     * Apply date criteria.
225
     *
226
     * @param ElementCriteriaModel $search
0 ignored issues
show
Bug introduced by
There is no parameter named $search. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
227
     * @param DbCommand            $query
228
     */
229
    private function applyDateCriteria(ElementCriteriaModel $criteria, DbCommand $query)
230
    {
231
        // Check for date modified
232
        if (!empty($criteria->modified)) {
233
            $query->andWhere(DbHelper::parseDateParam('auditlog.dateUpdated', $criteria->modified, $query->params));
234
        }
235
236
        // Check for date from
237
        if (!empty($criteria->from)) {
238
            $query->andWhere(DbHelper::parseDateParam('auditlog.dateUpdated', '>= '.DateTimeHelper::formatTimeForDb($criteria->from), $query->params));
239
        }
240
241
        // Check for date to
242
        if (!empty($criteria->to)) {
243
            $criteria->to->add(new DateInterval('PT23H59M59S'));
244
            $query->andWhere(DbHelper::parseDateParam('auditlog.dateUpdated', '<= '.DateTimeHelper::formatTimeForDb($criteria->to), $query->params));
245
        }
246
    }
247
248
    /**
249
     * Apply search criteria.
250
     *
251
     * @param ElementCriteriaModel $search
0 ignored issues
show
Bug introduced by
There is no parameter named $search. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
252
     * @param DbCommand            $query
253
     */
254
    private function applySearchCriteria(ElementCriteriaModel $criteria, DbCommand $query)
255
    {
256
        if (!empty($criteria->search)) {
257
258
            // Always perform a LIKE search
259
            $criteria->search = '*'.$criteria->search.'*';
260
261
            // Build conditions
262
            $conditions = array(
263
                'or',
264
                DbHelper::parseParam('auditlog.origin', $criteria->search, $query->params),
265
                DbHelper::parseParam('auditlog.before', $criteria->search, $query->params),
266
                DbHelper::parseParam('auditlog.after', $criteria->search, $query->params),
267
            );
268
269
            // Add to query
270
            $query->andWhere($conditions, $query->params);
271
272
            // Don't perform search logics after this
273
            $criteria->search = null;
274
        }
275
    }
276
277
    /**
278
     * Create element from row.
279
     *
280
     * @param array $row
281
     *
282
     * @return AuditLogModel
283
     */
284
    public function populateElementModel($row)
285
    {
286
        return AuditLogModel::populateModel($row);
287
    }
288
289
    /**
290
     * Define the sources.
291
     *
292
     * @param string $context
293
     */
294
    public function getSources($context = null)
295
    {
296
        // Get plugin settings
297
        $settings = craft()->plugins->getPlugin('AuditLog')->getSettings();
298
299
        // Set default sources
300
        $sources = array(
301
            '*' => array(
302
                'label' => Craft::t('All logs'),
303
            ),
304
            array('heading' => Craft::t('Elements')),
305
        );
306
307
        // Show sources for entries when enabled
308
        if (in_array(ElementType::Entry, $settings->enabled)) {
309
            $sources['entries'] = array(
310
                'label' => Craft::t('Entries'),
311
                'criteria' => array(
312
                    'type' => ElementType::Entry,
313
                ),
314
            );
315
        }
316
317
        // Show sources for categories when enabled
318
        if (in_array(ElementType::Category, $settings->enabled)) {
319
            $sources['categories'] = array(
320
                'label' => Craft::t('Categories'),
321
                'criteria' => array(
322
                    'type' => ElementType::Category,
323
                ),
324
            );
325
        }
326
327
        // Show sources for users when enabled
328
        if (in_array(ElementType::User, $settings->enabled)) {
329
            $sources['users'] = array(
330
                'label' => Craft::t('Users'),
331
                'criteria' => array(
332
                    'type' => ElementType::User,
333
                ),
334
            );
335
        }
336
337
        // Get sources by hook
338
        $plugins = craft()->plugins->call('registerAuditLogSources');
339
        if (count($plugins)) {
340
            $sources[] = array('heading' => Craft::t('Custom'));
341
            foreach ($plugins as $plugin) {
342
343
                // Add as own source
344
                $sources = array_merge($sources, $plugin);
345
            }
346
        }
347
348
        // Return sources
349
        return $sources;
350
    }
351
352
    /**
353
     * Set sortable attributes.
354
     *
355
     * @return array
356
     */
357
    public function defineSortableAttributes()
358
    {
359
        // Set modified first
360
        $attributes = array('dateUpdated' => Craft::t('Modified'));
361
362
        // Get table attributes
363
        $attributes = array_merge($attributes, parent::defineSortableAttributes());
364
365
        // Unset unsortable attributes
366
        unset($attributes['user'], $attributes['changes']);
367
368
        // Allow plugins to modify the attributes
369
        craft()->plugins->call('modifyAuditLogSortableAttributes', array(&$attributes));
370
371
        // Return attributes
372
        return $attributes;
373
    }
374
}
375