GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

YouTubeFieldType::getSettingsHtml()   B
last analyzed

Complexity

Conditions 4
Paths 6

Size

Total Lines 29
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 29
rs 8.5806
cc 4
eloc 17
nc 6
nop 0
1
<?php
2
3
namespace Craft;
4
5
/**
6
 * YouTube FieldType.
7
 *
8
 * Upload video assets to YouTube.
9
 *
10
 * @author    Bob Olde Hampsink <[email protected]>
11
 * @copyright Copyright (c) 2015, Itmundi
12
 * @license   MIT
13
 *
14
 * @link      http://github.com/boboldehampsink
15
 */
16
class YouTubeFieldType extends AssetsFieldType
17
{
18
    /**
19
     * The actual attribute we're working with.
20
     *
21
     * @var mixed
22
     */
23
    protected $attribute;
24
25
    /**
26
     * Holds changed element id's.
27
     *
28
     * @var array
29
     */
30
    protected $elementIds = array();
31
32
    /**
33
     * Get fieldtype name.
34
     *
35
     * @return string
36
     */
37
    public function getName()
38
    {
39
        return Craft::t('YouTube Upload');
40
    }
41
42
    /**
43
     * We're going to save an array of YouTube Video settings.
44
     *
45
     * @return mixed
46
     */
47
    public function defineContentAttribute()
48
    {
49
        return AttributeType::Mixed;
50
    }
51
52
    /**
53
     * Override default asset settings - leaving fileKinds out.
54
     *
55
     * @return string|null
56
     */
57
    public function getSettingsHtml()
58
    {
59
        // Create a list of folder options for the main Source setting, and source options for the upload location
60
        // settings.
61
        $folderOptions = array();
62
        $sourceOptions = array();
63
64
        foreach ($this->getElementType()->getSources() as $key => $source) {
65
            if (!isset($source['heading'])) {
66
                $folderOptions[] = array('label' => $source['label'], 'value' => $key);
67
            }
68
        }
69
70
        foreach (craft()->assetSources->getAllSources() as $source) {
71
            $sourceOptions[] = array('label' => $source->name, 'value' => $source->id);
72
        }
73
74
        $namespace = craft()->templates->getNamespace();
75
        $isMatrix = (strncmp($namespace, 'types[Matrix][blockTypes][', 26) === 0);
76
77
        return craft()->templates->render('youtube/settings/_fieldtype', array(
78
            'folderOptions'     => $folderOptions,
79
            'sourceOptions'     => $sourceOptions,
80
            'targetLocaleField' => $this->getTargetLocaleFieldHtml(),
81
            'settings'          => $this->getSettings(),
82
            'type'              => $this->getName(),
83
            'isMatrix'          => $isMatrix,
84
        ));
85
    }
86
87
    /**
88
     * Return criteria in back-end and YT ID(s) in front-end.
89
     *
90
     * @param mixed $value
91
     *
92
     * @return ElementCriteriaModel|array
93
     */
94
    public function prepValue($value)
95
    {
96
        // Behave as normal asset in back-end
97
        if (craft()->request->isCpRequest()) {
98
99
            // Overwrite value, if any
100
            if ($value) {
101
102
                // Fetch target id(s)
103
                $results = craft()->db->createCommand()
104
                                    ->select('targetId')
105
                                    ->from('relations')
106
                                    ->where(array(
107
                                        'fieldId'  => $this->model->id,
108
                                        'sourceId' => $this->element->id,
109
                                    ))
110
                                    ->queryAll();
111
112
                // If db result is valid
113
                if ($results && is_array($results)) {
114
115
                    // Gather value
116
                    $value = array();
117
118
                    // Loop through target ids
119
                    foreach ($results as $result) {
120
                        $value[] = $result['targetId'];
121
                    }
122
                } else {
123
124
                    // Else return nothing
125
                    $value = null;
126
                }
127
            }
128
129
            // Return with new values
130
            return parent::prepValue($value);
131
        }
132
133
        // Value is always an array
134
        if (!is_array($value)) {
135
            $value = array();
136
        }
137
138
        // Prepare for models
139
        $videos = array();
140
        foreach ($value as $id) {
141
            $videos[] = array('id' => $id);
142
        }
143
144
        // Return video models
145
        return YouTube_VideoModel::populateModels($videos);
146
    }
147
148
    /**
149
     * Ignore prepping value from post basically.
150
     *
151
     * @param mixed $value
152
     *
153
     * @return ElementCriteriaModel
154
     */
155
    public function prepValueFromPost($value)
156
    {
157
        // Check if anything has changed or emptied
158
        if ($this->hasChanged() || empty($value)) {
159
160
            // Yes! Prep value from post
161
            return parent::prepValueFromPost($value);
162
        }
163
164
        // Nope, just return the same 'old
165
        return $this->element->getContent()->getAttribute($this->model->handle);
166
    }
167
168
    /**
169
     * Get search keywords.
170
     *
171
     * @param ElementCriteriaModel|array $criteria
172
     *
173
     * @return array
174
     */
175
    public function getSearchKeywords($criteria)
176
    {
177
        // Behave normally in cp
178
        if (craft()->request->isCpRequest()) {
179
            return parent::getSearchKeywords($criteria);
180
        }
181
182
        // Or parse youtube video models
183
        $titles = array();
184
        foreach ($criteria as $element) {
185
            $titles[] = (string) $element;
186
        }
187
188
        return BaseFieldType::getSearchKeywords($titles);
189
    }
190
191
    /**
192
     * Send video off to YouTube after saving.
193
     */
194
    public function onAfterElementSave()
195
    {
196
        // Proceed when there's something new
197
        if ($this->hasChanged()) {
198
199
            // Let AssetsFieldType handle the default upload logics
200
            parent::onAfterElementSave();
201
202
            // Get logged-in user
203
            $user = craft()->userSession->getUser();
204
205
            // Now its our turn
206
            craft()->tasks->createTask('YouTube_Upload', Craft::t('Uploading video(s) to YouTube'), array(
207
                'id'     => $this->element->id,
208
                'model'  => $this->model,
209
                'assets' => $this->elementIds,
210
                'user'   => $user->id,
211
            ));
212
213
        // Or proceed if we have to remove the relations
214
        } elseif (!$this->attribute->total()) {
215
216
            // Let AssetsFieldType handle the removal of upload/relations
217
            parent::onAfterElementSave();
218
        }
219
    }
220
221
    // Protected
222
    // =========================================================================
223
224
    /**
225
     * Let users know we're uploading a video.
226
     *
227
     * @return string
228
     */
229
    protected function getAddButtonLabel()
230
    {
231
        return Craft::t('Add a video');
232
    }
233
234
    /**
235
     * Limit filekinds to video only.
236
     *
237
     * @return array
238
     */
239
    protected function defineSettings()
240
    {
241
        return array_merge(parent::defineSettings(), array(
242
            'restrictFiles' => array(AttributeType::Bool, 'default' => true),
243
            'allowedKinds'  => array(AttributeType::Mixed, 'default' => array('video')),
244
        ));
245
    }
246
247
    /**
248
     * Check if the video field has really changed, to prevent unneeded YouTube API calls.
249
     *
250
     * @return bool
251
     */
252
    protected function hasChanged()
253
    {
254
        // Get raw post data
255
        $posted = $this->element->getContentFromPost();
256
257
        // Get handle and attribute
258
        $handle = $this->model->handle;
259
        $this->attribute = $this->element->{$handle};
260
261
        // Check if they're actually set
262
        if ($this->attribute instanceof ElementCriteriaModel && isset($posted[$handle]) && is_array($posted[$handle])) {
263
264
            // Only get new element id's
265
            $this->elementIds = array_values(array_diff($posted[$handle], $this->attribute->ids()));
266
267
            // Proceed when there's something new
268
            return (bool) count($this->elementIds);
269
        }
270
271
        // Not set, not changed
272
        return false;
273
    }
274
}
275