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.

Helper::thumbnailOnDemand()   A
last analyzed

Complexity

Conditions 5
Paths 8

Size

Total Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 27
rs 9.1768
c 0
b 0
f 0
cc 5
nc 8
nop 5
1
<?php
2
3
namespace app\components;
4
5
use Yii;
6
use yii\base\Exception;
7
use yii\base\Model;
8
use yii\caching\TagDependency;
9
use yii\db\ActiveRecord;
10
use yii\helpers\ArrayHelper;
11
use Imagine\Image\ManipulatorInterface;
12
13
/**
14
 * Universal helper for common use cases
15
 * @package app\components
16
 */
17
class Helper
18
{
19
    private static $modelMaps = [];
20
21
    /**
22
     * Get all model records as array key => value.
23
     * @param string $className
24
     * @param string $keyAttribute
25
     * @param string $valueAttribute
26
     * @param bool $useCache
27
     * @param bool $useIntl
28
     * @return array
29
     */
30
    public static function getModelMap($className, $keyAttribute, $valueAttribute, $useCache = true, $useIntl = false)
31
    {
32
        /** @var ActiveRecord $className */
33
        $cacheKey = 'Map: ' . $className::tableName() . ':' . implode(':', [
34
            $keyAttribute,
35
            $valueAttribute,
36
            intval($useIntl)
37
        ]) ;
38
        if (isset(Helper::$modelMaps[$cacheKey]) === false) {
39
            Helper::$modelMaps[$cacheKey] = $useCache ? Yii::$app->cache->get($cacheKey) : false;
40
            if (Helper::$modelMaps[$cacheKey] === false) {
41
                Helper::$modelMaps[$cacheKey] = ArrayHelper::map($className::find()->asArray()->all(), $keyAttribute, $valueAttribute);
42
                if (true === $useIntl) {
43
                    array_walk(Helper::$modelMaps[$cacheKey],
44
                        function (&$value, $key)
0 ignored issues
show
Unused Code introduced by
The parameter $key is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
45
                        {
46
                            $value = Yii::t('app', $value);
47
                        });
48
                }
49
                if ($useCache === true) {
50
                    Yii::$app->cache->set(
51
                        $cacheKey,
52
                        Helper::$modelMaps[$cacheKey],
53
                        86400,
54
                        new TagDependency(
55
                            [
56
                                'tags' => [
57
                                    \devgroup\TagDependencyHelper\ActiveRecordHelper::getCommonTag($className),
58
                                ],
59
                            ]
60
                        )
61
                    );
62
                }
63
            }
64
        }
65
        return Helper::$modelMaps[$cacheKey];
66
    }
67
68
    public static function createSlug($source)
69
    {
70
        $source = mb_strtolower($source);
71
        $translateArray = [
72
            "ый" => "y", "а" => "a", "б" => "b",
73
            "в" => "v", "г" => "g", "д" => "d", "е" => "e", "ж" => "j",
74
            "з" => "z", "и" => "i", "й" => "y", "к" => "k", "л" => "l",
75
            "м" => "m", "н" => "n", "о" => "o", "п" => "p", "р" => "r",
76
            "с" => "s", "т" => "t", "у" => "u", "ф" => "f", "х" => "h",
77
            "ц" => "c", "ч" => "ch" ,"ш" => "sh", "щ" => "sch", "ъ" => "",
78
            "ы" => "y", "ь" => "", "э" => "e", "ю" => "yu", "я" => "ya",
79
            " " => "-", "." => "", "/" => "-", "_" => "-"
80
        ];
81
        $source = preg_replace('#[^a-z0-9\-]#is', '', strtr($source, $translateArray));
82
        return trim(preg_replace('#-{2,}#is', '-', $source));
83
    }
84
85
    /**
86
     * TrimPlain returns cleaned from tags part of text with given length
87
     * @param string $text input text
88
     * @param int $length length of text part
89
     * @param string $dots adding dots to end of part
90
     * @return string
91
     */
92
    public static function trimPlain($text, $length = 150, $dots = '...')
93
    {
94
        if (!is_string($text) && empty($text)) {
95
            return "";
96
        }
97
        $length = intval($length);
98
        $text = trim(strip_tags($text));
99
        $pos = mb_strrpos(mb_substr($text, 0, $length), ' ');
100
        $string = mb_substr($text, 0, $pos);
101
        if (!empty($string)) {
102
            return $string.$dots;
103
        } else {
104
            return "";
105
        }
106
    }
107
108
    public static function thumbnailOnDemand($filename, $width, $height, $relativePart = '.', $inset = true)
109
    {
110
        $pos = mb_strrpos($filename, '/', null);
111
        if ($pos > 0) {
112
            $dir = mb_substr($filename, 0, $pos);
113
            $file = mb_substr($filename, $pos + 1, null);
114
        } else {
115
            $dir = '';
116
            $file = $filename;
117
        }
118
        $thumbFilename = $dir . '/thumb-' . $width . 'x' . $height . '-' . $file;
119
        if (file_exists($relativePart . $thumbFilename) === false) {
120
            try {
121
                $image = \yii\imagine\Image::thumbnail(
122
                    $relativePart . $filename,
123
                    $width,
124
                    $height,
125
                    $inset ? ManipulatorInterface::THUMBNAIL_INSET : ManipulatorInterface::THUMBNAIL_OUTBOUND
126
                );
127
                $image->save($relativePart . $thumbFilename, ['quality' => 90]);
128
            } catch (\Imagine\Exception\InvalidArgumentException $e) {
129
                // it seems that file not found in most cases - return original filename instead
130
                return $filename;
131
            }
132
        }
133
        return $thumbFilename;
134
    }
135
136
    /**
137
     * @param Model $model
138
     * @param string $glue
139
     * @return string
140
     */
141
    public static function formatModelErrors(Model $model, $glue = PHP_EOL)
142
    {
143
        return implode($glue,
144
            array_map(
145
                function($item) {
146
                    return is_array($item) ? array_pop($item) : $item;
147
                },
148
                $model->getErrors()
149
            )
150
        );
151
    }
152
153
    /**
154
     * used with backend/widgets/DataRelationsWidget
155
     * @param ActiveRecord $model
156
     * @param $relationData
157
     * @return array
158
     */
159
    public static function getRelationDataByModel(ActiveRecord $model, $relationData)
160
    {
161
        $result = [];
162
163
        foreach ($relationData as $name => $data) {
164
            if ($data['type'] == 'field') {
165
                if (isset($model->attributes[$data['key']])) {
166
                    $result[$name] = [
167
                        'value' => $model->{$data['key']},
168
                        'label' => $model->getAttributeLabel($data['key'])
169
                    ];
170
                }
171
            }elseif ($data['type'] == 'property') {
172
                try {
173
                    $result[$name] = [
174
                        'value' => $model->AbstractModel->{$data['key']},
175
                        'label' => $model->AbstractModel->getAttributeLabel($data['key'])
176
                    ];
177
                } catch (Exception $e) {
178
                    Yii::warning(
179
                        'relation data not found: class: '.
180
                        $model::className().'; relation Type'.
0 ignored issues
show
Deprecated Code introduced by
The method yii\base\BaseObject::className() has been deprecated with message: since 2.0.14. On PHP >=5.5, use `::class` instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
181
                        $data['type'].'; id '.$model->id
182
                    );
183
                }
184
            } elseif ($data['type'] == 'relation') {
185
                try {
186
                    $result[$name] = [
187
                        'value' => $model->{$data['relationName']}->{$data['key']},
188
                        'label' => $model->{$data['relationName']}->getAttributeLabel($data['key'])
189
                    ];
190
                } catch (Exception $e) {
191
                    Yii::warning(
192
                        'relation data not found: class: '.
193
                        $model::className().'; relation Type'.
0 ignored issues
show
Deprecated Code introduced by
The method yii\base\BaseObject::className() has been deprecated with message: since 2.0.14. On PHP >=5.5, use `::class` instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
194
                        $data['type'].'; id '.$model->id
195
                    );
196
                }
197
            }
198
        }
199
200
        return $result;
201
    }
202
}
203