Issues (53)

src/functions.php (15 issues)

1
<?php
2
3
use Alex19pov31\BitrixHelper\ComponentHelper;
4
use Alex19pov31\BitrixHelper\HlBlockHelper;
5
use Alex19pov31\BitrixHelper\IblockHelper;
6
use Bitrix\Main\Application;
0 ignored issues
show
The type Bitrix\Main\Application was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
7
use Bitrix\Main\Data\Cache;
0 ignored issues
show
The type Bitrix\Main\Data\Cache was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use Bitrix\Main\Data\TaggedCache;
0 ignored issues
show
The type Bitrix\Main\Data\TaggedCache was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
9
use Bitrix\Main\DB\Exception;
0 ignored issues
show
The type Bitrix\Main\DB\Exception was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
This use statement conflicts with another class in this namespace, Exception. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
10
use Bitrix\Main\DB\Result;
0 ignored issues
show
The type Bitrix\Main\DB\Result was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
11
use Bitrix\Main\Loader;
0 ignored issues
show
The type Bitrix\Main\Loader was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
12
use Bitrix\Main\ORM\Data\DataManager;
0 ignored issues
show
The type Bitrix\Main\ORM\Data\DataManager was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
13
use Bitrix\Main\HttpRequest;
0 ignored issues
show
The type Bitrix\Main\HttpRequest was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
This use statement conflicts with another class in this namespace, HttpRequest. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
14
15
if (!function_exists('bxApp')) {
16
    /**
17
     * Entry point bitrix application
18
     *
19
     * @return CMain
20
     */
21
    function bxApp(): CMain
0 ignored issues
show
The type CMain was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
22
    {
23
        global $APPLICATION;
24
        return $APPLICATION;
25
    }
26
}
27
28
if (!function_exists('appInstance')) {
29
    function appInstance(): Application
30
    {
31
        return Application::getInstance();
32
    }
33
}
34
35
if (!function_exists('sql')) {
36
    /**
37
     * Выполнить sql запрос
38
     *
39
     * @param string $sql
40
     * @return Result
41
     */
42
    function sql(string $sql): Result
43
    {
44
        return appInstance()->getConnection()->query($sql);
45
    }
46
}
47
48
if (!function_exists('loadModule')) {
49
    /**
50
     * Загрузить модуль
51
     *
52
     * @param string $moduleName
53
     * @return boolean
54
     */
55
    function loadModule(string $moduleName): bool
56
    {
57
        return (bool)Loader::includeModule($moduleName);
58
    }
59
}
60
61
if (!function_exists('cacheKey')) {
62
    /**
63
     * Ключ кеша
64
     *
65
     * @param array $data
66
     * @return string
67
     */
68
    function cacheKey(array $data): string
69
    {
70
        return md5(
71
            json_encode($data)
72
        );
73
    }
74
}
75
76
if (!function_exists('bxUser')) {
77
    /**
78
     * Объект локального пользователя
79
     *
80
     * @return CUser
81
     */
82
    function bxUser(): CUser
0 ignored issues
show
The type CUser was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
83
    {
84
        global $USER;
85
        return $USER;
86
    }
87
}
88
89
if (!function_exists('getIblockId')) {
90
    /**
91
     * Идентификатор инфоблока
92
     *
93
     * @param string $code
94
     * @param string|null $iblockType
95
     * @return integer|null
96
     */
97
    function getIblockId(string $code, $iblockType = null, int $minutes = 0)
98
    {
99
        IblockHelper::setCacheTime($minutes);
100
        return IblockHelper::getIblockID($code, $iblockType);
101
    }
102
}
103
104
if (!function_exists('getHlBlock')) {
105
    /**
106
     * Информация о HL блоке
107
     *
108
     * @param string $code
109
     * @param integer $minutes
110
     * @return array|null
111
     */
112
    function getHlBlock(string $code, $minutes = 0)
113
    {
114
        HlBlockHelper::setCacheTime($minutes);
115
        return HlBlockHelper::getHlblock($code);
116
    }
117
}
118
119
if (!function_exists('getHlBlockClass')) {
120
    /**
121
     * Класс для работы с HL блоком
122
     *
123
     * @param string $code
124
     * @param integer $minutes
125
     * @return DataManager|null
126
     */
127
    function getHlBlockClass(string $code, $minutes = 0)
128
    {
129
        HlBlockHelper::setCacheTime($minutes);
130
        return HlBlockHelper::getHlblockClass($code);
131
    }
132
}
133
134
if (!function_exists('taggedCache')) {
135
    /**
136
     * Тэггированный кеш
137
     *
138
     * @return TaggedCache
139
     */
140
    function taggedCache(): TaggedCache
141
    {
142
        return appInstance()->getTaggedCache();
143
    }
144
}
145
146
if (!function_exists('initTagCache')) {
147
    /**
148
     * Инициализация тэггированного кеша
149
     *
150
     * @param array $tags
151
     * @param string $cacheDir
152
     * @return void
153
     */
154
    function initTagCache(array $tags, string $cacheDir = '/')
155
    {
156
        taggedCache()->startTagCache($cacheDir);
157
        foreach ($tags as $tag) {
158
            taggedCache()->registerTag($tag);
159
        }
160
        taggedCache()->endTagCache();
161
    }
162
}
163
164
if (!function_exists('cache')) {
165
    /**
166
     * Кеширование
167
     *
168
     * @param integer $minutes
169
     * @param string $key
170
     * @param string $initDir
171
     * @param string $baseDir
172
     * @param callable $func
173
     * @return mixed
174
     */
175
    function cache(int $minutes, string $key, $initDir = '/', string $baseDir = 'cache', callable $func)
176
    {
177
        $data = null;
178
        $ttl = $minutes * 60;
179
        $cache = Cache::createInstance();
180
        if ($cache->initCache($ttl, $key, $initDir, $baseDir)) {
181
            $data = $cache->getVars();
182
        } elseif ($cache->startDataCache($ttl, $key, $initDir, [], $baseDir)) {
183
            try {
184
                $data = $func();
185
                $cache->endDataCache($data);
186
            } catch (Exception $e) {
187
                $cache->abortDataCache();
188
                taggedCache()->abortTagCache();
189
            }
190
        }
191
192
        return $data;
193
    }
194
}
195
196
if (!function_exists('cleanCache')) {
197
    /**
198
     * Отчистка кеша
199
     *
200
     * @param string $key
201
     * @param string $initDir
202
     * @param string $baseDir
203
     * @return void
204
     */
205
    function cleanCache(string $key, $initDir = '/', string $baseDir = 'cache')
206
    {
207
        $cache = Cache::createInstance();
208
        $cache->clean($key, $initDir, $baseDir);
209
    }
210
}
211
212
if (!function_exists('setCacheData')) {
213
    /**
214
     * Зписать данные в кеш (с предварительной отчисткой)
215
     *
216
     * @param integer $minutes
217
     * @param string $key
218
     * @param string $initDir
219
     * @param string $baseDir
220
     * @param [type] $data
0 ignored issues
show
Documentation Bug introduced by
The doc comment [type] at position 0 could not be parsed: Unknown type name '[' at position 0 in [type].
Loading history...
221
     * @return void
222
     */
223
    function setCacheData(int $minutes, string $key, $initDir = '/', string $baseDir = 'cache', $data)
224
    {
225
        cleanCache($key, $initDir, $baseDir);
226
        cache($minutes, $key, $initDir, $baseDir, function () use ($data) {
227
            return $data;
228
        });
229
    }
230
}
231
232
if (!function_exists('initEditIblockElement')) {
233
    /**
234
     * Область редактирования элемента инфоблока
235
     *
236
     * @param CBitrixComponentTemplate $tpl
237
     * @param integer $elementId
238
     * @param integer $iblockId
239
     * @param string $iblockType
240
     * @param string $description
241
     * @return string
242
     */
243
    function initEditIblockElement(CBitrixComponentTemplate $tpl, int $elementId, int $iblockId, string $iblockType, string $description = null): string
0 ignored issues
show
The type CBitrixComponentTemplate was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
244
    {
245
        $link = '/bitrix/admin/iblock_element_edit.php?IBLOCK_ID=' . $iblockId . '&type=' . $iblockType . '&ID=' . $elementId . '&lang=ru&force_catalog=&filter_section=0&bxpublic=Y&from_module=iblock';
246
        if (is_null($description)) {
247
            $description = "Редактировать элемент";
248
        }
249
250
        $tpl->AddEditAction($elementId, $link, $description);
251
252
        return (string)$tpl->GetEditAreaId($elementId);
253
    }
254
}
255
256
if (!function_exists('initEditIblockSection')) {
257
    /**
258
     * Область редактирования раздела инфоблока
259
     *
260
     * @param CBitrixComponentTemplate $tpl
261
     * @param integer $sectionId
262
     * @param integer $iblockId
263
     * @param string $iblockType
264
     * @param string $description
265
     * @return string
266
     */
267
    function initEditIblockSection(CBitrixComponentTemplate $tpl, int $sectionId, int $iblockId, string $iblockType, string $description = null): string
268
    {
269
        $link = '/bitrix/admin/iblock_section_edit.php?IBLOCK_ID=' . $iblockId . '&type=' . $iblockType . '&ID=' . $sectionId . '&lang=ru&find_section_section=0&bxpublic=Y&from_module=iblock';
270
        if (is_null($description)) {
271
            $description = "Редактировать раздел";
272
        }
273
274
        $tpl->AddEditAction($sectionId, $link, $description);
275
276
        return (string)$tpl->GetEditAreaId($sectionId);
277
    }
278
}
279
280
if (!function_exists('initEditHLBlockElement')) {
281
    /**
282
     * Область редактирования элемента HL блока
283
     *
284
     * @param CBitrixComponentTemplate $tpl
285
     * @param integer $elementId
286
     * @param string $hlBlockName
287
     * @param string $description
288
     * @return string
289
     */
290
    function initEditHLBlockElement(CBitrixComponentTemplate $tpl, int $elementId, string $hlBlockName, string $description = null): string
291
    {
292
        $hlBlock = getHlBlock($hlBlockName);
293
        if (empty($hlBlock)) {
294
            return '';
295
        }
296
297
        $link = '/bitrix/admin/highloadblock_row_edit.php?ENTITY_ID=' . $hlBlock['ID'] . '&ID=' . $elementId . '&bxpublic=Y';
298
        if (is_null($description)) {
299
            $description = "Редактировать элемент";
300
        }
301
302
        $tpl->AddEditAction($elementId, $link, $description);
303
304
        return (string)$tpl->GetEditAreaId($elementId);
305
    }
306
}
307
308
if (!function_exists('initComponent')) {
309
    /**
310
     * Инициализация компонента
311
     *
312
     * @param string $name
313
     * @param string $template
314
     * @param array $params
315
     * @param mixed $parentComponent
316
     * @param array $functionParams
317
     * @return ComponentHelper
318
     */
319
    function initComponent(string $name, string $template = '', array $params = [], $parentComponent = null, $functionParams = []): ComponentHelper
320
    {
321
        return new ComponentHelper($name, $template, $params, $parentComponent, $functionParams);
322
    }
323
}
324
325
if (!function_exists('includeArea')) {
326
    /**
327
     * Включаемая область
328
     *
329
     * @param string $path
330
     * @param string|null $folder
331
     * @return void
332
     */
333
    function includeArea(string $path, $basePath = null)
334
    {
335
        if (is_null($basePath)) {
336
            $basePath = bxApp()->GetTemplatePath('') . 'include';
337
        }
338
339
        initComponent('bitrix:main.include')
340
            ->setTemplate('.default')
341
            ->setParams([
342
                "AREA_FILE_SHOW" => "file",
343
                "AREA_FILE_SUFFIX" => "inc",
344
                "AREA_FILE_RECURSIVE" => "Y",
345
                "EDIT_TEMPLATE" => "",
346
                "COMPONENT_TEMPLATE" => ".default",
347
                "PATH" => "{$basePath}/{$path}",
348
            ])
349
            ->show();
350
    }
351
}
352
353
if (!function_exists('sendJsonResponse')) {
354
    /**
355
     * Ответ в формате json
356
     *
357
     * @param array $data
358
     * @param integer $statusCode
359
     * @return void
360
     */
361
    function sendJsonResponse(array $data, int $statusCode)
362
    {
363
        bxApp()->RestartBuffer();
364
        http_response_code($statusCode);
365
        header('Content-Type: application/json');
366
        echo json_encode($data);
367
        die();
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
368
    }
369
}
370
371
/**
372
 * Инициализация констант с идентификаторами инфоблоков
373
 *
374
 * @param integer $caheMinutes
375
 * @return void
376
 */
377
function initIBConstantList(int $caheMinutes)
378
{
379
    IblockHelper::setCacheTime($caheMinutes);
380
    $list = IblockHelper::getListIblock();
381
    foreach ($list as $iblock) {
382
        define('IBLOCK_' . strtoupper($iblock['CODE']), $iblock['ID']);
383
    }
384
}
385
386
/**
387
 * Объект запроса
388
 *
389
 * @return HttpRequest
390
 */
391
function bxRequest(): HttpRequest
392
{
393
    return appInstance()->getContext()->getRequest();
394
}
395