Exemple #1
0
 public function __construct($postType, $commentsTable, $postsTable, $rubricsTable = null)
 {
     $this->postType = PsCheck::notEmptyString($postType);
     $this->postsTable = PsCheck::notEmptyString($postsTable);
     $this->rubricsTable = $rubricsTable;
     $this->commentsTable = PsCheck::notEmptyString($commentsTable);
 }
Exemple #2
0
 /**
  * Метод возвращает экземпляр кеша для класса
  * 
  * @param string название класса
  * @return SimpleDataCache
  */
 public static function getCache($class)
 {
     if (array_key_exists($class, self::$CACHES)) {
         return self::$CACHES[$class];
     }
     PsLogger::inst(__CLASS__)->info('+ Cache for [{}]', PsCheck::notEmptyString($class));
     return self::$CACHES[$class] = new SimpleDataCache();
 }
Exemple #3
0
 function __construct($name, $value, $asBind = true, $operator = self::DEFAULT_OPERATOR, array $extraBinds = array())
 {
     $this->name = PsCheck::tableColName($name);
     $this->value = $asBind ? PsCheck::queryBindParam($value, $name) : PsCheck::queryPlainExpression($value, $name);
     $this->asBind = $asBind;
     $this->operator = PsCheck::notEmptyString($operator);
     foreach ($extraBinds as $bindParam) {
         $this->extraBinds[] = PsCheck::queryBindParam($bindParam, $name);
     }
 }
 /**
  * В конструкторе проинициализируем все параметры соединения
  */
 private function __construct(array $params, $sourceDescr)
 {
     foreach (PsUtil::getClassConsts(__CLASS__, 'PARAM_') as $param) {
         $value = array_get_value(PsCheck::notEmptyString($param), $params);
         if (PsCheck::isNotEmptyString($value)) {
             $this->PARAMS[$param] = $value;
         } else {
             $this->PARAMS[$param] = null;
             //raise_error("Задано пустое значения для параметра $param в источнике $sourceDescr");
         }
     }
     $this->url = PsStrings::replaceWithBraced("{}://{}:{}@{}/{}", $this->scheme(), $this->user(), $this->password(), $this->host(), $this->database());
     $this->toString = PsStrings::replaceWithBraced("{}://{}:{}@{}/{} (source: {})", $this->scheme(), $this->user(), '***', $this->host(), $this->database(), $sourceDescr);
 }
 /**
  * Метод регистрации страницы
  * 
  * WebPages::register('xxx.php', 'Консоль администратора', PAGE_ADMIN, self::getIdent(), AuthManager::AUTH_TYPE_NO_MATTER, PAGE_ADMIN);
  * 
  * @param string $path - путь к скрипту, например 'xxx.php'
  * @param string $name - название страницы, например 'Консоль администратора'
  * @param int $code - код страницы PAGE_ADMIN
  * @param int $builderIdent - идентификатор построителя страниц, например 'PB_admin::getIdent()'
  * @param int $authType - тип авторизации, необходимый для доступа к странице, например 'AuthManager::AUTH_TYPE_NO_MATTER'
  * @param int $pageCodeNoAccess - страница, на которую нужно перейти при отсутствии доступа, например 'BASE_PAGE_INDEX'
  * @param bool $allovedInProduction - признак, доступна ли страница в ProductionMode
  */
 protected final function register($path, $name, $code, $builderIdent = null, $authType = AuthManager::AUTH_TYPE_NO_MATTER, $pageCodeNoAccess = null, $allovedInProduction = true)
 {
     if (!$allovedInProduction && PsDefines::isProduction()) {
         return;
         //----
     }
     $path = PsCheck::notEmptyString($path);
     $name = PsCheck::notEmptyString($name);
     $code = PsCheck::int($code);
     if (array_key_exists($code, $this->PAGES)) {
         PsUtil::raise('\'{}\' is already registered. Cannot register WebPage with same code \'{}\'.', $this->PAGES[$code], $code);
     } else {
         $this->PAGES[$code] = new WebPage($path, $name, $code, $authType, $pageCodeNoAccess, $builderIdent);
         $this->LOGGER->info('+{}. {}', pad_left(count($this->PAGES), 2, ' '), $this->PAGES[$code]);
     }
 }
Exemple #6
0
 /**
  * Метод выполняет фактическое получение лока
  */
 private function doLock($lockname, $wait)
 {
     PsCheck::notEmptyString($lockname);
     if ($this->lockName == $lockname) {
         $this->lockCnt++;
         $this->LOGGER->info('Lock ident [{}] counter inreased to {}.', $lockname, $this->lockCnt);
         return true;
     }
     check_condition($lockname, 'Lock ident cannot be empty');
     check_condition(!$this->lockName, "Lock [{$lockname}] cannot be set, previous lock [{$this->lockName}] is active");
     $filename = md5($lockname);
     $this->LOGGER->info("Trying to get lock with ident [{$lockname}], mode: {}. Lock file name=[{$filename}].", $wait ? 'WAIT' : 'NOWAIT');
     /**
      * Храним в auto-no-del, а не в autogen, так как можем потерять локи при удалении autogen
      * или вообще не иметь возможности удалить папку autogen.
      */
     $di = DirManager::autoNoDel('locks')->getDirItem(null, $filename, 'lock');
     /*
      * Файл будет создан при открытии
      */
     $fp = fopen($di->getAbsPath(), 'a+');
     do {
         $this->LOGGER->info('Locking file...');
         if (flock($fp, $wait ? LOCK_EX : LOCK_EX | LOCK_NB)) {
             $this->lockCnt = 1;
             $this->lockFile = $fp;
             $this->lockName = $lockname;
             $this->LOGGER->info('Lock acquired!');
             return true;
         }
         //Мы не получили блокировку...
         if ($wait) {
             $this->LOGGER->info('Lock not acquired, sleep for 1 sec');
             sleep(1);
         }
     } while ($wait);
     @fclose($fp);
     $this->LOGGER->info("Lock not setted.\n");
     return false;
 }
 /**
  * Извлекает тип и подтип фолдинга из его идентификатора:
  * [lib-p] => [lib, p]
  */
 public static function extractFoldedTypeAndSubtype($foldedUnique, &$type, &$subtype)
 {
     $tokens = explode('-', PsCheck::notEmptyString($foldedUnique), 3);
     $tokensCnt = count($tokens);
     switch ($tokensCnt) {
         case 1:
             $type = PsCheck::notEmptyString($tokens[0]);
             $subtype = '';
             break;
         case 2:
             $type = PsCheck::notEmptyString($tokens[0]);
             $subtype = PsCheck::notEmptyString($tokens[1]);
             break;
         default:
             PsUtil::raise('Invalid folded resource ident: [{}]', $foldedUnique);
     }
 }
Exemple #8
0
/**
 * Определим функцию, которая выполнит все действия - не будем лишними переменными засорять глобальное пространство
 */
function psExecuteAjaxAction()
{
    /*
     * Название действия должно быть в переменной запроса. Оно же - название класса, который будет выполнен.
     * Группа действия должны быть не обязательна, при определении действия группа нужна обязательно.
     */
    $actionName = RequestArrayAdapter::inst()->str(AJAX_ACTION_PARAM);
    $actionGroup = RequestArrayAdapter::inst()->str(AJAX_ACTION_GROUP_PARAM, 'client');
    if (!PsCheck::notEmptyString($actionName) || !PsCheck::notEmptyString($actionGroup)) {
        return json_error('Не передан код действия или его группа');
        //---
    }
    /*
     * Экземпляр класса действия - должен быть наследником AbstractAjaxAction
     */
    $action = null;
    /*
     * Поищем в проектных действиях, они для нас имеют больший приоритет
     */
    foreach (ConfigIni::ajaxActionsAbs($actionGroup) as $dirAbsPath) {
        $classPath = file_path($dirAbsPath, $actionName, PsConst::EXT_PHP);
        if (is_file($classPath)) {
            /*
             * Нашли файл. Загрузим и проверим, является ли он наследником AbstractAjaxAction
             */
            require_once $classPath;
            if (!PsUtil::isInstanceOf($actionName, AbstractAjaxAction::getClassName())) {
                continue;
                //---
            }
            $action = new $actionName();
            break;
            //---
        }
    }
    /*
     * Проверим, существует ли действие.
     * Для безопасности не будем писать детали обработки.
     */
    if (!$action || !$action instanceof AbstractAjaxAction) {
        return json_error('Действие не опеределено');
        //---
    }
    /*
     * Выполняем
     */
    $result = null;
    try {
        $result = $action->execute();
    } catch (Exception $e) {
        $result = $e->getMessage();
    }
    /*
     * Проверим результат
     */
    if ($result instanceof AjaxSuccess) {
        json_success($result->getJsParams());
    } else {
        json_error($result ? $result : 'Ошибка выполнения действия');
    }
}
 public function __construct($group)
 {
     $this->group = PsCheck::notEmptyString($group);
 }
Exemple #10
0
 /**
  * Метод возвращает формы слова во всех падежах
  * 
  * @param type $word
  * @return array - все склонения слова в виде массива, где под индексом 0 - оригинальное значение
  */
 public function getInflections($word)
 {
     $word = PsCheck::notEmptyString(trim($word));
     if ($this->CACHE->has($word)) {
         return $this->CACHE->get($word);
     }
     $this->LOGGER->info();
     $this->LOGGER->info('> Запрошено склонение для слова [{}]', $word);
     //$fileName = iconv('UTF-8', 'cp1251', $word);
     /*
      * Ищем в БД
      */
     $inflections = InflectsBean::inst()->getInflections($word);
     if (is_array($inflections)) {
         $this->LOGGER->info('< Cклонение для [{}] найдено в базе: {}', $word, array_to_string($inflections));
         return $this->CACHE->set($word, $inflections);
     }
     /*
      * Загружаем с сервиса
      */
     $inflections = $this->loadInflectionImpl($word);
     if (is_array($inflections) && count($inflections) == 7) {
         $this->LOGGER->info('< Склонение для [{}] успешно загружено: {}', $word, array_to_string($inflections));
         //Не забудем сохранить полеченное склонение для слова
         InflectsBean::inst()->saveInflections($inflections);
         return $this->CACHE->set($word, $inflections);
     }
     /*
      * Загрузить не удалось, возвращаем балванку
      */
     $inflections = array_fill(0, 7, $word);
     $this->LOGGER->info('< Склонение для [{}] не определено, возвращаем "болванку": {}', $word, array_to_string($inflections));
     return $this->CACHE->set($word, $inflections);
 }
Exemple #11
0
 private static function assertValidType($type)
 {
     return PsCheck::notEmptyString($type);
 }
Exemple #12
0
 /**
  * Метод очищает кеш или определённую группу кешей
  * 
  * @param string|null $group - код группы, которую нужно очистить
  */
 public function cleanCache($group = null)
 {
     if ($group === null) {
         /*
          * Полная очистка кеша
          */
         $this->LOGGER->info('--- Полная очистка кеша');
         $this->CACHE_LOCAL = array();
     } else {
         $group = PsCheck::notEmptyString($group);
         /*
          * Полная очистка кеша
          */
         $this->LOGGER->info("-- Очистка кеша по группе [{$group}]");
         unset($this->CACHE_LOCAL[$group]);
     }
     $this->CACHE_ENGINE->cleanCache($group);
 }
Exemple #13
0
 function __construct($what, $table, $where = null, $group = null, $order = null, $limit = null)
 {
     $this->table = PsCheck::tableName($table);
     $this->what = PsCheck::notEmptyString(self::concatQueryTokens('', $what));
     $this->addWhere($where)->setGroup($group)->setOrder($order)->setLimit($limit);
 }
Exemple #14
0
 public static function projectSrcCommonDir()
 {
     return PsCheck::notEmptyString(self::getPropCheckType(self::GROUP_PROJECT_INCLUDES, 'src-common', array(PsConst::PHP_TYPE_STRING)));
 }
Exemple #15
0
 public function assertExtension($ext)
 {
     if (PsCheck::notEmptyString($ext) !== $this->getExtension()) {
         PsUtil::raise('File with extention [.{}] is expected', $ext);
     }
 }
 /**
  * Методы, позволяющие зарегистрировать плагины.
  * 
  * @param string $tagName - название тега для вызова
  * @param string $pluginType - тип плагина
  */
 protected final function register($tagName, $pluginType)
 {
     check_condition(is_array($this->PLUGINS), 'Регистрация функций Smarty допускается только в методе #registerPluginsImpl');
     $this->PLUGINS[PsCheck::notEmptyString($tagName)] = PSSmartyTools::checkFunctionType($pluginType);
 }