/** * Процесс выполняет периодические задачи cron * * @param array $argv */ function executeProcess(array $argv) { $SYNC_DIR = 'd:/Zona Downloads/Архив пранкоты/'; $lists = DirManager::inst(__DIR__)->getDirContent('m3u', PsConst::EXT_M3U); $filesCopied = DirItem::inst(__DIR__, 'all_copied', 'list')->remove()->touch(); $filesSkipped = DirItem::inst(__DIR__, 'all_skipped', 'list')->remove()->touch(); $destDir = DirManager::inst(__DIR__, 'dest')->clearDir()->makePath(); /* @var $list DirItem */ foreach ($lists as $name => $list) { $name = mb_convert_encoding($name, 'UTF-8', 'cp1251'); dolog("+ {$name}"); foreach ($list->getFileLines() as $newFile) { $newFile = mb_convert_encoding($newFile, 'UTF-8', 'UTF-8'); if (starts_with($newFile, '#')) { dolog(" - {$newFile}"); continue; //--- } $absPath = next_level_dir($SYNC_DIR, $newFile); $absPath = iconv('UTF-8', 'cp1251', $absPath); $isFile = is_file($absPath); dolog(" + {$newFile} ? {}", var_export($isFile, true)); if (!$isFile) { $filesSkipped->writeLineToFile($absPath); continue; //--- } $fileName = iconv('UTF-8', 'cp1251', basename($newFile)); copy($absPath, $destDir->absFilePath(null, $fileName)); $filesCopied->writeLineToFile($absPath); } //print_r($list->getFileLines()); } }
/** * @covers AutoloadDir::isRebuilded */ public function testIsRebuilded() { //Запросим путь к тестовому классу, чтобы он уже наверняка был найден на момент запроса. $this->assertNotNull(Autoload::inst()->getClassPath(ClassA::get__CLASS__())); //Мы должны найти нагш класс без перезагрузки, так как уже нашли его ранее $cpDir = new AutoloadDir(DirItem::inst(Autoload::DIR_TESTS)); $this->assertNotNull($cpDir->getClassPath(ClassA::get__CLASS__())); $this->assertFalse($cpDir->isRebuilded()); }
function saveResult2Html($tplName, $params = null, $__DIR__ = __DIR__, $htmlName = 'results.html', $title = null) { $tplName = ensure_file_ext($tplName, 'tpl'); $pageClass = cut_string_end($tplName, '.tpl'); $body = PSSmarty::template("hometools/{$tplName}", $params)->fetch(); $pageParams['title'] = $title == null ? 'Результаты' : $title; $pageParams['body'] = $body; $pageParams['class'] = $pageClass; $html = PSSmarty::template('hometools/page_pattern.tpl', $pageParams)->fetch(); $htmlName = ensure_file_ext($htmlName, 'html'); DirItem::inst($__DIR__, $htmlName)->writeToFile($html, true); }
public static function format($__CLASS__, $__FUNCTION__, array $arguments) { if (!array_key_exists($__CLASS__, self::$MESSAGES)) { /* * Защита от зацикливания */ self::$MESSAGES[$__CLASS__] = null; /* * Определим, где расположен класс с сообщениями */ $classPath = Autoload::inst()->getClassPath($__CLASS__); if (!$classPath) { return PsUtil::raise('Группа сообщений {} не зарегистрирована', $__CLASS__); } /* * Получим DirItem сообщений для этого класса */ $messagesDi = DirItem::inst(dirname($classPath), $__CLASS__, PsConst::EXT_MSGS); if (!$messagesDi->isFile()) { return PsUtil::raise('Файл с сообщениями {} не существует', $messagesDi->getName()); } /* * Распарсим сообщения из файла */ self::$MESSAGES[$__CLASS__] = $messagesDi->getFileAsProps(); } /* * Проверим на зацикливание */ if (self::$MESSAGES[$__CLASS__] === null) { PsUtil::raise('Зацикливание при попытке получить сообещние {}::{}', $__CLASS__, $__FUNCTION__); } /* * Проверим на существование самого сообщения */ if (!array_key_exists($__FUNCTION__, self::$MESSAGES[$__CLASS__])) { return PsUtil::raise('Сообщение {}::{} не существует', $__CLASS__, $__FUNCTION__); } /* * Заменим макросы {} и вернём сообщение */ return PsStrings::replaceMapBracedKeys(self::$MESSAGES[$__CLASS__][$__FUNCTION__], $arguments); }
function executeProcess(array $argv) { $rebuses = DirItem::inst(__DIR__, 'rebuses.txt')->getTextFileAdapter(); $MR = PsMathRebus::inst(); $result = array(); foreach ($rebuses->getLines() as $rebus) { if (starts_with($rebus, '#')) { continue; //--- } $rebus = $MR->normalize($rebus); switch ($MR->rebusState($rebus)) { case PsMathRebus::STATE_HAS_ANSWERS: dolog("Take rebus answers: {$rebus}"); $result[$rebus] = $MR->rebusAnswers($rebus); break; case PsMathRebus::STATE_NO_ANSWERS: dolog("Skipping rebus: {$rebus}"); $result[$rebus] = array(); break; case PsMathRebus::STATE_NOT_REGISTERED: dolog("Processing rebus: {$rebus}"); $result[$rebus] = PsMathRebusSolver::solve($rebus); break; } } $ansDI = DirItem::inst(__DIR__, 'answers.txt'); $ansDI->remove(); foreach ($result as $rebus => $answers) { $ansDI->writeLineToFile($rebus); foreach ($answers as $answer) { $ansDI->writeLineToFile($answer); } $ansDI->writeLineToFile(); } /* * Если передан параметр копирования, то скопируем файл после обработки */ if (1 == array_get_value(1, $argv, 0)) { dolog('Copy from [{}] to [{}]', $ansDI->getRelPath(), $MR->getAnswersDI()->getRelPath()); $ansDI->copyTo($MR->getAnswersDI()->getAbsPath()); } }
/** * Метод регистрирует директорию, как доступную для поиска и подключения классов * * @param type $dirName - название директории (одна из констант DIR_ данного класса) */ public function registerBaseDir($path, $required = true) { //Получим DirItem, соответствующий нашей директории $di = DirItem::inst(next_level_dir($path, DIR_SEPARATOR)); //Проверим - может уже подключили? if (array_key_exists($di->getRelPath(), $this->DIRS)) { return; //--- } //$dirAbsPath = [C:/www/postupayu.ru/www/kit/] $dirAbsPath = $di->getAbsPath(); //Проверим, является ли путь - директорией if (!$di->isDir()) { check_condition(!$required, "Invalid class path dir given: [{$dirAbsPath}]"); return; //--- } //Отлогируем $this->LOGGER->infoBox("CLASS PATH DIR [{$dirAbsPath}] REGISTERED"); //Сохраним ссылку на директорию $this->DIRS[$di->getRelPath()] = new AutoloadDir($di); }
/** * Загрузка разметки администраторского меню */ public function getLayout() { $store = DirItem::inst(__DIR__, __CLASS__, 'layout')->getArrayFromFile(); $store = to_array($store); //Получим массив - копию страниц и будем удалять из него те страницы, которые входят в Layout $pages = $this->pages; //Базовую страницу всегда показываем в самом верху (единственная ссылка первого уровня) $LAY = new AdminPagesNavigation(); $LAY->addItem($this->getHrefToPage(AP_APCommon::getPageIdent()), 1); unset($pages[AP_APCommon::getPageIdent()]); //0 - группа, 1 - элемент foreach ($store as $item) { $type = $item[0]; $value = $item[1]; switch ($type) { //Группа case 0: $LAY->addItem($value, 1); break; //Элемент //Элемент case 1: if ($this->hasPage($value) && $value != AP_APCommon::getPageIdent()) { unset($pages[$value]); $LAY->addItem($this->getHrefToPage($value), 2); } break; } } //Оставшиеся страницы добавим в общую группу if (count($pages) > 0) { $LAY->addItem('Все страницы', 1); foreach ($pages as $page) { $LAY->addItem($this->getHrefToPage($page), 2); } } return $LAY->getHtml(); }
/** * Метод получает на вход url ресурса и пытается его обфусцировать, если это возможно. * * @return: путь к ресурсу, который должнет быть подключен, или null, если ресурс подключать не нужно */ private function tryReplaceResource($url) { if (!starts_with($url, DIR_SEPARATOR)) { //Это внешний ресурс: http:// и т.д. - подключаем. return $url; } $di = DirItem::inst($url); if (!$di->isFile() || $di->getSize() <= 0) { return null; } if (!PsDefines::isProduction()) { //Не будем пытаться обфусцировать в девелопменте //return $url; } if (!ends_with($url, '.js')) { //Мы не можем обфусцировать .css файлы, так как они используют относительные пути к ресурсам. return $url; } return $url; $url = $di->getRelPath(); if (!starts_with($url, $this->OBFUSCATABLE)) { //Не стоит обфусцировать не наши .js файлы, так как они могут внутри использовать ссылки на рядом лежащие ресурсы return $url; } $type = 'js'; $obfuscatedDi = DirManager::autogen("resources/{$type}")->getDirItem(null, md5($url), $type); $mtyme = $obfuscatedDi->getModificationTime(); if (!$mtyme || $mtyme < $di->getModificationTime()) { $obfuscatedDi->writeToFile(StringUtils::normalizeResourceFile($type, $di->getFileContents()), true); } return $obfuscatedDi->getRelPath(); }
public static function arr($num, $process_sections = true) { return parse_ini_file(DirItem::inst(__DIR__, 'ini' . $num, 'ini')->getAbsPath(), $process_sections); }
/** @return DirItem */ public final function getUploadedFileDi($uploadId, $userId = null) { if (!$this->CACHE->has($uploadId)) { $this->assertCanUseDb(__FUNCTION__); $this->assertAutonomous('файл не может быть загружен из БД'); $file = UploadsBean::inst()->getFile($this->DBTYPE, $uploadId, $userId); $this->LOGGER->info("File [{$uploadId}] loaded from DB for user [{$userId}] ? {}.", var_export($file, true)); $this->CACHE->set($uploadId, is_array($file) && array_key_exists('name', $file) ? DirItem::inst($file['name']) : null); } return $this->CACHE->get($uploadId); }
$rootPages = DirManager::inst()->getDirContent(null, PsConst::EXT_PHP); /** @var DirItem */ foreach ($rootPages as $page) { $name = $page->getName(); if (in_array($name, $pages)) { dolog("+ {$name}"); } else { dolog("- {$name}"); $page->remove(); } } /* * УСТАНОВИМ КОНСТАНТЫ */ LOGBOX('Set consts'); $props = DirItem::inst(__DIR__, 'consts.txt')->getFileAsProps(); dolog(print_r($props, true)); PsGlobals::inst()->updateProps($props); /* * УДАЛИМ ТЕСТОВЫЕ ДИРЕКТОРИИ */ LOGBOX('Remove test dirs'); $dirs = DirManager::inst()->getDirContentFull(null, DirItemFilter::DIRS); $testDirNames = array('temp', 'orig', '4use', 'tests', 'testcase'); $testDirStartsWith = array('!'); /* @var $dir DirItem */ foreach ($dirs as $dir) { if (in_array($dir->getName(), $testDirNames) || starts_with($dir->getName(), $testDirStartsWith)) { $path = $dir->getAbsPath(); dolog('Removing: ' . $path); DirManager::inst($path)->clearDir(null, true);
protected function __construct() { $this->LOGGER = PsLogger::inst(__CLASS__); $this->DI = DirItem::inst('kitcore', 'Globals.php'); $this->load(); }
public function getAnswersDI() { return DirItem::inst(__DIR__, 'answers', PsConst::EXT_TXT); }
public function __construct($class) { $this->rc = PsUtil::newReflectionClass($class); $this->di = DirItem::inst(Autoload::inst()->getClassPath($this->rc->name)); }
private function __construct() { $this->di = DirItem::inst(__DIR__, __CLASS__, PsConst::EXT_TPL)->touchIfNotFile(); }
/** * Возвращает DirItem, находящийся на том-же уровне, что и данный элемент * * @param str $name * @param str $ext * @return DirItem */ public function getSibling($name, $ext = null) { return DirItem::inst($this->getDirname(), $name, $ext); }
/** * @covers DirManager::getDirItem */ public function testGetDirItem() { $di = DirManager::inst(DirManagerTestHelper::dirsAbsPath())->getDirItem(DirManagerTestHelper::IMAGES); $this->assertTrue($di instanceof DirItem); $this->assertTrue($di->isDir()); //Объект должен создаться, хотя файла и нет $di = DirManager::inst(DirManagerTestHelper::dirsAbsPath())->getDirItem(DirManagerTestHelper::IMAGES, self::NOT_ALLOWED_STR); $this->assertEquals($di->getAbsPath(), DirManagerTestHelper::imagesAbsPath() . self::NOT_ALLOWED_STR); //Проверим на однм и том-же объекте, должны получить один и тот же экземпляр $di1 = DirManager::inst(DirManagerTestHelper::dirsAbsPath())->getDirItem(DirManagerTestHelper::IMAGES, '16x16.png'); $this->assertTrue($di1->isImg()); $di2 = DirManager::inst(DirManagerTestHelper::dirsAbsPath())->getDirItem(DirManagerTestHelper::IMAGES, '16x16', 'png'); $this->assertTrue($di2->isImg()); $this->assertTrue($di1 === $di2); $di2 = DirItem::inst(array(DirManagerTestHelper::dirsAbsPath(), DirManagerTestHelper::IMAGES), '16x16', 'png'); $this->assertTrue($di1 === $di2); $di1 = DirManager::inst(DirManagerTestHelper::dirsAbsPath())->getDirItem(); $di2 = DirItem::inst(array(DirManagerTestHelper::dirsAbsPath())); $this->assertTrue($di1 === $di2); }
continue; } $rebus = $MR->normalize($rebus); switch ($MR->rebusState($rebus)) { case PsMathRebus::STATE_HAS_ANSWERS: dolog("Take rebus answers: {$rebus}"); $result[$rebus] = $MR->rebusAnswers($rebus); break; case PsMathRebus::STATE_NO_ANSWERS: dolog("Scipping rebus: {$rebus}"); $result[$rebus] = array(); break; case PsMathRebus::STATE_NOT_REGISTERED: dolog("Processing rebus: {$rebus}"); $result[$rebus] = PsMathRebusSolver::solve($rebus); break; } } $ansDI = DirItem::inst(__DIR__, 'answers.txt'); $ansDI->remove(); foreach ($result as $rebus => $answers) { $ansDI->writeLineToFile($rebus); foreach ($answers as $answer) { $ansDI->writeLineToFile($answer); } $ansDI->writeLineToFile(); } if (getCmdParam(1) == 1) { dolog('Copy from [' . $ansDI->getRelPath() . '] to [' . $MR->getAnswersDI()->getRelPath() . ']'); $ansDI->copyTo($MR->getAnswersDI()->getAbsPath()); }
public final function copyDirContent2Dir($dirFrom, $dirToAbsPath, $includeDir = true, $filterName = null) { $fromDirRelPath = $this->relDirPath($dirFrom); $includeDirName = basename($fromDirRelPath); check_condition($includeDirName, "Trying to copy root directory"); $destDirAbsPath = $dirToAbsPath instanceof DirItem ? $dirToAbsPath->getAbsPath() : DirItem::inst($dirToAbsPath)->getAbsPath(); //$includeDir = $includeDir && $fromDirRelPath && ($fromDirRelPath != DIR_SEPARATOR); $content = $this->getDirContentFull($dirFrom, $filterName); if (empty($content)) { //Папка пуста. Если $includeDir=true, то просто создадим её if ($includeDir && $this->isDir($dirFrom)) { $destAbsPath = next_level_dir($destDirAbsPath, $includeDirName); DirItem::inst($destAbsPath)->makePath(); } return; //--- } /* @var $src DirItem */ foreach ($content as $src) { $relPathNewDirFromOldDir = cut_string_start($src->getRelPath(), $fromDirRelPath); $destAbsPath = next_level_dir($destDirAbsPath, $includeDir ? $includeDirName : null, $relPathNewDirFromOldDir); $destDi = DirItem::inst($destAbsPath)->makePath(); if ($src->isFile()) { $src->copyTo($destDi); } } }
public function getAnswersDI() { return DirItem::inst(__DIR__, 'answers.txt'); }
function smarty_function_linkup_js($params, Smarty_Internal_Template &$smarty) { $di = DirItem::inst(array_get_value('dir', $params), array_get_value('name', $params), PsConst::EXT_JS); echo $di->isFile() ? PsHtml::linkJs($di) : ''; }
private function __construct() { $this->di = DirItem::inst(__DIR__, __CLASS__, 'tpl')->touchIfNotFile(); }
/** * Метод создаёт новый фолдинг */ public function makeNewFolding(ArrayAdapter $adapter) { $ifaces = $adapter->arr('ifaces'); $rtypes = $adapter->arr('rtypes'); $type = lowertrim($adapter->str('FoldingType')); $subtype = lowertrim($adapter->str('FoldingSubType')); $group = $adapter->str('FoldingGroup'); $classPrefix = $adapter->str('FoldingClassPrefix'); check_condition($type, 'Не передан тип фолдинга'); check_condition($group, 'Не передана группа для фолдинга'); check_condition($classPrefix, 'Не передан префикс для классов фолдинга'); //TODO - определять директорию для воздания менеджера фолдингов. die('Folding dir is not deffined.'); $classesDi = DirItem::inst(array('sdk/kit', 'folded'), $group); check_condition(!$classesDi->isDir(), "Директория {$classesDi} уже существует"); check_condition(!$classesDi->isFile(), "Элемент {$classesDi} не может быть файлом"); $rtypes = array_intersect(array_keys(PsUtil::getClassConsts('FoldedResources', 'RTYPE_')), $rtypes); $rtypesArr = trim(implode(', self::', $rtypes)); $rtypesArr = $rtypesArr ? "self::{$rtypesArr}" : ''; $hasPhp = in_array('RTYPE_PHP', $rtypes); $classesDm = DirManager::inst($classesDi->getRelPath())->makePath(); $resourcesPatternDmTo = DirManager::resources(array('folded', $group, FoldedResources::PATTERN_NAME)); check_condition(!$resourcesPatternDmTo->isDir(), "Целевая директория {$resourcesPatternDmTo} существует"); $resourcesPatternDmFrom = DirManager::resources(array('folded', FoldedResources::PATTERN_NAME)); check_condition($resourcesPatternDmFrom->isDir(), "Некорректна директория-источник {$resourcesPatternDmFrom}"); $interfaces = array(); foreach ($this->getFoldedInterfaces($ifaces) as $name => $ifaceClass) { $ctt = $ifaceClass->getClassBody(); if ($ctt) { $interfaces[] = "/****************\n\t * {$name}\n\t ****************/\n" . $ctt; } } $smParams = $adapter->getData(); $smParams['rtypes'] = $rtypesArr; $smParams['funique'] = FoldedResources::unique($type, $subtype); $smParams['BaseClass'] = 'Base' . $classPrefix; $smParams['ManagerClass'] = $classPrefix . 'Manager'; $smParams['ResourcesClass'] = $classPrefix . 'Resources'; $smParams['implements'] = $ifaces ? 'implements ' . implode(', ', $ifaces) . ' ' : ''; $smParams['interfaces'] = $interfaces ? implode("\n\n\t", $interfaces) : ''; try { //КЛАССЫ //Resources $tpl = PSSmarty::template(DirItem::inst(array(__DIR__, 'tpls'), 'resources.tpl'), $smParams); $di = $classesDm->getDirItem(null, $smParams['ResourcesClass'], 'php'); $di->writeToFile(trim($tpl->fetch()), true); //Manager $tpl = PSSmarty::template(DirItem::inst(array(__DIR__, 'tpls'), 'manager.tpl'), $smParams); $di = $classesDm->getDirItem(null, $smParams['ManagerClass'], 'php'); $di->writeToFile(trim($tpl->fetch()), true); if ($hasPhp) { //BaseClass $tpl = PSSmarty::template(DirItem::inst(array(__DIR__, 'tpls'), 'baseclass.tpl'), $smParams); $di = $classesDm->getDirItem(null, $smParams['BaseClass'], 'php'); $di->writeToFile(trim($tpl->fetch()), true); } //ШАБЛОН ДЛЯ СУЩНОСТЕЙ $resourcesPatternDmTo->makePath(); foreach ($rtypes as $rtype) { $ext = FoldedResources::resourceTypeToExt(PsUtil::newReflectionClass('FoldedResources')->getConstant($rtype)); $diTo = $resourcesPatternDmTo->getDirItem(null, FoldedResources::PATTERN_NAME, $ext); $diFrom = $resourcesPatternDmFrom->getDirItem(null, FoldedResources::PATTERN_NAME, $ext); if ($ext == PsConst::EXT_PHP) { $diTo->writeToFile(str_replace('eclassnamebase', $smParams['BaseClass'], $diFrom->getFileContents())); continue; } $diFrom->copyTo($diTo); } } catch (Exception $ex) { $classesDm->clearDir(null, true); $resourcesPatternDmTo->clearDir(null, true); throw $ex; } }
/** * Извлекает формулы из переданного текста. * Возвращает коолекцию TEX->DirItem */ public function extractTexImages($string, $createIfNotExists = true, $addDescr = false) { $formules = array(); foreach (TexExtractor::inst($string, true)->getTexContents() as $formula) { $di = $this->getImgDi($formula, $createIfNotExists); if (!$di) { continue; } $formules[$formula] = $di; if (!$addDescr) { continue; } $formules["{$formula}.tex"] = DirItem::inst(null, $di->getAbsPath(), '.tex'); } return $formules; }
private function getImages(ArrayAdapter $params, $FNAME) { $dir = $params->str('dir'); $name = $params->get('name'); //НЕПОСРЕДСТВЕННО КАРТИНКА if ($name instanceof DirItem) { return $name; } /* * FOLDING */ $FCW = FoldedContextWatcher::getInstance(); $folding = null; $ident = $params->get('ident'); //Тип фолдинга. Он может быть передан либо в параметре 'group', либо по префиксу смарти-функции, например: postimg (post-название типа фолдинга). $foldingType = $params->get('group'); $foldingType = $foldingType ? $foldingType : (starts_with($FNAME, 'img') ? null : array_get_value(0, explode('img', $FNAME))); //Подтип фолдинга, например: is - подтип фолдингов для фолдингов с типом post (выпуск журнала среди всех постов). $foldingSubType = $params->get('type'); if ($params->has('post')) { /* @var $post AbstractPost */ $post = $params->get('post'); $ident = $post->getIdent(); $folding = Handlers::getInstance()->getPostsProcessorByPostType($post->getPostType())->getFolding(); } else { if ($foldingType) { $hasSubtype = FoldedStorage::isFoldingHasSubtype($foldingType); if ($hasSubtype && !$foldingSubType) { //У фолдинга есть подтип, но в параметрах он не передан - определим фолдинг по контексту $folding = $FCW->getFoldedEntityEnsureType($foldingType)->getFolding(); } else { $folding = FoldedStorageInsts::byTypeStype($foldingType, $foldingSubType); } } else { if ($foldingSubType) { //Если передан только тип, то считаем, что имеется ввиду фолдинг поста $folding = Handlers::getInstance()->getPostsProcessorByPostType($foldingSubType)->getFolding(); } } } if ($folding && !$ident) { //У нас есть фолдинг, но нет идентификатора сущности - определим её из контекста $ident = $FCW->getFoldedEntityEnsureType($folding->getFoldingType())->getIdent(); } if (!$dir && !$name && $ident && $folding) { /* * Не передано название картинки, но передан идентификатор сущности - показываем cover. * TODO - подумать, возможно имеет смысл сделать возможность показывать любую картинку в заданном размере. */ return $folding->getCover($ident, $params->str('dim')); } /* * Берём путь "как есть", если: * 1. Передан специальный параметр asis * 2. Передана dir, и она начинается с '/' * 3. Не передана dir, но при этом name начинается с '/' * 4. dir или name указывают на адрес в интернете */ $asis = $params->bool('asis') || starts_with($dir, DIR_SEPARATOR) || !$dir && starts_with($name, DIR_SEPARATOR) || PsUrl::isHttp($dir) || PsUrl::isHttp($name); if ($asis) { if (!$dir) { return $name; } if (starts_with($name, DIR_SEPARATOR)) { return cut_string_end($dir, DIR_SEPARATOR) . $name; } return ($name ? ensure_ends_with($dir, DIR_SEPARATOR) : $dir) . $name; } /** @var DirManager */ $DM = null; /* * Теперь определим DirManager. Мы его можем взять: */ if ($folding) { //1. Из ресурсов фолдинга $DM = $folding->getResourcesDm($ident, 'src'); } else { //2. Обычный resources->images, если фолдинг не установлен $DM = DirManager::images(); } /* * Определим список показываемых картинок по атрибуту $name. Пример тега: * {postimg type='tr' ident='matrix' name='mao.gif mu.png mu.png'} * Просто разделим значение атрибута $name по точкам и пробелам и склеим в названия картинок. */ $NAMES = preg_split("/[. ]/", $name); $DI = $DM ? $DM->getDirItem($dir, $name) : DirItem::inst($dir, $name); if (count($NAMES) % 2 != 0 || $DI->isImg()) { //Указано что-то непонятное - не чётное кол-во составных элементов return $DI; } $IMAGES = array(); for ($i = 0; $i < count($NAMES); $i += 2) { $imgName = $NAMES[$i] . '.' . $NAMES[$i + 1]; $IMAGES[] = $DM ? $DM->getDirItem($dir, $imgName) : DirItem::inst($dir, $imgName); } return $IMAGES; }
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 }
public static function fileDiBreak() { return DirItem::inst(__DIR__, 'fileSequence2'); }
protected function __construct() { $this->DI = DirItem::inst(ConfigIni::projectGlobalsFilePath(), null, PsConst::EXT_PHP); $this->FileMtimeUpdate(); }