Completed
Push — develop ( d7ed2f...d8dd03 )
by Benjamin
17s queued 12s
created

Video::getInputHtml()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 39
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 7
Bugs 0 Features 0
Metric Value
cc 4
eloc 21
c 7
b 0
f 0
nc 4
nop 2
dl 0
loc 39
rs 9.584
1
<?php
2
/**
3
 * @link https://dukt.net/videos/
4
 *
5
 * @copyright Copyright (c) 2021, Dukt
6
 * @license https://github.com/dukt/videos/blob/v2/LICENSE.md
7
 */
8
9
namespace dukt\videos\fields;
10
11
use Craft;
12
use craft\base\ElementInterface;
13
use craft\base\Field;
14
use craft\helpers\Db;
15
use craft\helpers\StringHelper;
16
use dukt\videos\models\VideoError;
17
use dukt\videos\Plugin as Videos;
18
use dukt\videos\web\assets\videofield\VideoFieldAsset;
19
20
/**
21
 * Video field.
22
 */
23
class Video extends Field
24
{
25
    // Public Methods
26
    // =========================================================================
27
28
    /**
29
     * Get the field’s name.
30
     *
31
     * @return string
32
     */
33
    public function getName(): string
34
    {
35
        return Craft::t('videos', 'Videos');
36
    }
37
38
    /**
39
     * Get Input HTML.
40
     *
41
     * @param                       $value
42
     * @param null|ElementInterface $element
43
     *
44
     * @return string
45
     *
46
     * @throws \Twig_Error_Loader
47
     * @throws \yii\base\Exception
48
     * @throws \yii\base\InvalidConfigException
49
     */
50
    public function getInputHtml($value, ElementInterface $element = null): string
51
    {
52
        $view = Craft::$app->getView();
53
        $name = $this->handle;
54
55
        // Reformat the input name into something that looks more like an ID
56
        $id = $view->formatInputId($name);
57
58
        // Init CSRF Token
59
        $jsTemplate = 'window.csrfTokenName = "'.Craft::$app->getConfig()->getGeneral()->csrfTokenName.'";';
60
        $jsTemplate .= 'window.csrfTokenValue = "'.Craft::$app->getRequest()->getCsrfToken().'";';
61
        $js = $view->renderString($jsTemplate);
62
        $view->registerJs($js);
63
64
        // Asset bundle
65
        $view->registerAssetBundle(VideoFieldAsset::class);
66
67
        // Preview
68
        $preview = $view->renderTemplate('videos/_elements/fieldPreview', ['video' => $value]);
69
70
        // Has gateways
71
        $gateways = Videos::$plugin->getGateways()->getGateways();
72
        $hasGateways = false;
73
74
        if ($gateways && count($gateways) > 0) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $gateways of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
75
            $hasGateways = true;
76
        }
77
78
        if ($hasGateways) {
79
            // Instantiate Videos Field
80
            $view->registerJs('new Videos.Field("'.$view->namespaceInputId($id).'");');
81
        }
82
83
        return $view->renderTemplate('videos/_components/fieldtypes/Video/input', [
84
            'id' => $id,
85
            'name' => $name,
86
            'value' => $value,
87
            'preview' => $preview,
88
            'hasGateways' => $hasGateways,
89
        ]);
90
    }
91
92
    /**
93
     * {@inheritdoc}
94
     */
95
    public function serializeValue($value, ElementInterface $element = null)
96
    {
97
        if (!empty($value->url)) {
98
            return Db::prepareValueForDb($value->url);
99
        }
100
101
        return parent::serializeValue($value, $element);
102
    }
103
104
    /**
105
     * {@inheritdoc}
106
     */
107
    public function normalizeValue($value, ElementInterface $element = null)
108
    {
109
        if (empty($value)) {
110
            return null;
111
        }
112
113
        if ($value instanceof \dukt\videos\models\AbstractVideo) {
114
            return $value;
115
        }
116
117
        try {
118
            $video = Videos::$plugin->getVideos()->getVideoByUrl($value);
119
120
            if ($video) {
121
                return $video;
122
            }
123
        } catch (\Exception $e) {
124
            $errorMessage = "Couldn't get video in field normalizeValue: ".$e->getMessage();
125
126
            Craft::info($errorMessage, __METHOD__);
127
128
            return new VideoError([
129
                'url' => $value,
130
                'errors' => [
131
                    $errorMessage,
132
                ],
133
            ]);
134
        }
135
136
        return null;
137
    }
138
139
    /**
140
     * Get Search Keywords.
141
     *
142
     * @param mixed            $value
143
     * @param ElementInterface $element
144
     *
145
     * @return string
146
     */
147
    public function getSearchKeywords($value, ElementInterface $element): string
148
    {
149
        $keywords = [];
150
151
        if ($value instanceof \dukt\videos\models\Video) {
152
            $keywords[] = $value->id;
153
            $keywords[] = $value->url;
154
            $keywords[] = $value->gatewayHandle;
155
            $keywords[] = $value->gatewayName;
156
            $keywords[] = $value->authorName;
157
            $keywords[] = $value->authorUsername;
158
            $keywords[] = $value->title;
159
            $keywords[] = $value->description;
160
        }
161
162
        $searchKeywords = StringHelper::toString($keywords, ' ');
163
164
        return StringHelper::encodeMb4($searchKeywords);
165
    }
166
}
167