403Webshell
Server IP : 80.87.202.40  /  Your IP : 216.73.216.169
Web Server : Apache
System : Linux rospirotorg.ru 5.14.0-539.el9.x86_64 #1 SMP PREEMPT_DYNAMIC Thu Dec 5 22:26:13 UTC 2024 x86_64
User : bitrix ( 600)
PHP Version : 8.2.27
Disable Function : NONE
MySQL : OFF |  cURL : ON |  WGET : ON |  Perl : ON |  Python : OFF |  Sudo : ON |  Pkexec : ON
Directory :  /home/bitrix/ext_www/rospirotorg.ru/bitrix/modules/burlakastudio.realcommenter/lib/

Upload File :
current_dir [ Writeable] document_root [ Writeable]

 

Command :


[ Back ]     

Current File : /home/bitrix/ext_www/rospirotorg.ru/bitrix/modules/burlakastudio.realcommenter/lib/OrmHelper.php
<?php


namespace Burlakastudio\Realcommenter;


use Bitrix\Main\ArgumentException;
use Bitrix\Main\DB\Exception;
use Bitrix\Main\Entity\IntegerField;
use Bitrix\Main\Error;
use Bitrix\Main\ORM\Data\AddResult;
use Bitrix\Main\ORM\Entity;
use Bitrix\Main\ORM\Fields\ArrayField;
use Bitrix\Main\ORM\Fields\Relations\Reference;
use Bitrix\Main\ORM\Objectify\EntityObject;
use Bitrix\Main\ORM\Query\Filter\ConditionTree;
use Bitrix\Main\ORM\Query\Query;
use Bitrix\Main\SystemException;
use RuntimeException;

class OrmHelper
{

    protected static $hlApiCode;
    protected static $compiledEntities = [];

    public static function getInfo($idList = null, $simplifySingle = true)
    {
        $result = null;

        if (!empty($idList)) {

            if (!is_array($idList)) {
                $idList = [$idList];
            }

            $list = static::getList();
            $result = array_filter($list, static function ($key) use ($idList) {
                return in_array($key, $idList);
            }, ARRAY_FILTER_USE_KEY);
        }

        if ($result && $simplifySingle && count($idList) === 1) {
            return array_shift($result);
        }

        return $result;
    }

    public static function getList($parameters = [])
    {
        $result = [];

        if (static::$hlApiCode) {
            $entity = static::compileEntity();
            $query = new Query($entity);

            if ($parameters['filter']) {
                $query = $query->setFilter($parameters['filter']);
            }

            if ($parameters['order']) {
                $query = $query->setOrder($parameters['order']);
            }

            if ($parameters['limit']) {
                $query = $query->setLimit($parameters['limit']);
            }

            if ($parameters['select']) {
                $query = $query->setSelect($parameters['select']);
            } else {
                $query = $query->setSelect(['*']);
            }

            if (empty($parameters)) {
                $query = $query
                    ->setCacheTtl(CACHE::getTtl())
                    ->cacheJoins(true);
            }

            $queryResult = $query->exec();

            while ($arr = $queryResult->fetch()) {
                $result[$arr['ID']] = $arr;
            }
        }

        return $result;
    }

    /**
     * First attempt to compiler class
     * Hlblock imply Integer, todo reference
     *
     * @param null $hlType
     * @return Entity|null
     * @throws ArgumentException
     * @throws SystemException
     */
    public static function compileEntity($hlType = null)
    {
        $hlType = $hlType ?? static::$hlApiCode;

        if (isset(self::$compiledEntities[$hlType])) {
            return self::$compiledEntities[$hlType];
        }

        $hlInfo = CheckerDb::getHlStruct($hlType);
        if (empty($hlInfo)) {
            return null;
        }

        $entity = Entity::compileEntity(
            $hlType . 'Custom',
            [(new IntegerField('ID'))->configurePrimary()],
            [
                'namespace' => 'Burlakastudio\Realcommenter',
                'table_name' => $hlInfo['TABLE_NAME']
            ]
        );

        //\Bitrix\Main\Entity\Field
        //\Bitrix\Main\ORM\Fields\

        foreach ($hlInfo['UF'] as $fieldName => $fieldInfo) {
            if ($fieldInfo['MULTIPLE'] === 'Y' || $fieldInfo['USER_TYPE_ID'] === 'array') {
                $entity->addField(
                    (new ArrayField($fieldName))
                        ->configureSerializationPhp(),
                    $fieldName
                );
            } else {
                $fieldType = $fieldInfo['USER_TYPE_ID'] === 'hlblock' ? 'integer' : $fieldInfo['USER_TYPE_ID'];
                $entity->addField(
                    [
                        'data_type' => $fieldType,
                        'default_value' => $fieldInfo['SETTINGS']['DEFAULT_VALUE'] ?? ''
                    ],
                    $fieldName
                );
            }
        }

        self::$compiledEntities[$hlType] = $entity;
        return $entity;
    }

    /**
     * Add through "get free row or create new" way
     *
     * @param array $data
     * @return array|bool|int|string
     * @throws Exception
     */
    public static function addViaFreeRowsWay($data = [])
    {
        if (empty($data)) {
            return false;
        }

        $row = static::getFreeRow();

        if (empty($row) || !$row['ID']) {
            throw new RuntimeException('Orm add via free row failed');
        }

        $updateResult = static::update($row['ID'], array_merge($row, $data));
        if ($updateResult && !$updateResult->isSuccess()) {
            throw new RuntimeException(implode(', ', $updateResult->getErrorMessages()));
        }

        return $updateResult->getId();
    }

    /**
     * ����� ����� ����������� �� ������� ������ ������-���������
     * ��������� ������ � ���� ID ������
     *
     * @return array|bool|mixed
     * @throws Exception
     */
    public static function getFreeRow()
    {
        /**
         * ��� ��������� ������ ��,
         * ������ ��� ����� ����� ������ ��� �����
         */
        $getlistFilter = static::prepareFreeRowLeadFilter();
        if (empty($getlistFilter)) {
            return [];
        }

        $row = static::getList([
            'filter' => $getlistFilter,
            'order' => ['ID' => 'ASC'],
            'limit' => 1
        ]);

        //����� ������ ����� � ������ �������� �����
        $fields = static::prepareEmptyFields();

        if ($row) {
            $row = array_shift($row);
            /**
             * � ���� ����� �����,
             * ������ � ����� ������ �����.
             *
             * �� ������� �� ��� �� ��������� ����.
             * ...� ��� ����� ����� � ���� ���� �����
             */
            $row += $fields;

            return $row;
        }

        //����� ������ ����� � ������ �������� �����
        $addResult = static::add($fields);

        if (!$addResult->isSuccess()) {
            throw new Exception(
                ErrorNotificator::getErrorLang('error_to_get_free_cell')
                . implode(', ', $addResult->getErrorMessages())
            );
        }

        $rowId = $addResult->getId();

        if ($rowId) {
            return ['ID' => $rowId];
        }

        return false;
    }

    protected static function prepareFreeRowLeadFilter()
    {
        $filter = [];

        $leadFieldname = static::getLeadFieldName();
        if (!empty($leadFieldname)) {
            array_walk($leadFieldname, static function ($item) use (&$filter) {
                $filter[$item] = null;
            });
        }

        return $filter;
    }

    protected static function getLeadFieldName()
    {
        // Pretty often UF_NAME is lead field
        return ['UF_NAME'];
    }

    protected static function prepareEmptyFields()
    {
        $result = [];

        $fields = static::getFields(true);

        /**
         * ������ ������ � ������ �������� �� ������� UF_* ���.
         * ������� ���� ������ ������ �� �������, � �������� ������ ������,
         *      ������� ��� ���� ���� �����
         */
        array_walk($fields, static function ($defaultValue, $keyName) use (&$result) {
            if (!($keyName === 'ID' || strpos($keyName, '_REF'))) {
                $result[$keyName] = $defaultValue;
            }
        });

        return $result;
    }

    protected static function getFields($skipReferences = null)
    {
        $result = [];

        $entity = static::compileEntity();
        if ($entity) {
            foreach ($entity->getFields() as $field) {
                if ($skipReferences && $field instanceof Reference) {
                    continue;
                }

                $result[$field->getName()] = $field->getParameter('default_value');
            }
        }

        return $result;
    }

    public static function add($data = [])
    {

        if (!empty($data)) {
            $entity = static::compileEntity();

            if ($entity) {

                /**
                 * @var EntityObject $newObject
                 */
                $newObject = $entity->createObject();
                foreach ($data as $key => $value) {
                    $newObject->set($key, $value);
                }

                $result = $newObject->save();
                if (!$result->isSuccess()) {
                    DEBUGGER::error(
                        implode(', ', $result->getErrorMessages()),
                        ['func' => 'OrmHelper::add', 'data' => $data],
                        false
                    );
                }

            } else {
                $result = new AddResult();
                $result->addError(new Error('Compile Entity Error'));
            }
        } else {
            $result = new AddResult();
            $result->addError(new Error('Empty Data'));
        }

        return $result;
    }

    public static function update($primary = null, $data = [])
    {
        if ($primary && !empty($data)) {
            $entity = static::compileEntity();

            if ($entity) {
                $entityClass = $entity->getDataClass();

                if (isset($data['ID'])) {
                    unset($data['ID']);
                }

                return $entityClass::updateMulti([$primary], $data, true);
            }
        }

        return null;
    }

    /**
     * Not literally delete, but pretending:
     * set old rows free and awailable to get new data in future
     * @param ConditionTree $filter
     * @throws ArgumentException
     * @throws SystemException
     * @throws \Bitrix\Main\ObjectPropertyException
     */
    public static function makeThemFree(ConditionTree $filter = null)
    {
        $entity = static::compileEntity();
        if (!$entity) {
            return;
        }

        /**
         * Eigher filter sent to us outside
         * or create filter by lead fields
         */
        if (!$filter) {
            $leadFields = static::getLeadFieldName();

            $filter = Query::filter();
            foreach ($leadFields as $fieldName) {
                $filter->whereNotNull($fieldName);
            }
        }

        $qRes = (new Query($entity))
            ->where($filter)
            ->setSelect(['ID', '*'])
            ->exec();

        //����� ������ ����� � ������ �������� �����
        $emptyFields = static::prepareEmptyFields();

        /**
         * @var EntityObject $valueObj
         */
        while ($valueObj = $qRes->fetchObject()) {
            foreach ($emptyFields as $fieldName => $fieldVal) {
                $valueObj->set($fieldName, null);
            }

            $valueObj->save();
        }
    }

    protected static function validateAndFillBeforeSave(&$data)
    {
        $fieldsSettings = CheckerDb::getHlUserfieldsOptions(static::$hlApiCode) ?: null;
        if (!$fieldsSettings) {
            return;
        }

        foreach ($data as $key => &$value) {
            if (!$value) {
                $defaultValue = $fieldsSettings[$key]['SETTINGS']['DEFAULT_VALUE'] ?: null;
                if ($defaultValue) {
                    $value = $defaultValue;
                }
            }

            unset($fieldsSettings[$key]);
        }

        unset($value);

        if (!empty($fieldsSettings)) {
            foreach ($fieldsSettings as $key => $value) {
                $defaultValue = $value['SETTINGS']['DEFAULT_VALUE'] ?: null;
                if ($defaultValue) {
                    $data[$key] = $defaultValue;
                }
            }
        }
    }

}

Youez - 2016 - github.com/yon3zu
LinuXploit