/** * Метод разбирает файл с ребусами, который выглядит как: * * ребус 1 * ответ 1.1 * ответ 1.2 * * ребус 2 * ответ 2.1 * ответ 2.2 * * @return type */ private function parseAnswersFile(DirItem $di) { $result = array(); $lines = explode("\n", trim($di->getFileContents(false))); $current = null; foreach ($lines as $line) { $line = trim($line); if ($line && !$current) { //Начинается новый ребус $current = $line; $result[$current] = array(); } else { if ($line && $current) { //Ответ на ребус $result[$current][] = $line; } else { if (!$line && $current) { //Пробел, закончили ребус $current = null; } } } } if ($this->LOGGER->isEnabled()) { $this->LOGGER->info('Rebuses of {}:', $di->getRelPath()); $this->LOGGER->info(print_r($result, true)); $this->LOGGER->info(); } return $result; }
public static final function finalize(PsLoggerInterface $LOGGER, $CONTENT) { //Проверим на пустоту if (isEmpty($CONTENT)) { return $CONTENT; } $call = ++self::$call; //Создадим экземпляр финализатора и вызовем его $class = get_called_class(); $PROFILER = PsProfiler::inst($class); $inst = new $class($LOGGER, $PROFILER); $PROFILER->start(__FUNCTION__); $SECUNDOMER = Secundomer::startedInst(); $LOGGER->infoBox(">>> CALLED {$call}. {$class}"); try { $CONTENT = $inst->doFinalize($CONTENT); $PROFILER->stop(); $SECUNDOMER->stop(); } catch (Exception $ex) { $PROFILER->stop(false); $LOGGER->infoBox("Exception occured while calling {$class}::finalize. Message: " . $ex->getMessage()); throw $ex; } $LOGGER->infoBox("<<< CALL {$call}. {$class} FINISHED IN " . $SECUNDOMER->getAverage() . ' seconds'); return $CONTENT; }
private function processAnswersFile() { $result = array(); $lines = explode("\n", trim($this->getAnswersDI()->getFileContents(false))); $current = null; foreach ($lines as $line) { $line = trim($line); if ($line && !$current) { //Начинается новый ребус $current = $line; $result[$current] = array(); } else { if ($line && $current) { //Ответ на ребус $result[$current][] = $line; } else { if (!$line && $current) { //Пробел, закончили ребус $current = null; } } } } $this->LOGGER->info(print_r($result, true)); return $result; }
/** * Основной метод, вызываемый для регистрации плагинов, предоставляемых данным классом для выполнения смарти-функций */ public final function registerPlugins(Smarty $smarty) { $this->LOGGER->info('Регистрируем плагины класса [{}]', $this->CLASS); foreach ($this->getPlugins() as $tagName => $pluginType) { PSSmartyTools::checkFunctionType($pluginType); if (array_key_exists($pluginType, $smarty->registered_plugins) && array_key_exists($tagName, $smarty->registered_plugins[$pluginType])) { $this->LOGGER->info('Не зарeгистрирован плагин [{}]', 'smarty_' . $pluginType . '_' . $tagName); } else { $smarty->registerPlugin($pluginType, $tagName, array($this, 'do_' . $pluginType . '_' . $tagName)); $this->LOGGER->info('Зарeгистрирован плагин [{}]', 'smarty_' . $pluginType . '_' . $tagName); } } }
public final function ctxtAction(AbstractContext $ctxt, $isSetted) { if (!$this->isOurContext($ctxt)) { return; //--- } if ($isSetted) { $this->CTXTS[] = $ctxt; } else { check_condition($this->CTXTS, 'Попытка сбросить контекст, который не был стартован'); $lastCtxt = array_pop($this->CTXTS); check_condition($lastCtxt === $ctxt, 'Сбрасываемый контекст не соответствует установленному: ' . get_class($lastCtxt) . '-' . get_class($ctxt)); } $this->LOGGER->info("{} context: {} - {}", $isSetted ? '+' : '-', get_class($ctxt), $ctxt->getContextIdent()); }
/** * Метод возвращает формы слова во всех падежах * * @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); }
/** * Метод утверждает, что мы можем выполнять модификацию пользователя, что возможно, если: * 1. Данный пользователь является нами * 2. Мы авторизованы под администратором */ protected final function assertCanEdit($__FUNCTION__, $doAssert = true) { if ($doAssert) { $this->LOGGER->info('[{}] {}({})', $this->userId, __FUNCTION__, $__FUNCTION__); check_condition($this->canEdit, 'Cannot call ' . $__FUNCTION__ . ' for user ' . $this->userId); } }
/** * Генерация комментариев к постам. * rootCount - кол-во root комментариев * childCount - кол-во дочерних комментариев, при этом они привязываются случайным образом * postType - если передан, то комментарии будут сгенерированы только к постам этого типа * postId - для генерации комменариев к конкретному посту * takeTextFromPost - признак, брать ли текст комментариев из тела поста */ public final function generateComments($rootCount = 20, $childCount = 50, $postType = null, $postId = null, $takeTextFromPost = true) { $cproc = $this->getCommentsProcessor($postType); /* @var $proc PostsProcessor */ foreach ($cproc as $proc) { $this->LOGGER->info("<<<CREATING COMMENTS FOR POSTS OF TYPE [" . $proc->getPostType() . "]>>>"); if ($postId) { $posts[] = $proc->getPost($postId); } else { $posts = $proc->getPosts(); } /* @var $post AbstractPost */ foreach ($posts as $post) { $this->LOGGER->info("Creating comments for post " . $post->getPostType() . '|' . $post->getName()); for ($i = 1; $i <= $rootCount; $i++) { $proc->getDiscussionController()->saveMessage($post->getId(), null, $this->getText($proc, $post->getId(), $takeTextFromPost), null, PsUser::inst(TESTBean::inst()->getRandomUserId())); } for ($i = 1; $i <= $childCount; $i++) { $commentsTable = $proc->dbBean()->getCommentsTable(); $parentId = TESTBean::inst()->getRandomCommentId($commentsTable, $post->getId()); $proc->getDiscussionController()->saveMessage($post->getId(), $parentId, $this->getText($proc, $post->getId(), $takeTextFromPost), null, PsUser::inst(TESTBean::inst()->getRandomUserId())); } } } }
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('Полная очистка кеша'); } }
/** * Предварительная обработка страницы - самое время выполнить сабмит формы, редирект и остальные подобные вещи */ private final function postProcess() { //Проверим и сменим состояние $this->changeState(self::STATE_STARTED, self::STATE_FINISHED); //Устанавливаем контекст $BUILDER_CTXT = PageBuilderContext::getInstance(); //Проверим, что наш контекст не был сброшен check_condition(__CLASS__ == $BUILDER_CTXT->getContextIdent(), 'Unexpected ' . get_class($BUILDER_CTXT) . ': ' . $BUILDER_CTXT->getContextIdent()); //Получим параметры страницы $pagePrams = new PageParams($BUILDER_CTXT->finalizeTplContent(null)); //Сброим контекст, он нам больше не нужен $BUILDER_CTXT->dropContext(); try { //Вызываем завершающую обработку страницы $result = $this->postProcessImpl($pagePrams, RequestArrayAdapter::inst()); //Останавливаем профайлер $sec = $this->PROFILER->stop(); //Отлогируем $this->LOGGER->info('Page build done in {} sec', $sec->getTime()); //Вернём return $result; //--- } catch (Exception $ex) { $this->PROFILER->stop(false); throw $ex; } }
/** * В конструкторе зарегистрируем все страницы */ protected final function __construct() { $class = get_called_class(); $basic = __CLASS__ == $class; //Логгер $this->LOGGER = PsLogger::inst(__CLASS__); $this->LOGGER->info('USING {} PLUGIN PROVIDER: {}', $basic ? 'SDK' : 'CUSTOM', $class); //Стартуем профайлер $this->PROFILER = PsProfiler::inst(__CLASS__); $this->PROFILER->start('Loading plugins'); //Регистрируем фолдинги SDK $this->LOGGER->info(); $this->LOGGER->info('PLUGINS SDK:'); $this->registerSdkSmartyPlugins(); //Если используем не SDK провайдер, вызываем регистратор if (!$basic) { $this->LOGGER->info(); $this->LOGGER->info('PLUGINS PROJECT:'); $this->registerProjectSmartyPlugins(); } //Останавливаем профайлер $sec = $this->PROFILER->stop(); //Логируем $this->LOGGER->info(); $this->LOGGER->info('COLLECTING TIME: {} sec', $sec->getTotalTime()); }
/** * В конструкторе зарегистрируем все страницы */ protected final function __construct() { $class = get_called_class(); $basic = __CLASS__ == $class; //Логгер $this->LOGGER = PsLogger::inst(__CLASS__); $this->LOGGER->info('USING {} STORAGE: {}', $basic ? 'SDK' : 'CUSTOM', $class); //Стартуем профайлер $this->PROFILER = PsProfiler::inst(__CLASS__); $this->PROFILER->start('Registering Web pages'); //Регистрируем страницы SDK $this->LOGGER->info(); $this->LOGGER->info('PAGES SDK:'); $this->registerSdkPages(); //Если используем не SDK провайдер, вызываем регистратор if (!$basic) { $this->LOGGER->info(); $this->LOGGER->info('PAGES PROJECT:'); $this->registerProjectPages(); } //Проведём инициализацию $this->LOGGER->info(); $this->LOGGER->info('INITIALIZING...'); $this->init(); //Останавливаем профайлер $sec = $this->PROFILER->stop(); //Логируем $this->LOGGER->info(); $this->LOGGER->info('REGISTERING TIME: {} sec', $sec->getTotalTime()); }
/** * В конструкторе зарегистрируем все страницы */ protected final function __construct() { //Инициализируем хранилище, чтобы честно замерять время создания регистрации самих экземпляров FoldedStorage::init(); $class = get_called_class(); $basic = __CLASS__ == $class; //Логгер $this->LOGGER = PsLogger::inst(__CLASS__); $this->LOGGER->info('USING {} STORAGE: {}', $basic ? 'SDK' : 'CUSTOM', $class); //Стартуем профайлер $this->PROFILER = PsProfiler::inst(__CLASS__); $this->PROFILER->start('Loading folding insts'); //Регистрируем фолдинги SDK $this->LOGGER->info(); $this->LOGGER->info('FOLDINGS SDK:'); $this->registerSdkFoldings(); //Если используем не SDK провайдер, вызываем регистратор if (!$basic) { $this->LOGGER->info(); $this->LOGGER->info('FOLDINGS PROJECT:'); $this->registerProjectFoldings(); } //Отсортируем фолдинги по идентификаторам ksort($this->FOLDINGS); //Останавливаем профайлер $sec = $this->PROFILER->stop(); //Логируем $this->LOGGER->info(); $this->LOGGER->info('COLLECTING TIME: {} sec', $sec->getTotalTime()); }
protected function __construct() { $this->CACHE = new SimpleDataCache(); $this->LOGGER = PsLogger::inst(__CLASS__); if ($this->LOGGER->isEnabled()) { PsShotdownSdk::registerDestructable($this, PsShotdownSdk::FoldedResourcesManager); } }
private function __construct() { $this->CLASS = get_called_class(); $this->CACHE = new SimpleDataCache(); $this->DBTYPE = $this->getUploadType(); $this->LOGGER = PsLogger::inst($this->CLASS); $this->LOGGER->info('Instance created. Work with db ? {}. Is autonomous ? {}.', var_export($this->isStoreToDb(), true), var_export($this->isAutonomous(), true)); $this->LOGGER->info(); }
/** * Метод должен быть вызван перед подключением библиотеки для предотвращения повторного подключения * Пример использования: * * if ($this->isAlreadyIncluded(__FUNCTION__)) { * return;//--- * } * * @param string $libName - название подключаемой библиотеки * @return boolean - признак, нужно ли подключать данную библиотеку */ protected final function isAlreadyIncluded($libName) { if (in_array($libName, $this->INCLUDED)) { return true; } $this->INCLUDED[] = $libName; $this->LOGGER->info('+ {}', $libName); return false; }
protected final function __construct() { $this->LOGGER = PsLogger::inst(__CLASS__); $class = 'Memcache'; if (!class_exists($class)) { $this->LOGGER->info($class . ' class is not exists!'); return; //--- } $this->MEMCACHE = new $class(); if (!@$this->MEMCACHE->connect('127.0.0.1', 11211)) { $this->LOGGER->info('Could not connect to localhost!'); $this->MEMCACHE = null; return; //--- } $this->LOGGER->info($class . ' is enabled.'); }
/** * Метод регистрирует плагины смарти для вызова * * @param Smarty $smarty * @param PsLoggerInterface $LOGGER */ public final function bind(Smarty $smarty, PsLoggerInterface $LOGGER) { foreach ($this->getPlugins() as $tagName => $pluginType) { $needAdd = !array_key_exists($pluginType, $smarty->registered_plugins) || !array_key_exists($tagName, $smarty->registered_plugins[$pluginType]); if ($needAdd) { $smarty->registerPlugin($pluginType, $tagName, array($this, 'do_' . $pluginType . '_' . $tagName)); } $LOGGER->info(' [{}] {} {}', $pluginType, 'smarty_' . $pluginType . '_' . $tagName, $needAdd ? '' : ' (NOT ADDED)'); } }
/** * Метод строит композицию временной шкалы. * Построенная композиция будет автоматически сохранена в кеш. * Методы были разделены осознанно, возможно нам нужно будет получить именно композицию. * * @return TimeLineItemsComposite */ public final function getTimeLineComposition(ArrayAdapter $params) { $cacheKey = $this->prepareBuildCompositionParamsAndGetCahceKey($params); $this->LOGGER->info('Строим хронологическую шкалу, данные: ' . $cacheKey); $this->profilerStart(__FUNCTION__); try { $composition = $this->buildComposition($params); check_condition($composition instanceof TimeLineItemsComposite, 'Некорректно построена хронологическая шкала'); $this->profilerStop(); $this->LOGGER->info('Шкала успешно построена'); PSCacheGroups::TIMELINES()->saveToCache($composition->getTimeLineJson(), $cacheKey); $this->LOGGER->info('Шкала сохранена в кеш под ключём: ' . $cacheKey); return $composition; } catch (Exception $ex) { $this->profilerStop(false); $this->LOGGER->info('Ошибка построения шкалы: ' . $ex->getMessage()); throw $ex; } }
private function __construct() { $this->CLASS = get_called_class(); $this->CACHE = new SimpleDataCache(); $this->DBTYPE = $this->isStoreToDb() ? $this->CLASS : null; $this->DIR_MANAGER = DirManager::inst(array(ConfigIni::uploadsDirRel(), $this->CLASS)); $this->LOGGER = PsLogger::inst($this->CLASS); $this->LOGGER->info('Instance created. Work with db ? {}. Is autonomous ? {}.', var_export($this->isStoreToDb(), true), var_export($this->isAutonomous(), true)); $this->LOGGER->info('Upload dir: [{}].', $this->DIR_MANAGER->relDirPath()); $this->LOGGER->info(); }
/** * Редактирование сущности фолдинга */ public function editEntity($ident, ArrayAdapter $params) { $this->assertAdminCanDo(__FUNCTION__, $ident); foreach ($this->RESOURCE_TYPES_ALLOWED as $type) { if ($params->has($type)) { $this->getResourceDi($ident, $type)->writeToFile($params->str($type), true); } } //Сущность могла стать видна из-за редактирования записи в базе $this->LOGGER->info('Очищаем кеш доступных сущностей'); $this->IDENTS = null; $this->onEntityChanged($ident); }
/** * Основной метод, получающий абсолютный путь к классу. * * @param str $class * @return str - Путь к файлу */ private function getClassPathImpl($class) { /* @var $classPathDir AutoloadDir */ foreach ($this->DIRS as $classPathDir) { //ИЩЕМ КЛАСС $path = $classPathDir->getClassPath($class); if ($path) { /* * Мы нашли класс! * Если он отмечен, как исключённый для всех - сборосим список исключённых. * Могло так случиться, что класс загружался без подключённой директорией (например admin). */ if ($this->isCommonExcluded($class)) { $this->LOGGER->info("Class [{$class}] was marked as excluded, but now found in {$classPathDir}. Clearing excluded."); $this->cleanCommonExcluded(); } return $path; } } //ПОПРОБУЕМ ВОСПОЛЬЗОВАТЬСЯ ФОЛДИНГАМИ $path = Handlers::tryGetFoldedEntityClassPath($class); if ($path) { $this->LOGGER->info("Class path for [{$class}] found with folded resources."); return $path; } //МЫ НЕ НАШЛИ НАШ КЛАСС В ПУТЯХ, А МОЖЕТ ОН ИСКЛЮЧЁН ДЛЯ ВСЕХ? if ($this->isCommonExcluded($class)) { $this->LOGGER->info("Class [{$class}] is common excluded."); return null; } //КЛАСС НЕ ЯВЛЯЕТСЯ КЛАССОМ СУЩНОСТИ ФОЛДИНГА. ПЕРЕСТРОИМ КЛАССПАСЫ ДЛЯ ЗАКЕШОРОВАННЫХ ДИРЕКТОРИЙ ИЛИ ОТМЕТИМ КЛАСС, КАК ИСКЛЮЧЁННЫЙ /* @var $classPathDir AutoloadDir */ foreach ($this->DIRS as $classPathDir) { if ($classPathDir->isRebuilded()) { //Данную директорию уже перезагружали, в ней класса точно нет continue; } //Если файл не найден, но при этом класспас не перестраивался, то необходимо поискать его заново $this->LOGGER->info("Class [{$class}] not excluded, need to check {$classPathDir} again."); $path = $classPathDir->rebuild()->getClassPath($class); if ($path) { //Ура, наши класс в одной из директорий $this->LOGGER->info("Class [{$class}] found for {$classPathDir} after rebuild."); return $path; } } $this->saveCommonExcluded($class); $this->LOGGER->info("Class [{$class}] is marked as excluded, null is returned."); return null; }
/** * В конструкторе пробежимся по всем хранилищам и соберём все фолдинги */ protected function __construct() { $this->LOGGER = PsLogger::inst(__CLASS__); $this->PROFILER = PsProfiler::inst(__CLASS__); /* * Инициалилизируем коллекцию */ $this->PROVIDERS = array(); /* * Собираем полный список доступных хранилищ и менеджеров фолдингов в них */ $providerClasses = ConfigIni::getPropCheckType(ConfigIni::GROUP_FOLDINGS, 'providers', array(PsConst::PHP_TYPE_ARRAY, PsConst::PHP_TYPE_NULL)); $providerClasses = to_array($providerClasses); $providerClasses[] = FoldingsProviderSdk::calledClass(); $this->LOGGER->info('Providers: {}', array_to_string($providerClasses)); foreach ($providerClasses as $provider) { if (in_array($provider, $this->PROVIDERS)) { $this->LOGGER->info('[-] {} - {}', $provider, 'is already registered'); continue; //--- } if (!class_exists($provider)) { $this->LOGGER->info('[-] {} - {}', $provider, 'is not included'); continue; //--- } if (!PsUtil::isInstanceOf($provider, FoldingsProviderAbstract::calledClass())) { $this->LOGGER->info('[-] {} - {}', $provider, 'is not instance of ' . FoldingsProviderAbstract::calledClass()); continue; //--- } $this->LOGGER->info('[+] {}', $provider); $this->PROVIDERS[] = $provider; /* * Для каждого хранилища загружаем список входящих в него фолдингов */ $this->PROFILER->start($provider . '::list'); /* @var $folding FoldedResources */ foreach ($provider::listFoldings() as $folding) { $funique = $folding->getUnique(); if (array_key_exists($funique, $this->UNIQUE_2_PROVIDER)) { raise_error(PsStrings::replaceWithBraced('Folding {} is provided by: {}, {}', $funique, $this->UNIQUE_2_PROVIDER[$funique], $provider)); } $this->LOGGER->info(' [>] {}', $funique); $this->UNIQUE_2_PROVIDER[$funique] = $provider; $this->UNIQUE_2_FOLDING[$funique] = $folding; } $this->PROFILER->stop(); } }
public function CreateSprite(CssSprite $sprite) { if ($sprite->exists()) { return; //--- Спрайт существует } $this->LOGGER->info("Waiting to make {$sprite}"); PsLock::lockMethod(__CLASS__, __FUNCTION__); try { if ($sprite->exists()) { $this->LOGGER->info('Sprite was created in another thread, skipping'); } else { $this->PROFILER->start('Sprite creation'); $this->CssSpriteGen->CreateSprite($sprite); $this->LOGGER->info('Sprite was successfully created, path: ' . $sprite->getCssDi()->getAbsPath()); $this->PROFILER->stop(); } } catch (Exception $ex) { PsLock::unlock(); throw $ex; } PsLock::unlock(); }
private function checkCombination(array $char2num) { $expr = PsStrings::replaceMap($this->EXPR, $char2num); $res = PsMathEvaluator::inst()->e($expr); if ($res === false) { $error = 'Ошибка обработки ребуса: ' . PsMathEvaluator::inst()->lastError(); $this->LOGGER->info($error); raise_error($error); } if ($res == 0) { $combination = PsStrings::replaceMap($this->REBUS, $char2num); $this->COMBINATIONS[] = $combination; $this->LOGGER->info($combination); } ++$this->cnt; }
/** * Копирует ячейки из картинки-источника в картинку-мозайку. * * @param array $INFO - информация о картинке * @param array $cells - ячейки из БД, которые будут скопированы * @param type $userId - код пользователя, к которому ячейки будут привязаны */ private function copyCells(array $cells, $userId = null) { //Проверим, есть ли сейчас "чистая" картинка, на которую мы будем копировать ячейки if (!$this->diDst()->isImg()) { SimpleImage::inst()->create($this->width, $this->height, self::BG_COLOR)->save($this->diDst())->close(); } if (empty($cells)) { return; //--- } if ($this->LOGGER->isEnabled()) { $this->LOGGER->info('Copy cells of image ' . $this->id . ', user for bind: ' . var_export($userId, true)); $this->LOGGER->info('Not processed cells: ' . print_r($cells, true)); } PsUtil::startUnlimitedMode(); $this->PROFILER->start('Copy cells of img ' . $this->id); //1. Разберёмся с ячейками - привяжем к пользователю те их них, которые никому не принадлежат foreach ($cells as $cell) { $n_part = 1 * $cell['n_part']; $owned = !!$cell['owned']; //Ячейка должна кому-то принадлежать, либо быть привязана к переданному пользователю check_condition($owned || is_numeric($userId), "Ячейка {$this->id}.{$n_part} никому не принадлежит."); if (!$owned) { //Если ячейка уже привязана к пользователю, то не будем лишний раз дёргать базу $this->LOGGER->info('{}. Cell binded to user {}', $n_part, $userId); $this->BEAN->markAsOwned($userId, $this->id, $n_part); } } //2. Копируем ячейки, предварительно объединив их $srcImg = SimpleImage::inst()->load($this->diSrc()); $dstImg = SimpleImage::inst()->load($this->diDst()); $unioned = MosaicImageCellsCompositor::union($cells, $this->cellWidth, $this->cellHeight, false); foreach ($unioned as $cell) { $x1 = $cell[0]; $y1 = $cell[1]; $x2 = $cell[2]; $y2 = $cell[3]; $w = $x2 - $x1; $h = $y2 - $y1; $dstImg->copyFromAnother($srcImg, $x1, $y1, $x1, $y1, $w, $h)->save(); $this->LOGGER->info('Copied rectangle: {}x{}-{}x{}', $x1, $y1, $x2, $y2); } $srcImg->close(); $dstImg->close(); $this->PROFILER->stop(); }
/** * Метод отпускает полученную ранее блокировку. */ private function doUnlock() { if ($this->lockCnt > 1) { $this->lockCnt--; $this->LOGGER->info('Lock ident [{}] counter decreased to {}.', $this->lockName, $this->lockCnt); return; //--- } if ($this->lockCnt == 1) { $this->lockCnt--; flock($this->lockFile, LOCK_UN); fclose($this->lockFile); $this->LOGGER->info("Lock [{$this->lockName}] released!\n"); $this->lockFile = null; $this->lockName = null; } }
/** * Непосредственное наполнение */ private function doFill($filterName = null) { $this->LOGGER->info("Loading full content of dir [{}] with [{}] filter.", $this->PATH, PsUtil::toString($filterName)); $this->PROFILER->start('doFill'); /* * На данный момент у нас все директории собраны, остаётся только пробежаться по ним * и взять всё необходимое. * При этом нужно выполнить array_values, так как getDirContent возвращает ассоциативный массив, * а файлы в директориях могут повторяться. */ $RESULT = array(); foreach ($this->DIRS as $dirPath) { $items = DirManager::inst($dirPath)->getDirContent(null, $filterName); $RESULT = array_merge($RESULT, array_values($items)); } $this->LOGGER->info('Loading finished, items count: {}. Taken time: {}sec.', count($RESULT), $this->PROFILER->stop()->getTime()); $this->LOGGER->info(''); return $RESULT; }
/** * Перестроение спрайта * * @return CssSprite */ public function rebuild($force = true) { if (!$this->rebuilded && ($force || !$this->exists())) { //Отлогируем $this->LOGGER->info("REBUILDING SPRITE FOR [{$this->name}]"); //Поставим признак перестроенносьти $this->rebuilded = true; //Сбросим закешированные элементы, так как css файл мог поменяться $this->items = null; //Удалим .css файл $this->cssDi->remove(); //Перестроим CssSpritesCreator::inst()->CreateSprite($this); //Создадим .css файл, даже если он не был создан в процессе построения. Просто у нас нет картинок в $spritable. $this->cssDi->touch(); } return $this; //--- }
/** * Метод выполняет фактическую замену TEX тега на его представление в виде картинки или спрайта. * * @param str $original \[v_{\text{cp}}=\frac{\Delta S}{\Delta t}\] * @param str $formula v_{\text{cp}}=\frac{\Delta S}{\Delta t} * @param str $type block or inline */ public function _replaceInTextImpl($original, $formula, $isBlock) { $type = $isBlock ? 'block' : 'inline'; $replace = ''; if ($formula) { /* * Проверяем, разрешена ли замена формул на спрайты и есть ли сейчас контекст. * Если всё выполнено, то это вовсе не означает, что необходимый спрайт подключен и есть * спрайт для данной формулы. */ if (PsDefines::isReplaceFormulesWithSprites() && FoldedContextWatcher::getInstance()->getSpritableContext()) { $replace = CssSpritesManager::getFormulaSprite(FoldedContextWatcher::getInstance()->getSpritableContext()->getSpritable(), $formula, array('TeX', $type)); } /* * Если спрайта не нашлось, то заменяем на картинку. */ if (!$replace) { $imgDi = $this->getImgDi($formula); $imgPath = $imgDi ? $imgDi->getRelPath() : null; if ($imgPath) { $replace = PsHtml::img(array('src' => $imgPath, 'class' => "TeX {$type}", 'alt' => '')); } else { $replace = $original; } } } /* * Логирование */ if ($this->LOGGER->isEnabled()) { $this->LOGGER->info(++$this->replaced . ". Replacing {$type} TeX"); $this->LOGGER->info("FULL: {$original}"); $this->LOGGER->info("CONTENT: {$formula}"); $this->LOGGER->info("SAVED: {$formula}"); $this->LOGGER->info("REPLACED: {$replace}"); $this->LOGGER->info("\n"); } return $replace; }