/** @return PsProfilerInterface */ private function getProfiler($profilerId) { //Не будем выполнять get_file_name($profilerId), так как нужно вернуть профайлер максимально быстро if ($this->CAHCE->has($profilerId)) { return $this->CAHCE->get($profilerId); } check_condition($profilerId, 'Profiler id cannot be empty.'); if (!$this->enabled) { return $this->CAHCE->set($profilerId, new PsProfilerEmpty($profilerId)); } $di = $this->getProfilerDi($profilerId); $pr = null; //Проверим текущий размер профайлера if ($di->isMaxSize(ConfigIni::profilingMaxFileSize())) { $locked = PsLock::lock(__CLASS__ . "::compressProfiler({$profilerId})", false); if ($locked) { $this->compressProfiler($di); PsLock::unlock(); } else { //Разимер превышен и мы не смогли получить лок для дампа профайлера. Не будем в этот раз вести профайлинг. $pr = new PsProfilerEmpty($profilerId); } } return $this->CAHCE->set($profilerId, $pr ? $pr : new PsProfilerImpl($profilerId)); }
private function doClean(DirItem $srcDi) { foreach (DirManager::autogen()->getSubDirNames('images') as $dim) { $cacheKey = md5("[{$srcDi}]:[{$dim}]"); $this->CAHCE->remove($cacheKey); DirManager::autogen()->getHashedDirItem("images/{$dim}", $cacheKey, $cacheKey, SYSTEM_IMG_TYPE)->remove(); } }
/** * Метод возвращает формы слова во всех падежах * * @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); }
public function clean($group = null) { $this->LOGGER->info($group ? "Очистка кеша по группе [{$group}]" : 'Полная очистка кеша'); $this->CACHELITE->clean($group); if ($group) { //Эту группу больше не нужно валидировать $this->TREE->setGroupValidated($group); //Очистим ключи локального хранилища $keys = $this->CACHE->keys(); $removed = array(); $prefix = $this->localCacheGroup($group); foreach ($keys as $key) { if (starts_with($key, $prefix)) { $removed[] = $key; $this->CACHE->remove($key); } } if ($removed) { $this->LOGGER->info('В локальном кеше были удалены следующие ключи: {}.', concat($removed)); } } else { $this->CACHE->clear(); $this->TREE->setAllValidated('Полная очистка кеша'); } }
/** * Создание экземпляра класса для сущности фолдинга * @return FoldedClass */ public function getEntityClassInst($ident, $cache = true) { if (!$cache || !$this->INSTS_CACHE->has($ident)) { //Получим элемент - класс $php = $this->getResourceDi($ident, self::RTYPE_PHP); //Проверим, что это - файл check_condition($php->isFile(), 'Не найден класс реализации для сущности ' . $this->getTextDescr($ident)); //Проверим сущность на изменение $this->checkEntityChanged($ident); //Получим FoldedEntity, так как её потом нужно будет передать в конструктор $foldedEntity = $this->getFoldedEntity($ident); //Подключим класс, не будем заставлять трудиться класслоадер require_once $php->getAbsPath(); //Построим название класса на основе идентификатора сущности $baseFoldedClass = 'FoldedClass'; $class = $this->ident2className($ident); check_condition(PsUtil::isInstanceOf($class, $baseFoldedClass), "Класс для сущности {$foldedEntity} не является наследником {$baseFoldedClass}"); //Создаём акземпляр $inst = new $class($foldedEntity); //Отлогируем $this->LOGGER->info("Instance of {$class} created."); FoldedResourcesManager::onEntityAction(FoldedResourcesManager::ACTION_ENTITY_INST_CREATED, $this, $ident); return $cache ? $this->INSTS_CACHE->set($ident, $inst) : $inst; } return $this->INSTS_CACHE->get($ident); }
/** * Метод получает экземпляр класса и, если нужно, кеширует его. */ public static function getClassInstance($__DIR__, $subDir, $className, $parent, $caching = true) { if (!is_valid_file_name($className)) { return null; //--- } $className = get_file_name($className); if ($className == $parent) { //Абстрактный класс/интерфейс лежит рядом с классами реализации - пропустим его return null; } //Абсолютный путь к классу $classPath = file_path(array($__DIR__, $subDir), $className, PsConst::EXT_PHP); //Ключ кеширования $cacheKey = md5($classPath); $CACHE = $caching ? SimpleDataCache::inst(__CLASS__, __FUNCTION__) : null; if ($CACHE && $CACHE->has($cacheKey)) { return $CACHE->get($cacheKey); } $INST = null; if (is_file($classPath)) { //Подключим данный класс require_once $classPath; //Проверим, существует ли класс $rc = PsUtil::newReflectionClass($className, false); $INST = $rc && $rc->isSubclassOf($parent) ? $rc->newInstance() : null; } if ($CACHE && $INST) { $CACHE->set($cacheKey, $INST); } return $INST; }
/** * Основной метод, выполняющий построение контроллера для просмотра постов. * Контроллер может быть отображен в двух случаях: * 1. На странице с просмотром всех постов * 2. На странице с рубрикой * * @return ShowcasesControllerPanel */ private function getScPanel($postType, Rubric $rubric = null) { $key = $postType . '-' . ($rubric ? $rubric->getIdent() : ''); if (!$this->CACHE->has($key)) { $plugins[] = $this->getBaseControllerIdents(); if ($rubric) { $plugins[] = Mappings::RUBRIC_2_SCCONTROLLERS($postType)->getMappedEntitys($rubric->getIdent()); } $insts = $this->getUserAcessibleClassInsts(to_array_expand($plugins)); $ctxt = new ShowcasesControllerCtxt($rubric); $result = array(); /** @var ShowcasesControllerItem */ foreach ($insts as $ident => $inst) { $inst->doProcess($ctxt); $result[$ident] = $inst; } $this->CACHE->set($key, new ShowcasesControllerPanel($result)); } return $this->CACHE->get($key); }
/** * Метод возвращает сущность фолдинга по заданному коду * * @return FoldedEntity Сущность, соответствующая заданному коду */ public function getFoldedEntityByDbCode($code) { return $this->CACHE->has($code) ? $this->CACHE->get($code) : $this->CACHE->set($code, FoldedStorageInsts::getFoldedEntityByUnique(FoldingBean::inst()->getUniqueByCode($code))); }
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; }
protected function __construct() { $this->LOGGER = PsLogger::inst(get_called_class()); $this->CACHE = SimpleDataCache::inst(); }
protected function __construct() { $this->LOGGER = PsLogger::inst(__CLASS__); $this->PROFILER = PsProfiler::inst(__CLASS__); $this->CACHE = SimpleDataCache::inst(); $this->DM = DirManager::autoNoDel(DirManager::DIR_FORMULES); }
public static function getContentProvider($item) { $ident = IdHelper::ident($item); $CACHE = SimpleDataCache::inst(__CLASS__); return $CACHE->has($ident) ? $CACHE->get($ident) : $CACHE->set($ident, self::makeProvider($item)); }
/** * Создание экземпляра класса для сущности фолдинга. * Если по каким-либо причинам экземпляр не может быть создан - выбрасываем ошибку. * * @return FoldedClass */ public final function getEntityClassInst($ident, $cache = true) { /* @var $CACHE SimpleDataCache */ $CACHE = $cache ? SimpleDataCache::inst($this->unique('CLASSES-CACHE')) : null; //--- if ($CACHE && $CACHE->has($ident)) { return $CACHE->get($ident); } $classPath = $this->getClassPath($ident); //Подключим класс, не будем заставлять трудиться класслоадер require_once $classPath; //Построим название класса на основе идентификатора сущности $className = $this->ident2className($ident); if (!PsUtil::isInstanceOf($className, FoldedClass::getCalledClass())) { return PsUtil::raise('Класс для сущности {} не является наследником {}', $this->getTextDescr($ident), FoldedClass::getCalledClass()); } //Получим FoldedEntity, так как её потом нужно будет передать в конструктор $foldedEntity = $this->getFoldedEntity($ident); //Создаём экземпляр $inst = new $className($foldedEntity); //Отлогируем $this->LOGGER->info('Instance of {} created.', $className); FoldedResourcesManager::onEntityAction(FoldedResourcesManager::ACTION_ENTITY_INST_CREATED, $this, $ident); return $CACHE ? $CACHE->set($ident, $inst) : $CACHE; }
protected function __construct() { $this->LOGGER = PsLogger::inst(__CLASS__); $this->PROFILER = PsProfiler::inst(__CLASS__); $this->CACHE = SimpleDataCache::inst(); $this->DM = DirManager::formules(); }