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;
 }
 /**
  * В процессе закрытия данного класса мы напишем полный список изменённых сущностей
  */
 public function onDestruct()
 {
     foreach (array('ACTION_FOLDING_' => 'Фолдинги', 'ACTION_ENTITY_' => 'Сущности') as $CONST_PREFIX => $name) {
         $this->LOGGER->infoBox($name);
         foreach (PsUtil::getClassConsts($this, $CONST_PREFIX) as $action) {
             $idents = array_get_value($action, $this->ACTIONS, array());
             $count = count($idents);
             $this->LOGGER->info();
             $this->LOGGER->info($action . ':');
             if ($count > 0) {
                 for ($i = 0; $i < $count; $i++) {
                     $this->LOGGER->info("\t" . (1 + $i) . '. ' . $idents[$i][0] . ($idents[$i][1] ? ' [' . $idents[$i][1] . ']' : ''));
                 }
             } else {
                 $this->LOGGER->info("\t -- Нет --");
             }
         }
     }
     /**
      * Распечатаем карту зависимости сущностей фолдинга.
      * Операция настолько тяжёлая, что в режиме ajax также будем избегать её выполнение.
      */
     if (PsDefines::isDevmode() && !PageContext::inst()->isAjax()) {
         $this->LOGGER->infoBox('Карта зависимости сущностей фолдингов:');
         foreach ($this->getDependsOnMap() as $who => $fromWhoArr) {
             $this->LOGGER->info("\t{$who}:");
             foreach ($fromWhoArr as $fromWho) {
                 $this->LOGGER->info("\t\t{$fromWho}");
             }
         }
     }
 }
 /**
  * В процессе закрытия данного класса мы напишем полный список изменённых сущностей
  */
 public function onDestruct()
 {
     foreach (array('ACTION_FOLDING_' => 'Фолдинги', 'ACTION_ENTITY_' => 'Сущности') as $CONST_PREFIX => $name) {
         $this->LOGGER->infoBox($name);
         foreach (PsUtil::getClassConsts($this, $CONST_PREFIX) as $action) {
             $idents = array_get_value($action, $this->ACTIONS, array());
             $count = count($idents);
             $this->LOGGER->info();
             $this->LOGGER->info($action . ':');
             if ($count > 0) {
                 for ($i = 0; $i < $count; $i++) {
                     $this->LOGGER->info("\t" . (1 + $i) . '. ' . $idents[$i][0] . ($idents[$i][1] ? ' [' . $idents[$i][1] . ']' : ''));
                 }
             } else {
                 $this->LOGGER->info("\t -- Нет --");
             }
         }
     }
 }
Exemple #4
0
 /**
  * Метод регистрирует директорию, как доступную для поиска и подключения классов
  * 
  * @param type $dirName - название директории (одна из констант DIR_ данного класса)
  */
 public function registerBaseDir($path, $required = true)
 {
     //Получим DirManager, соответствующий нашей директории
     $dm = DirManager::inst($path);
     //Проверим - может уже подключили?
     if (array_key_exists($dm->relDirPath(), $this->DIRS)) {
         return;
         //---
     }
     $dirAbsPath = $dm->absDirPath();
     //Проверим, является ли путь - директорией
     if (!$dm->isDir()) {
         check_condition(!$required, "Invalid class path dir given: [{$dirAbsPath}]");
         return;
         //---
     }
     //Отлогируем
     $this->LOGGER->infoBox("CLASS PATH DIR [{$dirAbsPath}] REGISTERED");
     //Сохраним ссылку на директорию
     $this->DIRS[$dm->relDirPath()] = new AutoloadDir($dm);
 }
Exemple #5
0
 /**
  * Метод регистрирует директорию, как доступную для поиска и подключения классов
  * 
  * @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);
 }
Exemple #6
0
 /**
 * Распечатывает текущее состояние дерева зависимости в лог.
 * При этом в дереве отмечаются всегда только полностью проверенные сущности.
 * Если, например, группа зависит от таблиц БД, которые были провалидированы, но при этом
 * сама группа отмечена, как валидная, то мы увидим подобную картину:
 * 
  +GALLERY:
  |	Сущности базы:
  |		ps_gallery
  |		ps_gallery_images
 */
 private function logTrees($caption, $doLog = true)
 {
     if (!$doLog || !$this->LOGGER->isEnabled()) {
         return;
         //---
     }
     $this->LOGGER->infoBox($caption);
     $GROUPS = PSCache::getCacheGroups();
     $hasPrintedGroups = false;
     foreach ($GROUPS as $group) {
         $isGroupPrinted = false;
         foreach ($this->TREE_DEP as $type => $groups2entitys) {
             if (!array_key_exists($group, $groups2entitys)) {
                 continue;
             }
             $valGr = !$this->isGroupValidatable($group);
             $valType = !$valGr && !$this->isTypeValidateble($type);
             if ($hasPrintedGroups && !$isGroupPrinted) {
                 $this->LOGGER->info();
             }
             if (!$isGroupPrinted) {
                 $isGroupPrinted = true;
                 $hasPrintedGroups = true;
                 $this->LOGGER->info("\t" . ($valGr ? '+' : '|') . $group . ':');
             } else {
                 $this->LOGGER->info("\t|");
             }
             $this->LOGGER->info("\t" . ($valType ? '+' : '|') . "\t{$type}:");
             foreach ($groups2entitys[$group] as $child) {
                 $varChild = !$valGr && !$valType && !in_array($child, $this->getChildsForValidate($type, $group));
                 $this->LOGGER->info("\t" . ($varChild ? '+' : '|') . "\t\t{$child}");
             }
         }
     }
     $this->LOGGER->info(pad_left('', ps_strlen($caption) + 4, '+'));
     $this->LOGGER->info();
 }
 /**
  * Метод, выполняющий всё вычисление и всю обработку
  */
 private function doProcess($cells)
 {
     PsProfiler::inst(__CLASS__)->start('Unioning cells');
     if ($this->LOGGER->isEnabled()) {
         $this->LOGGER->infoBox('Unioning ' . count($cells) . ' cells, user check: ' . var_export($this->checkUser, true));
         $this->LOGGER->info();
         $this->LOGGER->info('Before sorting and indexing:');
         $this->LOGGER->info(print_r($cells, true));
     }
     //Расположим ячейки от левого верхнего угла до правого нижнего (как при письме)
     usort($cells, function ($c1, $c2) {
         if ($c1['y_cell'] == $c2['y_cell']) {
             return $c1['x_cell'] > $c2['x_cell'] ? 1 : -1;
         }
         return $c1['y_cell'] > $c2['y_cell'] ? 1 : -1;
     });
     $this->cells = array();
     //Проиндексируем массив
     foreach ($cells as $cell) {
         $cell['x_cell'] = 1 * $cell['x_cell'];
         $cell['y_cell'] = 1 * $cell['y_cell'];
         $cell['id_user'] = 1 * $cell['id_user'];
         $this->cells[$cell['x_cell'] . 'x' . $cell['y_cell']] = $cell;
     }
     if ($this->LOGGER->isEnabled()) {
         $this->LOGGER->info();
         $this->LOGGER->info('After sorting and indexing:');
         $this->LOGGER->info(print_r($this->cells, true));
         $this->LOGGER->info();
     }
     //Пробегаем по всем ячейкам, объединяя их и исключая те ячейки, с которыми мы объединились
     $unioned = 0;
     foreach ($this->cells as $ident => $cell) {
         if (!array_key_exists($ident, $this->cells)) {
             //Видимо уже удаили ячейку из списка ячеек
             continue;
         }
         $x = $cell['x_cell'];
         $y = $cell['y_cell'];
         $id_user = $cell['id_user'];
         $dx = $this->getRightCellsCnt($x, $y, $id_user);
         if ($dx > 0) {
             //Объединяемся с ячейками справа
             $x1 = ($x - 1) * $this->w;
             $y1 = ($y - 1) * $this->h;
             $x2 = ($x + $dx) * $this->w;
             $y2 = $y * $this->h;
             for ($delta = 1; $delta <= $dx; $delta++) {
                 $cident = $x + $delta . 'x' . $y;
                 if ($this->LOGGER->isEnabled()) {
                     $cid_user = array_get_value_in(array($cident, 'id_user'), $this->cells);
                     $this->LOGGER->info(++$unioned . ". [{$ident}]({$id_user}) + [{$cident}]({$cid_user})");
                 }
                 unset($this->cells[$cident]);
             }
             $this->result[] = array($x1, $y1, $x2, $y2, $id_user);
             continue;
         }
         $dy = $this->getBottomCellsCnt($x, $y, $id_user);
         if ($dy > 0) {
             //Объединяемся с ячейками снизу
             $x1 = ($x - 1) * $this->w;
             $y1 = ($y - 1) * $this->h;
             $x2 = $x * $this->w;
             $y2 = ($y + $dy) * $this->h;
             for ($delta = 1; $delta <= $dy; $delta++) {
                 $cident = $x . 'x' . ($y + $delta);
                 if ($this->LOGGER->isEnabled()) {
                     $cid_user = array_get_value_in(array($cident, 'id_user'), $this->cells);
                     $this->LOGGER->info(++$unioned . ". [{$ident}]({$id_user}) + [{$cident}]({$cid_user})");
                 }
                 unset($this->cells[$cident]);
             }
             $this->result[] = array($x1, $y1, $x2, $y2, $id_user);
             continue;
         }
         //Не с кем объединяться, берём только эту ячейку
         $x1 = ($x - 1) * $this->w;
         $y1 = ($y - 1) * $this->h;
         $x2 = $x * $this->w;
         $y2 = $y * $this->h;
         $this->result[] = array($x1, $y1, $x2, $y2, $id_user);
     }
     $secundomer = PsProfiler::inst(__CLASS__)->stop();
     if ($this->LOGGER->isEnabled()) {
         $this->LOGGER->info();
         $this->LOGGER->info('Unioned cells:');
         $this->LOGGER->info(print_r($this->result, true));
         $this->LOGGER->info('Compression: {}%', round(count($this->result) / count($cells) * 100));
         if ($secundomer) {
             $this->LOGGER->info('Done in ' . $secundomer->getAverage() . ' seconds');
         }
     }
 }