/** * Возвращает очки по коду * * @param int|null $userId - если передан код пользователя, то стсиема убедится, что очки даны этому пользователю * @return UserPointDO */ public function getPointById($pointId, $userId = null) { $where['id_point'] = $pointId; if (is_inumeric($userId)) { $where['id_user'] = $userId; } return new UserPointDO($this->getRecEnsure(Query::select('*', 'ps_user_points', $where))); }
/** * Процесс строит скрипты для вставки ячеек в БД * * @param array $argv */ function executeProcess(array $argv) { $DM = DirManager::inst(array(__DIR__, 'output')); $customNum = $argv[1]; dolog('Processing mosaic demo, custom num={}', $customNum); /* @var $dir DirItem */ foreach ($DM->getDirContent(null, DirItemFilter::DIRS) as $dir) { if (is_inumeric($customNum) && $customNum != $dir->getName()) { continue; //---- } $imgDM = DirManager::inst($dir->getAbsPath()); $imgDI = end($imgDM->getDirContent(null, DirItemFilter::IMAGES)); $map = $imgDM->getDirItem(null, 'map', 'txt')->getFileAsProps(); $demoDM = DirManager::inst($imgDM->absDirPath(), 'demo'); $demoDM->clearDir(); dolog("Building map for: [{}].", $imgDI->getRelPath()); //CELLS BINDING $dim = $imgDM->getDirItem(null, 'settings', 'txt')->getFileAsProps(); $dim = $dim['dim']; $dim = explode('x', $dim); $cw = 1 * $dim[0]; $ch = 1 * $dim[1]; $sourceImg = SimpleImage::inst()->load($imgDI); $w = $sourceImg->getWidth(); $h = $sourceImg->getHeight(); $destImg = SimpleImage::inst()->create($w, $h, MosaicImage::BG_COLOR); dolog("Img size: [{$w} x {$h}]."); check_condition($w > 0 && !($w % $cw), 'Bad width'); check_condition($h > 0 && !($h % $ch), 'Bad height'); $totalCells = count($map); $lengtn = strlen("{$totalCells}"); //dolog("Cells cnt: [$xcells x $ycells], total: $totalCells."); //СТРОИМ КАРТИНКИ $secundomer = Secundomer::startedInst(); //$encoder = new PsGifEncoder(); for ($cellCnt = 0; $cellCnt <= $totalCells; $cellCnt++) { $name = pad_zero_left($cellCnt, $lengtn); $copyTo = $demoDM->absFilePath(null, $name, 'jpg'); if ($cellCnt > 0) { $cellParams = $map[$cellCnt]; $cellParams = explode('x', $cellParams); $xCell = $cellParams[0]; $yCell = $cellParams[1]; $x = ($xCell - 1) * $cw; $y = ($yCell - 1) * $ch; $destImg->copyFromAnother($sourceImg, $x, $y, $x, $y, $cw, $ch); } $destImg->save($copyTo); dolog("[{$totalCells}] {$copyTo}"); } //$encoder->saveToFile($demoDM->absFilePath(null, 'animation')); $secundomer->stop(); dolog('Execution time: ' . $secundomer->getTotalTime()); } }
/** @return PSSelect */ private function addParam($type, $param) { if (is_array($param)) { foreach ($param as $key => $value) { if (is_inumeric($key)) { $this->addParam($type, $value); } else { $this->setParam($type, $key, $value); } } return $this; } if ($param instanceof QueryParam) { return $this->registerQueryParam($type, $param); } if (PsCheck::isValidQueryPlainExpression($param)) { return $this->registerQueryParam($type, self::plainParam($param)); } return $this; }
/** * Построение запроса для обращения к БД */ private function makeQuery($prefix, array &$params, $asc = null) { check_condition($prefix, 'Не передан запрос'); $queryString = array(trim($prefix) . ' where type=? and b_deleted=0'); $queryParams = array(self::assertValidType(array_get_value_unset('type', $params))); //id_upload $id_upload = array_get_value_unset('id_upload', $params); if (is_inumeric($id_upload)) { $queryString[] = 'id_upload=?'; $queryParams[] = $id_upload; } //id_user $id_user = array_get_value_unset('id_user', $params); if (is_inumeric($id_user)) { $queryString[] = 'id_user is not null and id_user=?'; $queryParams[] = $id_user; } check_condition(empty($params), 'Неизвестные ключи переданы для запроса файла: ' . array_to_string($params, false)); $order = $asc === true ? ' order by dt_event asc, id_upload asc' : ''; $order = $asc === false ? ' order by dt_event desc, id_upload desc' : ''; $params = $queryParams; return implode(' and ', $queryString) . $order; }
public function int($key, $default = null) { $val = $this->get($key, $default); return is_inumeric($val) ? 1 * $val : null; }
/** * Метод возвращает содержимое строки файла */ function file_get_line_contents($path, $lineNum) { check_condition(is_inumeric($lineNum), "Invalid file line number given: [{$lineNum}]"); $lineNum = 1 * $lineNum; check_condition($lineNum > 0, "Only positive line numbers is alloved, given: [{$lineNum}]"); $handle = fopen($path, "r"); for ($num = 1; !feof($handle); ++$num) { $line = fgets($handle); if ($num == $lineNum) { fclose($handle); return $line; } } fclose($handle); return null; }
private function uploadFileImpl(DirItem $source, FILEAdapter $file = null, $userId = null, array $params = array()) { $userId = $this->checkUserId($userId); $this->LOGGER->info("Processing file upload for user [{$userId}], source {$source}."); $aa = ArrayAdapter::inst($params); $uploaded = $file ? $source : null; $originalName = $file ? $file->getOriginalName() : $source->getName(); $dbMsg = null; try { $this->LOGGER->info('Calling onBeforeSave...'); $dbMsg = $this->onBeforeSave($source, $userId, $aa); $this->LOGGER->info("\tDone!"); } catch (Exception $ex) { $this->LOGGER->info('Error occurred in onBeforeSave method: ' . $ex->getMessage()); $this->LOGGER->info('Source file will be deleted ? {}.', var_export(!!$uploaded, true)); if ($uploaded) { $uploaded->remove(); } throw $ex; } if ($uploaded) { //Это уже и так загруженный файл $this->LOGGER->info('Source file is uploaded file'); } else { $this->LOGGER->info('Move source file to uploads dir'); $uploaded = $this->makeTmpDirItem(); $source->copyTo($uploaded); } if ($this->LOGGER->isEnabled()) { $this->LOGGER->info("\tUploaded file: {$uploaded}"); $this->LOGGER->info("\tOriginal name: [{$originalName}]"); $this->LOGGER->info("\tMime: [{$uploaded->getMime()}]"); $this->LOGGER->info("\tParams: " . array_to_string($params, false)); } $uploadId = null; if ($this->isStoreToDb()) { $this->LOGGER->info("Saving upload file into database. DbMsg: '{$dbMsg}'."); try { $uploadId = UploadsBean::inst()->saveFileUpload($this->DBTYPE, $uploaded->getAbsPath(), $originalName, $uploaded->getMime(), $userId, $dbMsg); //Почистим кеш, вдруг мы запрашивали информацию по данному файлу $this->CACHE->remove($uploadId); $this->LOGGER->info("\tFile successfully saved, uploadId = {$uploadId}."); } catch (Exception $ex) { $this->LOGGER->info('Error occured while saving file to DB: ' . $ex->getMessage()); $this->LOGGER->info('Deleting upload file...'); $uploaded->remove(); $uploaded = null; throw $ex; } $uploaded->setData('id', $uploadId); } try { $this->LOGGER->info('Calling onAfterSave...'); $this->onAfterSave($uploaded, $userId, $aa); $this->LOGGER->info("\tDone!"); } catch (Exception $ex) { $this->LOGGER->info('Error occured in onAfterSave method: ' . $ex->getMessage()); if (is_inumeric($uploadId)) { $this->LOGGER->info('Deleting db record...'); UploadsBean::inst()->clearFileUpload($uploadId); $uploadId = null; } $this->LOGGER->info('Deleting upload file...'); $uploaded->remove(); $uploaded = null; throw $ex; } /* * Если класс работает автономно и не работает с базой, то файл нужно удалить. */ if ($this->isAutonomous() && !$this->isStoreToDb()) { $this->LOGGER->info('Class is auto clean, deleting uploaded file...'); $uploaded->remove(); $uploaded = null; } $this->LOGGER->info(''); return $uploaded; }
/** * По переданному на вход параметру определяет, является ли пользователь - указанным. * Можно передать: * 1. Код пользователя * 2. Объект данного класа */ public final function isIt($user) { if (is_inumeric($user)) { return $this->userId === 1 * $user; } if ($user instanceof PsUser) { return $this->userId === $user->getId(); } return false; }
/** * Метод получает страницу */ public final function getPage($search, $ensure = true) { if ($search instanceof WebPage) { return $search; //--- } //По коду if (is_inumeric($search)) { if (array_key_exists($search, $this->PAGES)) { return $this->PAGES[$search]; //--- } check_condition(!$ensure, "Страница с кодом [{$search}] не зарегистрирована"); return null; //--- } //Загрузка по идентификатору if (is_string($search)) { /* @var $page WebPage */ foreach ($this->PAGES as $page) { if ($page->getPath() == $search) { return $page; //--- } } check_condition(!$ensure, "Страница с адресом [{$search}] не зарегистрирована"); return null; //--- } check_condition(!$ensure, "Страница {$search} не зарегистрирована"); return null; }
/** * Метод валидирует $threadId согласно тому, работает ли данный менеджер дискуссии с тредами или нет */ private function validateThreadId($threadId) { if ($this->SETTINGS->isWorkWithThreadId()) { check_condition($threadId, 'Не указан код треда'); check_condition(is_inumeric($threadId), "Невалидный код треда: [{$threadId}]"); $threadId = 1 * $threadId; check_condition(is_integer($threadId), "Нецелочисленный код треда: [{$threadId}]"); $this->assertValidDiscussionEntityId($threadId); } else { check_condition(isEmpty($threadId), 'Указан код треда, хотя дискуссия ' . $this->getDiscussionUnique() . ' не работает с тредами'); $threadId = null; } return $threadId; }
/** * Метод загружает порцию сообщений - используется как для построения дерева, так и для дозагрузки сообщений в ветку. */ public function loadMsgsPortion($threadId = null, $maxCount = -1, $upDown = true, $rootId = null, &$bHasMore = false) { $where = array(); if (is_inumeric($rootId)) { $where[] = Query::assocParam('id_root', $rootId, true, $upDown ? '>' : '<'); } if ($this->threadIdColumn) { $where[] = "{$this->threadIdColumn} is not null"; $where[$this->threadIdColumn] = $threadId; } $orderRoot = 'id_root ' . ($upDown ? 'asc' : 'desc'); $orderMsgs = array('dt_event asc', $this->idColumn . ' asc'); $order = array($orderRoot, $orderMsgs); $limit = null; if ($maxCount > 0) { $groups = $this->getArray(Query::select('count(1) as cnt, id_root', $this->table, $where, 'id_root', $orderRoot, $maxCount + 1)); $groupNum = 0; $groupsCnt = count($groups); foreach ($groups as $group) { ++$groupNum; //$rootId = $group['id_root']; $limit = ($limit ? $limit : 0) + (int) $group['cnt']; if ($limit >= $maxCount) { $bHasMore = $groupsCnt > $groupNum; break; } } } //Мы вычислили лимит, теперь можно и загрузить сообщения return $this->loadMessages(Query::select('*', $this->table, $where, null, $order, $limit)); }
public final function isCurrent($num) { return is_inumeric($num) && 1 * $num == $this->current(); }
/** * Процесс строит скрипты для вставки ячеек в БД * * @param array $argv */ function executeProcess(array $argv) { $DM = DirManager::inst(__DIR__); //Перенесём картинки в директорию со всеми картинками /* @var $img DirItem */ foreach ($DM->getDirContent(null, DirItemFilter::IMAGES) as $img) { $img->copyTo($DM->absFilePath('source', $img->getName())); $img->remove(); } //Очистим директорию с выходными файлами $DM->clearDir('output'); $DM->makePath('output'); //Пробегаемся по картинкам, разбиваем их на ячейки и строим sql для вставки /* @var $img DirItem */ foreach ($DM->getDirContent('source', DirItemFilter::IMAGES) as $img) { $id = $img->getNameNoExt(); //Обрабатываем только картинки с целыми кодами if (is_inumeric($id)) { dolog("Processing img [{$img->getRelPath()}]."); $id = 1 * $id; } else { dolog("Skip img [{$img->getRelPath()}], name is not numeric."); continue; //--- } //Начало обработки $outDm = DirManager::inst(array(__DIR__, 'output'), $id); //Скопируем картинку $img->copyTo($outDm->absFilePath(null, $img->getName())); //Вычислим размеры ячейки $cw = 10; $ch = 10; $dim = $DM->getDirItem('source', $id, 'txt')->getFileAsProps(false); $dim = $dim['dim']; if ($dim) { $dim = explode('x', $dim); $cw = 1 * $dim[0]; $ch = 1 * $dim[1]; } //Скопируем свойства, с которыми она создавалась $outDm->getDirItem(null, 'settings', 'txt')->putToFile('dim=' . $cw . 'x' . $ch); dolog("Cell dimensions: [{$cw} x {$ch}]."); //Размеры картинки получим у самой картинки $w = $img->getImageAdapter()->getWidth(); $h = $img->getImageAdapter()->getHeight(); dolog("Img size: [{$w} x {$h}]."); check_condition($w > 0 && !($w % $cw), 'Bad width'); check_condition($h > 0 && !($h % $ch), 'Bad height'); $xcells = $w / $cw; $ycells = $h / $ch; $totalCells = $xcells * $ycells; dolog("Cells cnt: [{$xcells} x {$ycells}], total: {$totalCells}."); $generator = new MosaicCellsGenerator($totalCells); $secundomer = Secundomer::startedInst(); $sqlDI = $outDm->getDirItem(null, 'fill', 'sql'); $mapDI = $outDm->getDirItem(null, 'map', 'txt'); $sqlImg = "delete from ps_img_mosaic_parts where id_img={$id};"; $sqlDI->writeLineToFile($sqlImg); $sqlImg = "delete from ps_img_mosaic_answers where id_img={$id};"; $sqlDI->writeLineToFile($sqlImg); $sqlImg = "delete from ps_img_mosaic where id_img={$id};"; $sqlDI->writeLineToFile($sqlImg); $sqlImg = "insert into ps_img_mosaic (id_img, w, h, cx, cy, cw, ch) values ({$id}, {$w}, {$h}, {$xcells}, {$ycells}, {$cw}, {$ch});"; $sqlDI->writeLineToFile($sqlImg); for ($cellCnt = 1; $cellCnt <= $totalCells; $cellCnt++) { $cellNum = $generator->getCellNum(); $xCell = $cellNum % $xcells; $xCell = $xCell == 0 ? $xcells : $xCell; $yCell = ($cellNum - $xCell) / $xcells + 1; $sqlCell = "insert into ps_img_mosaic_parts (id_img, n_part, x_cell, y_cell) values ({$id}, {$cellCnt}, {$xCell}, {$yCell});"; $sqlDI->writeLineToFile($sqlCell); $mapDI->writeLineToFile($cellCnt . '=' . $xCell . 'x' . $yCell); } $secundomer->stop(); dolog('Execution time: ' . $secundomer->getTotalTime()); } }
/** * Проверка, является ли переданнй пользователь или код пользователя - текущим * авторизованным пользователем */ public static function isIt($UserOrId) { if (!$UserOrId || !self::isAuthorized()) { return false; //--- } if (is_inumeric($UserOrId)) { return self::getUserId() === 1 * $UserOrId; } if ($UserOrId instanceof PsUser) { return self::getUserId() === $UserOrId->getId(); } return false; }
public function current() { $num = $this->di->getFileContents(false); return is_inumeric($num) ? 1 * $num : null; }
/** * Единственный вариант создать экземпляр экземпляр класса, работающего с картинкой-мозайкой * * @return MosaicImage */ public static function inst($id) { if (!array_key_exists($id, self::$insts)) { check_condition(is_inumeric($id), "Некорректный код картинки-мозайки: [{$id}]."); self::$insts[$id] = new self($id); } return self::$insts[$id]; }
/** * Проверка целочисленного значения */ public static function isInt($var) { return is_inumeric($var); }
public function getPagingPostsIds($pagingNumber = null, $rubricId = null, $postsOnPage = POSTS_IN_ONE_PAGING) { $limit = is_inumeric($pagingNumber) ? ($pagingNumber - 1) * $postsOnPage : -1; $limit = $limit < 0 ? null : array($limit, $postsOnPage); return $this->getIds(Query::select('id_post as id', $this->postsView, is_inumeric($rubricId) ? array('id_rubric' => $rubricId) : null, null, null, $limit)); }
/** * Загрузка пользователя по email. * * @param str $email - электронный адрес пользователя * @return PsUser */ public static function instByMail($email) { $userId = UserBean::inst()->getUserIdByMail($email); check_condition(is_inumeric($userId), "Электронный адрес [{$email}] не зарегистрирован"); return self::inst($userId); }
/** * Является ли тип допустимым */ public static function hasType($type) { return is_inumeric($type) && in_array($type, self::TYPES()); }
function executeProcess(array $argv) { $CLASS_PATTERN = file_get_contents(file_path(__DIR__, 'class.txt')); $METHOD_PATTERN = file_get_contents(file_path(__DIR__, 'method.txt')); /* * Название тестового файла. * Для проверки мы сначала удалим класс для него, если он был, потом проверим, что за класс был сгенерирован. */ $TEST_MESSAGES_FILE = 'ExampleSdkProcessMessages'; //Убедимся, что тестовый .msgs существует и удалим тестовый .php файл $TEST_PHP_DI = DirItem::inst(__DIR__ . '/classes', $TEST_MESSAGES_FILE, PsConst::EXT_PHP)->remove(); $TEST_MSGS_DI = DirItem::inst(__DIR__ . '/classes', $TEST_MESSAGES_FILE, PsConst::EXT_MSGS); check_condition($TEST_MSGS_DI->isFile(), "File {$TEST_MSGS_DI->getAbsPath()} must exists"); dolog('Loading all files, ended with Messages.msgs'); //TODO - после нужно получать эту информацию из какого-нибудь места $exceptDirs[] = DirManager::autogen()->relDirPath(); $exceptDirs[] = DirManager::resources()->relDirPath(); $exceptDirs[] = DirManager::stuff()->relDirPath(); //$exceptDirs = array(); $items = DirManager::inst()->getDirContentFull(null, function (DirItem $di) { dolog($di->getAbsPath()); return $di->isFile() && ends_with($di->getName(), 'Messages.msgs'); }, $exceptDirs); dolog('Message files for processing: {}', count($items)); //Проверим, что был выбран тестовый файл check_condition(in_array($TEST_MSGS_DI, $items, true), "Test file [{$TEST_MESSAGES_FILE}] is not included"); //Удалим его из массива... array_remove_value($items, $TEST_MSGS_DI, true); //И поместим наверх, чтобы он был обработан первым array_unshift($items, $TEST_MSGS_DI); /* @var $msgsDi DirItem */ foreach ($items as $msgsDi) { dolog('PROCESSING [{}]', $msgsDi->getAbsPath()); //Сбросим методы $METHODS = array(); //Извлечём название класса $CLASS = $msgsDi->getNameNoExt(); //DirItem файла с сообщениями php $classDi = DirItem::inst($msgsDi->getDirname(), $CLASS, PsConst::EXT_PHP); //Получаем сообщения из файла .msgs $messages = $msgsDi->getFileAsProps(); foreach ($messages as $MSG_KEY => $MGG_VALUE) { dolog(' >> {}={}', $MSG_KEY, $MGG_VALUE); //Получим список всех параметров из макросов ({0}, {1}, {2} и т.д.) preg_match_all("/\\{(.+?)\\}/", $MGG_VALUE, $args); $args = array_values(array_unique($args[1])); sort($args, SORT_NUMERIC); $ARGS = array(); for ($index = 0; $index < count($args); $index++) { $arg = $args[$index]; $lineDescr = PsStrings::replaceWithBraced('[{}] in line [{}={}]', $msgsDi->getRelPath(), $MSG_KEY, $MGG_VALUE); check_condition(is_inumeric($arg), "Invalid argument [{$arg}] for {$lineDescr}"); check_condition($index == $args[$index], "Missing index [{$index}] for {$lineDescr}"); $ARGS[] = '$p' . $index; } $ARGS = join(', ', $ARGS); //Добавляем метод dolog(" A: {}::{} ({})", $CLASS, $MSG_KEY, $ARGS); $PARAMS['SUPPORT_CLASS'] = PsMsgs::getClass(); $PARAMS['MESSAGE'] = $MGG_VALUE; $PARAMS['FUNCTION'] = $MSG_KEY; $PARAMS['ARGS'] = $ARGS; $METHODS[] = PsStrings::replaceMapBracedKeys($METHOD_PATTERN, $PARAMS); } dolog('Made methods: ({})', count($METHODS)); if ($METHODS) { $PARAMS['FILE'] = $msgsDi->getAbsPath(); $PARAMS['CLASS'] = $CLASS; $PARAMS['DATE'] = date(DF_PS); $PARAMS['METHODS'] = "\n" . join("\n\n", $METHODS) . "\n"; $CLASS_PHP = PsStrings::replaceMapBracedKeys($CLASS_PATTERN, $PARAMS); $classDi->putToFile($CLASS_PHP); } /* * Если обрабатываем тестовый файл - проверим его */ //TEST CLASS VALIDATION START >>> if ($msgsDi->equals($TEST_MSGS_DI)) { dolog(''); dolog('Validating test class {}', $TEST_MESSAGES_FILE); //Проверим, что .php был сгенерирован check_condition($TEST_PHP_DI->isFile(), "File {$TEST_PHP_DI->getAbsPath()} was not created!"); //Проверим, что для каждого сообщения был создан метод $methods = PsUtil::newReflectionClass($TEST_MESSAGES_FILE)->getMethods(); $messages = $TEST_MSGS_DI->getFileAsProps(); check_condition(count($methods) == count($messages), 'Methods count missmatch, check ' . $TEST_PHP_DI->getAbsPath()); /* @var $method ReflectionMethod */ foreach ($methods as $method) { check_condition(array_key_exists($method->getName(), $messages), "No method {$TEST_MESSAGES_FILE}::" . $method->getName()); } //Проверим, что возвращают методы тестового сгенерированного класса function doTest($className, $methodName, array $params, $expected) { $method = "{$className}::{$methodName}"; $actual = call_user_func_array($method, $params); dolog("{}({})='{}', Expected='{}'", $method, join(', ', $params), $actual, $expected); check_condition($actual == $expected, "{$actual} != {$expected}"); } doTest($TEST_MESSAGES_FILE, 'message1', array(), 'Message 1'); doTest($TEST_MESSAGES_FILE, 'message2', array('a', 'b', 'c'), 'Parametred a,c,b'); dolog('Test class is valid!'); } //TEST CLASS VALIDATION END <<< } //# DirItems validation end }
protected function doAudit($action, $userId = null, $data = null, $saveToSession = false, $parentAction = null, $auditIfNoParent = true, $clearParent = true) { try { $action = $this->validateAction($action); $parentAction = $this->validateAction($parentAction, true); $actionSessionKey = $this->sessionCode($action); $parentActionSessionKey = $parentAction ? $this->sessionCode($parentAction) : null; $parentId = $parentActionSessionKey ? SessionArrayHelper::getInt($parentActionSessionKey) : null; $hasParentIdInSession = is_integer($parentId); $userId = AuthManager::validateUserIdOrNull($userId); $userIdAuthed = AuthManager::getUserIdOrNull(); if ($this->LOGGER->isEnabled()) { $this->LOGGER->info(); $this->LOGGER->info("<Запись #{}>", ++$this->NUM); $this->LOGGER->info('Действие: {}', $this->decodeAction($action)); $this->LOGGER->info('Пользователь: {}', is_inumeric($userId) ? $userId : 'НЕТ'); $this->LOGGER->info('Авторизованный пользователь: {}', is_inumeric($userIdAuthed) ? $userIdAuthed : 'НЕТ'); $this->LOGGER->info('Данные: {}', $data === null ? 'НЕТ' : print_r($data, true)); $this->LOGGER->info('Сохранять в сессию: {}', $saveToSession ? 'ДА' : 'НЕТ'); $this->LOGGER->info('Родительское действие: {}', $this->decodeAction($parentAction)); if ($parentAction) { $this->LOGGER->info('Родительское действие есть в сессии: {}', $hasParentIdInSession ? "ДА ({$parentActionSessionKey}={$parentId})" : 'НЕТ'); if ($hasParentIdInSession) { $this->LOGGER->info('Очищать родительское действие в сессии: {}', $clearParent ? 'ДА' : 'НЕТ'); } else { $this->LOGGER->info('Производить аудит при отсутствии родит. действия: {}', $auditIfNoParent ? 'ДА' : 'НЕТ'); } } } if (!$hasParentIdInSession && !$auditIfNoParent) { $this->LOGGER->info('АУДИТ НЕ ПРОИЗВЕДЁН!'); return; //--- Нужен предок, но его нет } $encoded = 0; if (is_array($data)) { if (count($data) == 0) { $data = null; } else { $data = self::encodeData($data); $encoded = 1; } } check_condition($data === null || is_string($data) || is_numeric($data), 'Illegal audit data type: ' . gettype($data) . ' for ' . $this); $recId = UtilsBean::inst()->saveAudit($parentId, $userId, $userIdAuthed, $this->PROCESS_CODE, $action, $data, $encoded); if ($this->LOGGER->isEnabled()) { if ($data !== null) { $this->LOGGER->info('Данные кодированы: {}', $encoded ? "ДА ({$data})" : 'НЕТ'); } $this->LOGGER->info('Информация сохранена в базу, id={}', $recId); } if ($saveToSession) { SessionArrayHelper::setInt($actionSessionKey, $recId); $this->LOGGER->info("Данные о действии сохранены в сессию ({$actionSessionKey}={$recId})"); } if ($hasParentIdInSession && $clearParent) { SessionArrayHelper::reset($parentActionSessionKey); $this->LOGGER->info('Данные о родительском действии удалены из сессии'); } $this->LOGGER->info('АУДИТ ПРОИЗВЕДЁН.'); } catch (Exception $ex) { //Не удалось записть аудит, но работа должна быть продолжена! ExceptionHandler::dumpError($ex); } }