/** * Reads configuration from NEON file. * @param string file name * @return array * @throws Nette\InvalidStateException */ public static function load($file) { if (!is_file($file) || !is_readable($file)) { throw new Nette\FileNotFoundException("File '{$file}' is missing or is not readable."); } $neon = Neon::decode(file_get_contents($file)); $separator = trim(self::$sectionSeparator); $data = array(); foreach ($neon as $secName => $secData) { if ($secData === NULL) { // empty section $secData = array(); } if (is_array($secData)) { // process extends sections like [staging < production] $parts = $separator ? explode($separator, $secName) : array($secName); if (count($parts) > 1) { $parent = trim($parts[1]); if (!isset($data[$parent]) || !is_array($data[$parent])) { throw new Nette\InvalidStateException("Missing parent section '{$parent}' in file '{$file}'."); } $secData = array_reverse(Nette\Utils\Arrays::mergeTree(array_reverse($secData, TRUE), array_reverse($data[$parent], TRUE)), TRUE); $secName = trim($parts[0]); if ($secName === '') { throw new Nette\InvalidStateException("Invalid empty section name in file '{$file}'."); } } } $data[$secName] = $secData; } return $data; }
/** * @param \SplFileInfo $package * @return array * @throws \movi\FileNotFoundException */ private function getData(\SplFileInfo $package) { $file = $package->getPathname() . '/' . self::PACKAGE_FILE; if (!file_exists($file) || !is_readable($file)) { throw new FileNotFoundException("JSON file for package '" . $package->getFilename() . "' was not found or is not readable."); } $data = Json::decode(file_get_contents($file), Json::FORCE_ARRAY); $data['dir'] = $package->getPathname(); return Arrays::mergeTree($data, $this->defaults); }
public function beforeCompile() { $builder = $this->getContainerBuilder(); $connection = $builder->getDefinition('movi.connection'); foreach (array_keys($builder->findByTag(self::FILTER_TAG)) as $filter) { $def = $builder->getDefinition($filter); $tags = Arrays::mergeTree($def->tags, $this->defaults); $connection->addSetup('registerFilter', [$tags['name'], ['@' . $filter, $tags['callback']], !empty($tags['wire']) ? $tags['wire'] : NULL]); } }
public function saveConfig() { $values = $this->data; $this->loadConfig(); $data =& $this->data; foreach ($this->root as $item) { $data =& $data[$item]; } $data = $data ?: array(); $data = Arrays::mergeTree($values, $data); file_put_contents($this->fileName, $this->adapter->dump($this->data)); if (function_exists('opcache_reset')) { opcache_reset(); } }
public function loadLabelExtentsionProperties() { $params = $this->context->getParameters(); $loader = new Nette\Config\Loader(); $commonConfigFile = CONFIG_DIR . '/labels/labelExtensions.neon'; $projectConfigFile = $params['projectDir'] . '/config/labels/labelExtensions.neon'; $config = $loader->load($commonConfigFile); // dump($config); if (is_file($projectConfigFile)) { $projectConfig = $loader->load($projectConfigFile); $config = \Nette\Utils\Arrays::mergeTree($projectConfig, $config); } // dump($config); return $config; }
/** * @param \Nette\DI\Container * @param array */ public function __construct(DI\Container $context, array $configuration = array()) { $this->context = $context; $this->configuration = \Nette\Utils\Arrays::mergeTree(array( 'productionMode' => $context->params['productionMode'], 'proxyDir' => $context->expand("%appDir%/proxies"), 'proxyNamespace' => 'App\Models\Proxies', 'entityDirs' => array($context->params['appDir'], NELLA_FRAMEWORK_DIR), 'migrations' => array( 'name' => \Nella\Framework::NAME . " DB Migrations", 'table' => "db_version", 'directory' => $context->expand("%appDir%/migrations"), 'namespace' => 'App\Models\Migrations', ) ), $configuration); }
/** * Startup */ public function startup() { parent::startup(); $this->basePath = $this->getBasePath(); if ($this->name != 'Admin:Auth') { if (!$this->user->isLoggedIn()) { if ($this->user->getLogoutReason() === User::INACTIVITY) { $this->flashMessage('Session timeout, you have been logged out'); } $this->redirect('Auth:login', array('backlink' => $this->storeRequest())); } else { if (!$this->user->isAllowed($this->name, $this->action)) { $this->flashMessage('Access denied'); $this->redirect('Default:'); } } } // configure native components $adminModuleControlMap = array('~^pageMultiForm$~' => 'Components\\MultiForms', '~^[[:alnum:]]+Form$~' => 'AdminModule\\Forms', '~^[[:alnum:]]+DataGrid$~' => 'AdminModule\\DataGrids', '~^[[:alnum:]]+ConfirmDialog$~' => 'AdminModule\\Dialogs', '~^[[:alnum:]]+Sorter$~' => 'AdminModule\\Sorters'); $this->nativeControlMap = Arrays::mergeTree($this->nativeControlMap, $adminModuleControlMap); $this->setupUiComponents(); }
/** * Returns count statistics of playlist * @return array */ public function getSummary() { $summary = array("all" => 0, "approved" => 0, "waiting" => 0, "rejected" => 0); //Inital $summary = Arrays::mergeTree($this->getTable()->select("status, COUNT(status) AS score")->group("status")->fetchPairs("status", "score"), $summary); $summary["all"] = $this->findAll()->count(); //All return $summary; }
public function __construct(\Nette\Mail\IMailer $mailer, $config = []) { $this->mailer = $mailer; $this->config = \Nette\Utils\Arrays::mergeTree($this->config, $config); }
/** * Processes data from configuration file * @param array $data * @param bool $main * @return array * @throws FileNotFoundException * @throws InvalidConfigurationException */ protected function processConfig(array $data, $main = TRUE) { $config = []; $include = []; if (isset($data['include'])) { if (is_array($data['include'])) { foreach ($data['include'] as $another) { $include[] = $another; } } else { if (is_scalar($data['include'])) { $include[] = $data['include']; } } } unset($data['include']); if ($main) { foreach (['vendor', 'name', 'description', 'licence', 'version'] as $key) { if (isset($data[$key])) { $config[$key] = (string) $data[$key]; unset($data[$key]); } else { throw new InvalidConfigurationException("Missing configuration {$key} in configuration."); } } } foreach ($data as $key => $value) { $config[$key] = $value; } foreach ($include as $another) { if (!file_exists($another)) { throw new FileNotFoundException("Config file {$another} not found."); } $config = Arrays::mergeTree($config, $this->processConfig(Neon::decode(file_get_contents($another)), FALSE)); } return $config; }
/** * @param \Venne\DataTransfer\DataTransferQuery $query * @return \Venne\DataTransfer\DataTransferObject[] */ public function fetchIterator(DataTransferQuery $query) { $class = '\\' . trim($query->getClass(), '\\'); $rows = $query->getValues(); if (!class_exists($class)) { throw new InvalidArgumentException(sprintf('Class \'%n\' does not exist.', $class)); } if (!is_subclass_of($class, 'Venne\\DataTransfer\\DataTransferObject')) { throw new InvalidArgumentException(sprintf('Class \'%s\' must inherit from \'Venne\\DataTransfer\\DataTransferObject\'.', $class)); } if (!$query->isCacheEnabled()) { return new DataTransferObjectIterator($class, function () use(&$rows, $class) { $rows = is_callable($rows) ? Callback::invoke($rows) : $rows; $rowsData = array(); foreach ($rows as $row) { $rowsData[] = $this->driver->getValuesByObject($row, $class::getKeys()); } return $rowsData; }); } $cacheDependencies = $query->getCacheDependencies(); $primaryKeysCacheKey = $this->formatPrimaryKeysCacheKey(sprintf('%s[]', $class), $query->getCacheKey()); $primaryKeys = $this->cache->load($primaryKeysCacheKey, function (&$dependencies) use(&$rows, &$cacheDependencies, $class) { $rows = is_callable($rows) ? Callback::invoke($rows) : $rows; $primaryKeys = array(); foreach ($rows as $row) { $primaryKeys[] = $this->driver->getPrimaryKeyByObject($row); $dependencies = Arrays::mergeTree((array) $dependencies, $this->driver->getCacheDependenciesByObject($row)); } return $primaryKeys; }); $loadedValues = array(); foreach ($primaryKeys as $index => $primaryKey) { $loadedValues[] = $this->cache->load(array($this->formatValuesCacheKey($class, $primaryKey), $primaryKeysCacheKey), function (&$dependencies) use(&$rows, &$cacheDependencies, $class, $index) { $rows = is_callable($rows) ? Callback::invoke($rows) : $rows; $dependencies = Arrays::mergeTree((array) $dependencies, $this->driver->getCacheDependenciesByObject($rows[$index])); $row = $rows[$index]; $row = is_callable($row) ? Callback::invoke($row) : $row; /** @var DataTransferObject $dto */ $dto = new $class($this->driver->getValuesByObject($row, $class::getKeys())); return $dto->toArray(); }); } return new DataTransferObjectIterator($class, $loadedValues); }
protected function createComponentSongList($name) { $grid = new Grid($this, $name); $grid->setModel($this->songy->findAll()); $grid->addColumnDate("datum", "Datum", "d.m.y")->setSortable()->setFilterDateRange(); $grid->addColumnText("interpret_name", "Interpret")->setCustomRender(function ($item) { return $item->interpret_name . ($item->interpret ? " " . Html::el('i')->addAttributes(['class' => 'fa fa-ticket', 'title' => 'Asociován s ' . $item->interpret->nazev]) : null); })->setSortable()->setFilterText()->setSuggestion(); $grid->addColumnText("name", "Song")->setSortable()->setFilterText()->setSuggestion(); $filter = array('' => 'Všechny'); $filter = \Nette\Utils\Arrays::mergeTree($filter, $this->zanry->getList()); $grid->addColumnText("zanr_id", "Žánr")->setCustomRender(function ($item) { return $item->zanr ? $item->zanr->name : null; })->setFilterSelect($filter); $grid->addColumnText("zadatel", "Přidal(a)")->setSortable()->setFilterText()->setSuggestion(); $statuses = array('' => 'Všechny', 'approved' => 'Zařazené', 'rejected' => 'Vyřazené', 'waiting' => 'Čekající'); $grid->addColumnText("status", "Status")->setCustomRender(function ($item) { $status = $item->status; $revizor = $item->revisor ? $item->ref("user", "revisor")->username : "******"; switch ($status) { case "approved": return Html::el("span", array("class" => "label label-success", "title" => "Schválil(a) " . $revizor))->setText("Zařazen"); case "waiting": return Html::el("span", array("class" => "label label-warning", "title" => "Čeká ve frontě ke schválení"))->setText("Čeká"); case "rejected": return Html::el("span", array("class" => "label label-danger", "title" => "Zamítl(a) " . $revizor))->setText("Vyřazen"); default: return Html::el("i")->setText("Neznámý"); } })->setSortable()->setFilterSelect($statuses); $grid->addColumnText("pecka", "Pecka")->setReplacement(array(0 => '', 1 => Html::el('i')->addAttributes(['class' => 'fa fa-check'])))->setFilterCheck()->setCondition(" = 1"); $grid->addColumnText("instro", "Instro")->setReplacement(array(0 => '', 1 => Html::el('i')->addAttributes(['class' => 'fa fa-check'])))->setFilterCheck()->setCondition(" = 1"); $grid->addColumnText("remix", "Remix")->setReplacement(array(0 => '', 1 => Html::el('i')->addAttributes(['class' => 'fa fa-check'])))->setFilterCheck()->setCondition(" = 1"); $grid->addColumnNumber("likes", Html::el('i')->addAttributes(['class' => 'fa fa-heart']))->setCustomRender(function ($item) { return $item->related("song_likes")->count(); }); $grid->addActionHref("editor", "Editovat")->setIcon("pencil"); $grid->addActionHref('delete', 'Smazat', 'deleteSong!')->setIcon('trash')->setConfirm('Opravdu chcete smazat tento song?'); $grid->setFilterRenderType(Filter::RENDER_OUTER); $grid->setDefaultSort(array("datum" => "DESC")); //Set face for grid $gridTemplate = __DIR__ . "/../templates/components/Grid.latte"; if (file_exists($gridTemplate)) { $grid->setTemplateFile($gridTemplate); } return $grid; }
/** * @param \Venne\Packages\IPackage $package * @return mixed */ private function getGlobalMetadata(IPackage $package) { if ($this->globalMetadata === null) { $this->globalMetadata = array(); foreach ($this->metadataSources as $source) { if (substr($source, 0, 7) == 'http://' || substr($source, 0, 8) == 'https://') { $ch = curl_init(); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_URL, $source); $data = curl_exec($ch); } else { $data = file_get_contents($source); } if (!$data) { throw new InvalidStateException(sprintf('Source \'$source\' is empty.', $source)); } if ($data) { $this->globalMetadata = Arrays::mergeTree($this->globalMetadata, Json::decode($data, Json::FORCE_ARRAY)); } } } if (!isset($this->globalMetadata[$package->getName()])) { return null; } $versionProvide = new VersionConstraint('==', $this->getVersion($package)); foreach ($this->globalMetadata[$package->getName()] as $data) { $versionRequire = $this->versionParser->parseConstraints($data['version']); if ($versionRequire->matches($versionProvide)) { return $data['metadata']; } } }
public function __construct($parent, $name) { parent::__construct($parent, $name); /* PREPARE DATA */ //$pageId = $this->getPresenter()->getParam('id'); //dump($labelId); $st = new \BuboApp\AdminModule\Components\SelectTraverser($this->presenter); $cm = $this->presenter->pageManagerService->getCurrentModule(); $moduleConfig = $this->presenter->configLoaderService->loadModulesConfig($cm); $linkSelectData = array(); if (isset($moduleConfig['modules'])) { foreach ($moduleConfig['modules'] as $moduleName => $module) { $linkSelectData[$module['title']] = $st->getSelectMenu($this->presenter['structureManager']->getLanguage(), TRUE, $moduleName); } } $selectData = $st->getSelectMenu($this->presenter['structureManager']->getLanguage()); // dump($selectData); // dump($linkSelectData); //$this->addGroup('Obraz'); $this->addSelect('parent', "Rodič", $selectData)->setPrompt(':: Vyberte předka ::')->setRequired('Musíte vybrat předka'); $this['parent']->getControlPrototype()->style = 'font-family:monospace;z-index:250;font-size:12px;'; //$this->addGroup('Vzor'); $this->addSelect('pattern', "Vzorová stránka", $linkSelectData)->setPrompt(':: Vyberte vzorovou stránku ::')->setRequired('Musíte vybrat vzorovou stránku'); $this['pattern']->getControlPrototype()->style = 'font-family:monospace;z-index:250;font-size:12px;'; $moduleData = array('default' => 'Výchozí modul'); // if (count($moduleData) > 1) { // // $this->addSelect('pattern_module', "Modul", $moduleData) // ->setPrompt(':: Vyberte vzorový modul ::') // ->setRequired('Musíte vybrat modul'); // // } else { // // $this->addHidden('pattern_module', $this->presenter->pageManagerService->getCurrentModule()); // } $this->addHidden('image_module', $this->presenter->pageManagerService->getCurrentModule()); // load templates -> get only existing and with nice names (if possible) $_templates = $this->presenter->projectManagerService->getListOfTemplates(); $templateConfig = $this->presenter->configLoaderService->loadLayoutConfig(); $res = \Nette\Utils\Arrays::mergeTree($templateConfig['layouts'], $_templates); $templates = array_intersect_key($res, $_templates); $this->addSelect('layout', 'Šablona', $templates); //$this->addCheckbox('create_subtree', 'Vytvořit celý podstrom'); switch ($this->getPresenter()->getAction()) { case 'addLink': //$this->setCurrentGroup(NULL); $this->addSubmit('send', 'Vytvořit'); $this->onSuccess[] = array($this, 'addformSubmited'); break; case 'editLink': // edit $this->addSubmit('send', 'Uložit'); $this->addSubmit('delete', 'Smazat')->setValidationScope(NULL); $image = $this->presenter->getParam('id'); $this->addHidden('image', $image); $defaults = $this->presenter->pageModel->getLink($image); $this->setDefaults($defaults); $this->onSuccess[] = array($this, 'editFormSubmited'); break; } }
/** * Internal: receives submitted HTTP data. * @return array */ protected function receiveHttpData() { $presenter = $this->getPresenter(); if (!$presenter->isSignalReceiver($this, 'submit')) { return; } $isPost = $this->getMethod() === self::POST; $request = $presenter->getRequest(); if ($request->isMethod('forward') || $request->isMethod('post') !== $isPost) { return; } if ($isPost) { return Nette\Utils\Arrays::mergeTree($request->getPost(), $request->getFiles()); } else { return $request->getParameters(); } }
use Nette\Utils\Json; use Zend\Log\Writer\Stream; use Zend\Log\Logger; use Nette\Utils\JsonException; use Carbon\Carbon; require __DIR__ . '/../vendor/autoload.php'; require __DIR__ . '/../app/SongProvider.php'; if (!file_exists(__DIR__ . '/../../adminAndMobile/app/config/config.local.neon')) { die('Configuration file config.local.neon is missing!'); } if (!file_exists(__DIR__ . '/../../adminAndMobile/app/config/config.neon')) { die('Configuration file config.neon is missing!'); } $config1 = Neon::decode(file_get_contents(__DIR__ . '/../../adminAndMobile/app/config/config.neon')); $config2 = Neon::decode(file_get_contents(__DIR__ . '/../../adminAndMobile/app/config/config.local.neon')); $config = Arrays::mergeTree($config1, $config2); $host = $config['parameters']['host']; $dbName = $config['parameters']['dbname']; $username = $config['parameters']['user']; $password = $config['parameters']['password'] ?? ''; $songsDirectory = $config['parameters']['songsDir']; $port = $config['doctrine']['port']; $webSongsDir = \Nette\Utils\Strings::replace($songsDirectory, '~%wwwDir%/../../~', ''); $songsDirectory = \Nette\Utils\Strings::replace($songsDirectory, '~%wwwDir%~', __DIR__ . '/../../adminAndMobile/www'); $currentGenreFile = __DIR__ . '/../../adminAndMobile/app/model/currentGenre.txt'; $sessionFile = __DIR__ . '/../../adminAndMobile/app/model/session.txt'; //session id reading, security check $storedData = Json::decode(file_get_contents($sessionFile), Json::FORCE_ARRAY); session_start(); $sessionId = session_id(); if ($storedData === []) {
public function __construct($parent, $name) { parent::__construct($parent, $name); /* PREPARE DATA */ //$pageId = $this->getPresenter()->getParam('id'); // dump($labelId); //$this->addHidden('label_id'); $this->addGroup('Jméno a typ'); $this->addText('name', 'Jméno štítku')->addRule(Form::FILLED, 'Zadejte jméno štítku.'); $this->addHidden('color', '0000ff'); $this->addHidden('module', $this->presenter->pageManagerService->getCurrentModule()); $selectData = array(NULL => 'Single', '1' => '1. úroveň', '2' => '2. úroveň', '3' => '3. úroveň', '4' => '4. úroveň', '0' => 'Celý podstrom'); $this->addSelect('depth_of_recursion', 'Typ', $selectData); $this->addGroup('Konfigurace'); $this->addCheckBox('create_button', 'Vytvářet tlačítko'); // ->addConditionOn($this['is_singleton'], Form::EQUAL, NULL) // ->addRule(Form::EQUAL, 'Tlačítko lze vytvořit pouze u jedináčka', FALSE); // ->addConditionOn($this['depth_of_recursion'], ~Form::EQUAL, NULL) //->addRule(Form::EQUAL, 'Rekurzivní štítek nemůže být jedináček', FALSE); $this->addCheckBox('show_button', 'Zobrazit tlačítko'); // load templates -> get only existing and with nice names (if possible) $_templates = $this->presenter->projectManagerService->getListOfTemplates(TRUE); // dump($_templates); // die(); // $templateConfig = $this->presenter->configLoaderService->loadLayoutConfig(); // $res = \Nette\Utils\Arrays::mergeTree($templateConfig['layouts'], $_templates['head']); // $templates['Normální stránky'] = array_intersect_key($res, $_templates['head']); // if (isset($_templates['headless'])) { // $res = \Nette\Utils\Arrays::mergeTree($templateConfig['layouts'], $_templates['headless']); // $templates['Stránky bez url'] = array_intersect_key($res, $_templates['headless']); // } $templateConfig = $this->presenter->configLoaderService->loadLayoutConfig(); $res = \Nette\Utils\Arrays::mergeTree($templateConfig['layouts'], $_templates); $templates = array_intersect_key($res, $_templates); $this->addSelect('layout', 'Šablona', $templates); $entities['Stránky'] = $this->presenter->pageManagerService->getAllPageEntities(); $entities['Útržky'] = $this->presenter->pageManagerService->getAllScrapEntities(); $this->addSelect('entity', 'Entita', $entities); $this->addCheckbox('lock_layout', 'Uzamknout šablonu'); // $this->addCheckBox('is_resource','Chráněný zdroj'); //$this->addCheckBox('is_singleton', 'Jedináček'); $this->addGroup('Jazyky'); //$this->addSelect('is_global', 'Viditelnost', $visibilityData); $langs = $this->addContainer('langs'); foreach ($this->presenter->langManagerService->getLangs() as $langCode => $langTitle) { $c = \Nette\Utils\Html::el(); $el = $c->create('img'); $el->src = $this->presenter->baseUri . '/images/flags/' . strtolower($langCode) . '.png'; $c->add(\Nette\Utils\Html::el('span')->setHtml(' ' . $langTitle)); $langs->addCheckbox(strtolower($langCode), $c); } $allLangs = array_keys($this->presenter->langManagerService->getLangs()); $this['langs'][strtolower(reset($allLangs))]->addRule(array($this, 'atLeastOneCheckBoxChecked'), 'Alespoň jeden jazyk musí být vybrán', $this['langs']); $this['name']->getControlPrototype()->class[] = 'fleft'; $this['color']->getControlPrototype()->class[] = 'color-listener'; switch ($this->getPresenter()->getAction()) { case 'addLabel': $this->setCurrentGroup(NULL); $this->addSubmit('send', 'Vytvořit'); $this->onSuccess[] = array($this, 'addformSubmited'); break; case 'editLabel': // edit $labelId = $this->presenter->labelId; $this->setCurrentGroup(NULL); $this->addSubmit('send', 'Uložit'); $this->addHidden('label_id', $labelId); //$this['is_global']->setDisabled(); $defaults = $this->presenter->labelModel->getLabel($labelId); if ($defaults['langs'] === NULL) { $defaults['langs'] = array(); } $this->addSubmit('manage_extensions', 'Rozšíření...')->setValidationScope(NULL); $this->addSubmit('sort', 'Třídění...')->setValidationScope(NULL); $this->addSubmit('entityParams', 'Parametry entity...')->setValidationScope(NULL); $this->addSubmit('delete', 'Smazat štítek'); $this['delete']->getControlPrototype()->class[] = 'are-you-sure'; $this->addSubmit('createPage', 'Vytvořit stránku'); $this->onSuccess[] = array($this, 'editFormSubmited'); $this->setDefaults($defaults); break; } }
/** * @param array $config */ private function setupConfigByExtensions(array &$config) { foreach ($this->compiler->getExtensions() as $extension) { if ($extension instanceof EntityProvider) { $metadata = $extension->getEntityMapping(); Validators::assert($metadata, 'array'); $config['metadata'] = array_merge($config['metadata'], $metadata); } if ($extension instanceof TargetEntityProvider) { $targetEntities = $extension->getTargetEntityMapping(); Validators::assert($targetEntities, 'array'); $config['targetEntityMapping'] = Arrays::mergeTree($config['targetEntityMapping'], $targetEntities); } if ($extension instanceof EventSubscriberProvider) { $subscribers = $extension->getEventSubscribers(); Validators::assert($subscribers, 'array'); $config['eventSubscribers'] = array_merge($config['eventSubscribers'], $subscribers); } } }
public function __construct($parent, $name) { parent::__construct($parent, $name); $treeNodeId = $this->presenter->getParam('id'); $labelId = $this->presenter->getParam('labelId'); $entity = $this->presenter->getParam('entity'); if ($entity === NULL) { // determine entity by $treeNodeId if ($treeNodeId === NULL) { throw new \Nette\InvalidArgumentException("Unable to determine entity"); } $entity = $this->presenter->pageModel->getEntity($treeNodeId); } // load page configuration $entityConfig = $this->presenter->configLoaderService->loadEntityConfig($entity); $this->properties = $this->presenter->extModel->filterEntityProperties($entityConfig['properties'], $labelId); $this->createUrl = TRUE; if (isset($entityConfig['entityMeta']) && isset($entityConfig['entityMeta']['createUrl'])) { if (!$entityConfig['entityMeta']['createUrl']) { $this->createUrl = FALSE; } } $labelProperties = array(); $label = NULL; // for proper form generation...$labelId must be known if (!empty($labelId)) { // load all label extensions $allExtensions = $this->presenter->configLoaderService->loadLabelExtentsionProperties(); $labelProperties = $this->presenter->pageManagerService->intersectLabelProperties($labelId, $allExtensions); $this->properties = array_merge($this->properties, $labelProperties); // sort properties $extSortOrder = $this->presenter->extModel->loadExtSorting($labelId); if ($extSortOrder) { $extSorting = NULL; if ($extSorting = \Bubo\Utils\MultiValues::unserialize($extSortOrder)) { uksort($this->properties, function ($a, $b) use($extSorting) { $aPos = array_search(str_replace('_', '*', $a), $extSorting); $bPos = array_search(str_replace('_', '*', $b), $extSorting); if ($aPos !== FALSE && $bPos !== FALSE) { return $aPos - $bPos; } else { if ($aPos === FALSE) { return -1; } else { return 1; } } }); } } $label = $this->presenter->pageManagerService->getLabel($labelId); } // getLanguages $langs = $originalLangs = $this->presenter->langManagerService->getLangs(); $alienLangs = array(); $referencingPages = NULL; if ($treeNodeId !== NULL) { //$defaults = $this->presenter->pageManagerService->getDefaults($treeNodeId, $this->presenter->getParam('waiting')); $referencingPages = $this->presenter->pageModel->getReferencingPages($treeNodeId); $alienLangs = $this->presenter->langManagerService->getAlienLangs($referencingPages, $langs); $langs = $langs + $alienLangs; } $pageNameListeners = array('title', 'link_title', 'menu_title', 'page_title', 'url_name'); if ($this->presenter->preselectedParent !== NULL) { if (is_array($this->presenter->preselectedParent)) { $this->addSelect('parent', "Parent", $this->presenter->preselectedParent)->setPrompt(':: Vyberte předka ::')->setRequired('Musíte vybrat předka'); $this['parent']->getControlPrototype()->style = 'font-family:monospace;float:right;z-index:250;font-size:12px;'; } else { $this->addHidden('parent', $this->presenter->preselectedParent); } } else { // parent select //dump($entityConfig); $disablePagesWithNoUrl = isset($entityConfig['entityMeta']['createUrl']) ? $entityConfig['entityMeta']['createUrl'] : FALSE; //dump($disablePagesWithNoUrl); $st = new \BuboApp\AdminModule\Components\SelectTraverser($this->presenter, $treeNodeId, NULL, $disablePagesWithNoUrl); $selectData = $st->getSelectMenu($this->presenter['structureManager']->getLanguage()); $this->addSelect('parent', "Parent", $selectData)->setPrompt(':: Vyberte předka ::')->setRequired('Musíte vybrat předka'); $this['parent']->getControlPrototype()->style = 'font-family:monospace;float:right;z-index:250;font-size:12px;'; } $this->addHidden('entity'); $identity = $this->presenter->getUser()->getIdentity(); $editorId = $identity ? $identity->id : NULL; $mandatoryProperties = $this->presenter->configLoaderService->loadMandatoryProperties(); $langForms = array(); if (!empty($this->properties)) { // container with checkboxes $publishContainer = $this->addContainer('lang_versions'); foreach ($langs as $langCode => $language) { $publishContainer->addCheckbox($langCode); } // language containers foreach ($langs as $langCode => $language) { // !! create language section $langForms[$langCode] = $this->addContainer($langCode); // dump($mandatoryProperties); // die(); // mandatory parameters (will be in all pageForms??) foreach ($mandatoryProperties as $key => $array) { $formItem = NULL; switch ($array['type']) { case 'text': $formItem = $langForms[$langCode]->addText($key, $array['label']); break; case 'textArea': $formItem = $langForms[$langCode]->addTextArea($key, $array['label']); break; } if ($formItem !== NULL) { if (isset($array['class'])) { $formItem->getControlPrototype()->class[] = $array['class']; } $formItem->getLabelPrototype()->title = '_' . $key; } // manage classes for name and its listeners if ($key == 'name') { $formItem->getControlPrototype()->class[] = '_page_name_' . $langCode; } else { if (in_array($key, $pageNameListeners)) { $formItem->getControlPrototype()->class[] = '_page_name_listener_' . $langCode; } } } $langForms[$langCode]->addText('parent_url')->addConditionOn($langForms[$langCode]['name'], Form::FILLED)->addRule(~Form::EQUAL, 'Předek je duch. Pro uložení stránky v této mutaci je potřeba nejprve vytvořit předka.', '_undefin@_'); // dump($labelProperties); // die(); // parameters loaded from page configuration foreach ($this->properties as $propertyName => $property) { $formItem = NULL; if (isset($property['engine'])) { switch ($property['engine']) { case 'media': switch ($property['type']) { case 'mediaFile': $formItem = $langForms[$langCode]->addMediaFile($propertyName, $property['label']); break; case 'mediaGallery': $formItem = $langForms[$langCode]->addMediaFile($propertyName, $property['label']); break; } break; case 'label': $currentLanguage = $this->presenter['structureManager']->getLanguage(); $st = new \BuboApp\AdminModule\Components\SelectTraverser($this->presenter); $label = $this->presenter->pageManagerService->getLabelByName($property['bind']['labelName']); $selectData = array(); if ($label !== NULL) { $labelRoots = $this->presenter->pageManagerService->getLabelRoots($label['label_id'], $currentLanguage); $myRoot = reset($labelRoots); $st->setTopLevelPage($myRoot); $st->hideRootElement(); $selectData = $st->getSelectMenu($currentLanguage); } $formItem = $langForms[$langCode]->addSelect($propertyName, $property['label'], $selectData); if (isset($property['prompt'])) { $formItem->setPrompt($property['prompt']); } $formItem->getControlPrototype()->style = 'font-family:monospace;font-size:12px;'; } } else { switch ($property['type']) { case 'text': case 'external_url': $formItem = $langForms[$langCode]->addText($propertyName, $property['label']); if (isset($property['class'])) { $formItem->getControlPrototype()->class = $property['class']; } break; case 'textArea': $formItem = $langForms[$langCode]->addTextArea($propertyName, $property['label']); if (isset($property['class'])) { $formItem->getControlPrototype()->class = $property['class']; } break; case 'checkbox': $formItem = $langForms[$langCode]->addCheckbox($propertyName, $property['label']); if (isset($property['class'])) { $formItem->getControlPrototype()->class = $property['class']; } break; case 'select': $selectData = isset($property['data']) ? $property['data'] : call_user_func_array(array($this->presenter, $property['method']), array()); $formItem = $langForms[$langCode]->addSelect($propertyName, $property['label'], $selectData); if (isset($property['prompt'])) { $formItem->setPrompt($property['prompt']); } if (isset($property['required'])) { $formItem->setRequired($property['required']); } break; case 'color': $formItem = $langForms[$langCode]->addText($propertyName, $property['label']); $formItem->getControlPrototype()->type = 'color'; break; } } if ($formItem !== NULL) { $formItem->getLabelPrototype()->title = '_' . $propertyName; } } } } $this->addSubmit('send', 'Proveď'); $this->addSubmit('cancel', 'Cancel')->setValidationScope(FALSE); $whatToPublish = array('none' => 'Uložit a nepublikovat nic', 'selected' => 'Uložit a publikovat vybrané', 'all' => 'Uložit a publikovat vše'); $this->addSelect('what_to_publish', '', $whatToPublish)->addRule(array($this, 'draftNotInFuture'), 'Draft nemůže mít odloženou publikaci', $this)->addRule(array($this, 'atLeastOnePageFilled'), 'Vyplňte alespoň jednu stránku', $this)->getControlPrototype()->style = 'display: inline;'; // load templates -> get only existing and with nice names (if possible) $loadTemplatesWithUrl = TRUE; if (isset($entityConfig['entityMeta']) && isset($entityConfig['entityMeta']['createUrl'])) { $loadTemplatesWithUrl = $entityConfig['entityMeta']['createUrl']; } else { throw new Nette\InvalidArgumentException("Missing parameter 'createUrl' in entity config"); } $_templates = $this->presenter->projectManagerService->getListOfTemplates($loadTemplatesWithUrl); $templateConfig = $this->presenter->configLoaderService->loadLayoutConfig(); $res = \Nette\Utils\Arrays::mergeTree($templateConfig['layouts'], $_templates); $templates = array_intersect_key($res, $_templates); // any entity template restriction? if (isset($entityConfig['templates']) && isset($entityConfig['templates']['restrict'])) { $templates = array_intersect_key($templates, array_flip($entityConfig['templates']['restrict'])); if (empty($templates)) { throw new \Nette\InvalidStateException('Template restriction is empty.'); } } // any entity template exclusion? if (isset($entityConfig['templates']) && isset($entityConfig['templates']['exclude'])) { $templates = array_diff_key($templates, array_flip($entityConfig['templates']['exclude'])); if (empty($templates)) { throw new \Nette\InvalidStateException('Template exlusion is empty.'); } } // dump($templates); // die(); // // dump($templates, $entityConfig); // die(); // if (isset($_templates['headless'])) { // $res = \Nette\Utils\Arrays::mergeTree($templateConfig['layouts'], $_templates['headless']); // $templates['Stránky bez url'] = array_intersect_key($res, $_templates['headless']); // } $this->addSelect('layout', 'Šablona', $templates); // dump($label); // die(); if ($label && $label['lock_layout'] == 1) { $this['layout']->setDisabled(); // dump($label); // die(); } $this['send']->getControlPrototype()->class = "submit"; $this['cancel']->getControlPrototype()->class = "submit"; //$this['send']->addRule(callback($this, 'newUrlUniqueValidator'), '', $this); // if (!$isEditable) { // foreach ($this->getComponents() as $component) { // $component->setDisabled(); // } // } $this->getElementPrototype()->onsubmit('tinyMCE.triggerSave()'); switch ($this->getPresenter()->getAction()) { case 'default': // edit $this->addSubmit('move_to_trash', 'Hodit do koše')->setValidationScope(FALSE); $this->onSuccess[] = array($this, 'editFormSubmited'); if (!$this->isSubmitted()) { // dump($alienLangs); // die(); $defaults = $this->presenter->pageManagerService->getDefaults($treeNodeId, $this->presenter->getParam('waiting'), array_keys($alienLangs)); //\Nette\Diagnostics\Debugger::$maxDepth = 8; // dump($defaults); // die(); $currentDefault = reset($defaults); // $currentDefault = current($ccurrentDefault); //$allLanguages = $this->presenter->langManagerService->getLangs(); $defaultLanguage = $this->presenter->langManagerService->getDefaultLanguage(); $urls = $this->presenter->pageModel->getPagesUrls($currentDefault['parent'], array_keys($originalLangs), $defaultLanguage); $alienUrls = $this->presenter->pageModel->getAlienPagesUrls($referencingPages, $alienLangs, $this->presenter->langManagerService); $alienTabUrls = $this->presenter->pageModel->getAlienTabUrls($alienLangs, $alienUrls); //dump($referencingPages); // dump($referencingPages, $alienUrls); // $this->presenter->pageModel->getAllAlienUrls($referencingPages, $alienUrls, $this->presenter->langManagerService); // die(); // die(); $urls = $urls + $alienTabUrls; // add urls to defauls (even to nonexisting lang sections!) if (!empty($urls)) { foreach ($urls as $langCode => $parentUrl) { $defaults[$langCode]['parent_url'] = $urls[$langCode]['parent_url']; } } // dump($currentDefault); $defaults['parent'] = $currentDefault['parent']; $defaults['layout'] = $currentDefault['layout']; $defaults['entity'] = $entity; // expand extended values $identifiers = array(); foreach ($langs as $langCode => $langName) { if (isset($defaults[$langCode]) && isset($defaults[$langCode]['time_zone'])) { foreach ($defaults[$langCode]['time_zone'] as $timeZoneFlag => $timeZone) { foreach ($timeZone as $status => $labels) { foreach ($labels as $labelId => $pageData) { // unset($defaults[$langCode]['time_zone'][$timeZoneFlag][$status][$labelId]['ext_identifier']); // unset($defaults[$langCode]['time_zone'][$timeZoneFlag][$status][$labelId]['ext_value']); if (!empty($pageData['ext_identifier'])) { foreach ($pageData['ext_identifier'] as $extIdentifier => $d) { if ($extIdentifier != "") { if (isset($labelProperties) && isset($labelProperties['ext_' . $extIdentifier])) { $identifiers[$langCode]['ext_' . $extIdentifier] = $d['ext_value']; } } } } } } } } } // dump($defaults); // die(); // dump($allExtensions, $identifiers); // die(); $newDefaults = \Nette\Utils\Arrays::mergeTree($defaults, $identifiers); //dump($newDefaults); $this->setDefaults($newDefaults); } //$defaults = $this->presenter->pageManagerService->getDefaults($treeNodeId); break; case 'addPage': case 'addScrap': $this->onSuccess[] = array($this, 'addformSubmited'); if (!$this->isSubmitted()) { //$allLanguages = $this->presenter->langManagerService->getLangs(); $defaultLanguage = $this->presenter->langManagerService->getDefaultLanguage(); $defaults = $this->presenter->pageModel->getPagesUrls(NULL, array_keys($langs), $defaultLanguage); $defaults['entity'] = $entity; // dump($entity); // die(); if ($label) { //dump($label); $defaults['layout'] = $label['layout']; } if ($this->presenter->preselectedParent !== NULL && !is_array($this->presenter->preselectedParent)) { //$this->addHidden('parent', $this->presenter->preselectedParent); $urls = $this->presenter->pageModel->getPagesUrls($this->presenter->preselectedParent, array_keys($langs), $defaultLanguage); // add urls to defauls (even to nonexisting lang sections!) if (!empty($urls)) { foreach ($urls as $langCode => $parentUrl) { $defaults[$langCode]['parent_url'] = $urls[$langCode]['parent_url']; } } } $this->setDefaults($defaults); } break; } $this->onError[] = array($this, 'invalidSubmit'); }
protected function processEntityManager($name, array $defaults) { $builder = $this->getContainerBuilder(); $config = $this->resolveConfig($defaults, $this->managerDefaults, $this->connectionDefaults); if ($isDefault = !isset($builder->parameters[$this->name]['orm']['defaultEntityManager'])) { $builder->parameters[$this->name]['orm']['defaultEntityManager'] = $name; } $metadataDriver = $builder->addDefinition($this->prefix($name . '.metadataDriver'))->setClass('Doctrine\\Common\\Persistence\\Mapping\\Driver\\MappingDriverChain')->setAutowired(FALSE)->setInject(FALSE); /** @var Nette\DI\ServiceDefinition $metadataDriver */ Validators::assertField($config, 'metadata', 'array'); Validators::assertField($config, 'targetEntityMappings', 'array'); $config['targetEntityMappings'] = $this->normalizeTargetEntityMappings($config['targetEntityMappings']); foreach ($this->compiler->getExtensions() as $extension) { if ($extension instanceof IEntityProvider) { $metadata = $extension->getEntityMappings(); Validators::assert($metadata, 'array'); $config['metadata'] = array_merge($config['metadata'], $metadata); } if ($extension instanceof ITargetEntityProvider) { $targetEntities = $extension->getTargetEntityMappings(); Validators::assert($targetEntities, 'array'); $config['targetEntityMappings'] = Nette\Utils\Arrays::mergeTree($config['targetEntityMappings'], $this->normalizeTargetEntityMappings($targetEntities)); } if ($extension instanceof IDatabaseTypeProvider) { $providedTypes = $extension->getDatabaseTypes(); Validators::assert($providedTypes, 'array'); if (!isset($defaults['types'])) { $defaults['types'] = array(); } $defaults['types'] = array_merge($defaults['types'], $providedTypes); } } foreach (self::natSortKeys($config['metadata']) as $namespace => $driver) { $this->processMetadataDriver($metadataDriver, $namespace, $driver, $name); } $this->processMetadataDriver($metadataDriver, 'Kdyby\\Doctrine', __DIR__ . '/../Entities', $name); if (empty($config['metadata'])) { $metadataDriver->addSetup('setDefaultDriver', array(new Statement($this->metadataDriverClasses[self::ANNOTATION_DRIVER], array(array($builder->expand('%appDir%')), 2 => $this->prefix('@cache.' . $name . '.metadata'))))); } if ($config['repositoryFactoryClassName'] === 'default') { $config['repositoryFactoryClassName'] = 'Doctrine\\ORM\\Repository\\DefaultRepositoryFactory'; } $builder->addDefinition($this->prefix($name . '.repositoryFactory'))->setClass($config['repositoryFactoryClassName'])->setAutowired(FALSE); Validators::assertField($config, 'namespaceAlias', 'array'); Validators::assertField($config, 'hydrators', 'array'); Validators::assertField($config, 'dql', 'array'); Validators::assertField($config['dql'], 'string', 'array'); Validators::assertField($config['dql'], 'numeric', 'array'); Validators::assertField($config['dql'], 'datetime', 'array'); Validators::assertField($config['dql'], 'hints', 'array'); $autoGenerateProxyClasses = is_bool($config['autoGenerateProxyClasses']) ? $config['autoGenerateProxyClasses'] ? AbstractProxyFactory::AUTOGENERATE_ALWAYS : AbstractProxyFactory::AUTOGENERATE_NEVER : $config['autoGenerateProxyClasses']; $configuration = $builder->addDefinition($this->prefix($name . '.ormConfiguration'))->setClass('Kdyby\\Doctrine\\Configuration')->addSetup('setMetadataCacheImpl', array($this->processCache($config['metadataCache'], $name . '.metadata')))->addSetup('setQueryCacheImpl', array($this->processCache($config['queryCache'], $name . '.query')))->addSetup('setResultCacheImpl', array($this->processCache($config['resultCache'], $name . '.ormResult')))->addSetup('setHydrationCacheImpl', array($this->processCache($config['hydrationCache'], $name . '.hydration')))->addSetup('setMetadataDriverImpl', array($this->prefix('@' . $name . '.metadataDriver')))->addSetup('setClassMetadataFactoryName', array($config['classMetadataFactory']))->addSetup('setDefaultRepositoryClassName', array($config['defaultRepositoryClassName']))->addSetup('setQueryBuilderClassName', array($config['queryBuilderClassName']))->addSetup('setRepositoryFactory', array($this->prefix('@' . $name . '.repositoryFactory')))->addSetup('setProxyDir', array($config['proxyDir']))->addSetup('setProxyNamespace', array($config['proxyNamespace']))->addSetup('setAutoGenerateProxyClasses', array($autoGenerateProxyClasses))->addSetup('setEntityNamespaces', array($config['namespaceAlias']))->addSetup('setCustomHydrationModes', array($config['hydrators']))->addSetup('setCustomStringFunctions', array($config['dql']['string']))->addSetup('setCustomNumericFunctions', array($config['dql']['numeric']))->addSetup('setCustomDatetimeFunctions', array($config['dql']['datetime']))->addSetup('setDefaultQueryHints', array($config['dql']['hints']))->addSetup('setNamingStrategy', CacheHelpers::filterArgs($config['namingStrategy']))->addSetup('setQuoteStrategy', CacheHelpers::filterArgs($config['quoteStrategy']))->addSetup('setEntityListenerResolver', CacheHelpers::filterArgs($config['entityListenerResolver']))->setAutowired(FALSE)->setInject(FALSE); /** @var Nette\DI\ServiceDefinition $configuration */ $builder->addDefinition($this->prefix($name . '.proxyAutoloader'))->setClass('Kdyby\\Doctrine\\Proxy\\ProxyAutoloader')->setArguments(array($config['proxyDir'], $config['proxyNamespace']))->addTag(Kdyby\Events\DI\EventsExtension::SUBSCRIBER_TAG)->setAutowired(FALSE)->setInject(FALSE); $this->proxyAutoloaders[$config['proxyNamespace']] = $config['proxyDir']; $this->processSecondLevelCache($name, $config['secondLevelCache'], $isDefault); Validators::assertField($config, 'filters', 'array'); foreach ($config['filters'] as $filterName => $filterClass) { $configuration->addSetup('addFilter', array($filterName, $filterClass)); } if ($config['targetEntityMappings']) { $configuration->addSetup('setTargetEntityMap', array(array_map(function ($mapping) { return $mapping['targetEntity']; }, $config['targetEntityMappings']))); $this->targetEntityMappings = Nette\Utils\Arrays::mergeTree($this->targetEntityMappings, $config['targetEntityMappings']); } $builder->addDefinition($this->prefix($name . '.evm'))->setClass('Kdyby\\Events\\NamespacedEventManager', array(Kdyby\Doctrine\Events::NS . '::'))->addSetup('$dispatchGlobalEvents', array(TRUE))->setAutowired(FALSE); // entity manager $entityManager = $builder->addDefinition($managerServiceId = $this->prefix($name . '.entityManager'))->setClass('Kdyby\\Doctrine\\EntityManager')->setFactory('Kdyby\\Doctrine\\EntityManager::create', array($connectionService = $this->processConnection($name, $defaults, $isDefault), $this->prefix('@' . $name . '.ormConfiguration'), $this->prefix('@' . $name . '.evm')))->addTag(self::TAG_ENTITY_MANAGER)->addTag('kdyby.doctrine.entityManager')->setAutowired($isDefault)->setInject(FALSE); if ($this->isTracyPresent()) { $entityManager->addSetup('?->bindEntityManager(?)', array($this->prefix('@' . $name . '.diagnosticsPanel'), '@self')); } if ($isDefault && $config['defaultRepositoryClassName'] === 'Kdyby\\Doctrine\\EntityDao') { // syntax sugar for config $builder->addDefinition($this->prefix('dao'))->setClass('Kdyby\\Doctrine\\EntityDao')->setFactory('@Kdyby\\Doctrine\\EntityManager::getDao', array(new Code\PhpLiteral('$entityName')))->setParameters(array('entityName'))->setInject(FALSE); // interface for models & presenters $builder->addDefinition($this->prefix('daoFactory'))->setClass('Kdyby\\Doctrine\\EntityDao')->setFactory('@Kdyby\\Doctrine\\EntityManager::getDao', array(new Code\PhpLiteral('$entityName')))->setParameters(array('entityName'))->setImplement('Kdyby\\Doctrine\\EntityDaoFactory')->setInject(FALSE)->setAutowired(TRUE); } $builder->addDefinition($this->prefix('repositoryFactory.' . $name . '.defaultRepositoryFactory'))->setClass($config['defaultRepositoryClassName'])->setImplement('Kdyby\\Doctrine\\DI\\IRepositoryFactory')->setArguments([new Code\PhpLiteral('$entityManager'), new Code\PhpLiteral('$classMetadata')])->setParameters(array('Doctrine\\ORM\\EntityManagerInterface entityManager', 'Doctrine\\ORM\\Mapping\\ClassMetadata classMetadata'))->setAutowired(FALSE); $this->configuredManagers[$name] = $managerServiceId; $this->managerConfigs[$name] = $config; }
/** * Nastavi prvni prazdnou hodnotu do pole * @param array $array * @return array */ public function addPrompt($array) { return Arrays::mergeTree(['' => ''], $array); }
protected function createComponentSongList($name) { $grid = new Grido\Grid($this, $name); $grid->setModel($this->songy); $grid->addColumnDate("datum", "Datum", "d.m.y")->setSortable(); $grid->addColumnText("interpret_name", "Interpret")->setCustomRender(function ($item) { $template = $this->createTemplate(); $template->setFile(__DIR__ . "/../templates/components/Grid/interpret.latte"); $template->song = $item; return $template; })->setSortable()->setFilterText()->setSuggestion(); $grid->addColumnText("name", "Song")->setCustomRender(function ($item) { $template = $this->createTemplate(); $template->setFile(__DIR__ . "/../templates/components/Grid/song.latte"); $template->song = $item; return $template; })->setSortable()->setFilterText()->setSuggestion(); $filter = array('' => 'Všechny'); $filter = \Nette\Utils\Arrays::mergeTree($filter, $this->zanry->getList()); $grid->addColumnText("zanr_id", "Žánr")->setCustomRender(function ($item) { return $item->zanr ? $item->zanr->name : null; })->setFilterSelect($filter); $grid->addColumnText("zadatel", "Přidal(a)")->setCustomRender(function ($item) { $template = $this->createTemplate(); $template->setFile(__DIR__ . "/../templates/components/Grid/zadatel.latte"); $template->song = $item; return $template; })->setSortable()->setFilterText()->setSuggestion(); $statuses = array('' => 'Všechny', 'approved' => 'Zařazené', 'rejected' => 'Vyřazené', 'waiting' => 'Čekající'); $grid->addColumnText("status", "Status")->setCustomRender(function ($item) { $status = $item->status; $revizor = $item->revisor ? $item->ref("user", "revisor")->username : "******"; switch ($status) { case "approved": return Html::el("span", array("class" => "label label-success", "title" => "Schválil(a) " . $revizor))->setText("Zařazen"); case "waiting": return Html::el("span", array("class" => "label label-warning", "title" => "Čeká ve frontě ke schválení"))->setText("Čeká"); case "rejected": return Html::el("span", array("class" => "label label-danger", "title" => "Zamítl(a) " . $revizor))->setText("Vyřazen"); default: return Html::el("i")->setText("Neznámý"); } })->setSortable()->setFilterSelect($statuses); $grid->addColumnText("vzkaz", "Vzkaz DJovi")->setCustomRender(function ($item) { $elm = Html::el("span"); if ($item->private_vzkaz) { if (!$this->user->isAllowed("privateMsg", "view") && $this->user->id != $item->user_id) { $elm->addAttributes(array("class" => "msg-hidden", "title" => "Tento vzkaz je určen pouze pro DJe")); $elm->setText("Soukromý vzkaz"); return $elm; } $elm->addAttributes(array("class" => "msg-private", "title" => "Tento vzkaz je určen pouze pro DJe")); $elm->setText($item->vzkaz); } else { return $item->vzkaz; } return $elm; }); $myLikes = $this->songList->getMyLikes($this->user); $grid->addColumnText("likes", "")->setCustomRender(function ($item) use($myLikes) { $likes = count($item->related('song_likes')); $isLiked = isset($myLikes[$item->id]) ?: false; $el = Html::el('a')->addAttributes(['class' => 'like' . ($isLiked ? ' liked' : '')]); $el->add(Html::el('i')->addAttributes(['class' => 'glyphicon glyphicon-heart'])); $el->add(Html::el()->setText(' ' . $likes)); $el->href($this->link('like!', ['id' => $item->id])); return $el; }); if ($this->user->isAllowed("song", "approve")) { $grid->addActionHref("approve", "")->setIcon("ok")->setElementPrototype(Html::el("a", array("class" => "btn btn-success", "data-toggle" => "modal", "data-target" => ".modal"))); } if ($this->user->isAllowed("song", "reject")) { $grid->addActionHref("reject", "")->setIcon("remove")->setElementPrototype(Html::el("a", array("class" => "btn btn-danger", "data-toggle" => "modal", "data-target" => ".modal"))); } if ($this->user->isAllowed("song", "play")) { $grid->addActionHref("play", "")->setDisable(function ($item) { if ($item->link) { return false; } return true; })->setIcon("play")->setElementPrototype(Html::el("a", array("class" => "btn btn-info", "data-toggle" => "modal", "data-target" => ".modal"))); } if ($this->user->isAllowed("song", "edit")) { $grid->addActionHref("edit", "", "admin:song:editor")->setIcon("pencil")->setElementPrototype(Html::el("a", array("class" => "btn btn-default", "target" => "_blank"))); } $grid->setFilterRenderType(\Grido\Components\Filters\Filter::RENDER_OUTER); $grid->setDefaultSort(array("datum" => "DESC")); //Set face for grid $gridTemplate = __DIR__ . "/../templates/components/Grid.latte"; if (file_exists($gridTemplate)) { $grid->setTemplateFile($gridTemplate); } return $grid; }
protected function _hladajClanok($hlm, $language_id) { //Otestuj vstupy if (!isset($language_id)) { return array("error" => "Nie je zadané language_id!"); } //Prirad tabulky, ktore nemam $hlavne_menu_lang = $this->connection->table('hlavne_menu_lang'); $clanok_lang = $this->connection->table('clanok_lang'); //Najdi v tabulke clanok polozku podla id clanku $najdi_clanok = $this->getTable()->get($hlm->clanok); if ($najdi_clanok === FALSE || count($najdi_clanok) == 0) { return array("error" => "Nenájdená položka v tabulke clanok! - " . $hlm->clanok); } //Najdi v tabulke hlavne_menu_lang polozku podla id_lang, id_hlavne_menu - nazov, h1part2, description $texty_hl_menu = $hlavne_menu_lang->where("id_hlavne_menu", $hlm->id); if ($texty_hl_menu === FALSE || count($texty_hl_menu) == 0) { return array("error" => "Nenájdená položka v tabulke hlavne_menu_lang! - " . $hlm->id); } //Najdi v tabulke clanok_lang polozku podla id $texty_clanku = $clanok_lang->where("id_clanok", $hlm->clanok); if ($texty_clanku === FALSE || count($texty_clanku) == 0) { return array("error" => "Nenájdená položka v tabulke clanok_lang! - " . $hlm->clanok); } //Ak mam vsetko poslam to na vystup $out = array("hlavne_menu" => $hlm, "clanok" => $najdi_clanok, "lang" => $language_id); if ($language_id) { //Jeden jazyk $texty_hl_menu = $texty_hl_menu->where("id_lang", $language_id)->limit(1)->fetch(); $texty_clanku = $texty_clanku->where("id_lang", $language_id)->limit(1)->fetch(); $out["texty"][$language_id] = array("nazov" => $texty_hl_menu->nazov, "h1part2" => $texty_hl_menu->h1part2, "description" => $texty_hl_menu->description, "text" => $texty_clanku->text, "anotacia" => $texty_clanku->anotacia); } else { //Viac jazykov $pomh = array(); $pomc = array(); $ja = $this->connection->table('lang'); foreach ($ja as $j) { $prototip[$j->id] = array("nazov" => "", "h1part2" => "", "description" => "", "text" => "", "anotacia" => "", "jazyk_skr" => $j->skratka); } foreach ($texty_hl_menu as $hl_txt) { $pomh[$hl_txt->id_lang] = array("nazov" => $hl_txt->nazov, "h1part2" => $hl_txt->h1part2, "description" => $hl_txt->description, "jazyk_skr" => $hl_txt->lang->skratka); } foreach ($texty_clanku as $cl_txt) { $pomc[$cl_txt->id_lang] = array("text" => $cl_txt->text, "anotacia" => $cl_txt->anotacia, "jazyk_skr" => $cl_txt->lang->skratka); } $out["texty"] = Arrays::mergeTree($pomh, $pomc); $out["texty"] = Arrays::mergeTree($out["texty"], $prototip); // dump($out["texty"]); // die(); } return $out; }
/** * Internal: receives submitted HTTP data. * @return array */ protected function receiveHttpData() { $httpRequest = $this->getHttpRequest(); if (strcasecmp($this->getMethod(), $httpRequest->getMethod())) { return; } if ($httpRequest->isMethod('post')) { $data = Nette\Utils\Arrays::mergeTree($httpRequest->getPost(), $httpRequest->getFiles()); } else { $data = $httpRequest->getQuery(); } if ($tracker = $this->getComponent(self::TRACKER_ID, FALSE)) { if (!isset($data[self::TRACKER_ID]) || $data[self::TRACKER_ID] !== $tracker->getValue()) { return; } } return $data; }
<?php require_once __DIR__ . '/../vendor/autoload.php'; require_once __DIR__ . '/../app/TransactionReader.php'; if (!file_exists(__DIR__ . '/../../adminAndMobile/app/config/config.local.neon')) { die('Configuration file config.local.neon is missing!'); } if (!file_exists(__DIR__ . '/../../adminAndMobile/app/config/config.neon')) { die('Configuration file config.neon is missing!'); } $config1 = \Nette\Neon\Neon::decode(file_get_contents(__DIR__ . '/../../adminAndMobile/app/config/config.neon')); $config2 = \Nette\Neon\Neon::decode(file_get_contents(__DIR__ . '/../../adminAndMobile/app/config/config.local.neon')); $config = \Nette\Utils\Arrays::mergeTree($config1, $config2); $host = $config['parameters']['host']; $dbName = $config['parameters']['dbname']; $username = $config['parameters']['user']; $password = $config['parameters']['password'] ?? ''; $addressLockTime = $config['parameters']['addressLockTime']; $port = $config['doctrine']['port']; try { $reader = new TransactionReader($host, $dbName, $username, $password, $addressLockTime, $port); $reader->run(); } catch (\Exception $e) { $logger = new \Zend\Log\Logger(); $fileWriter = new \Zend\Log\Writer\Stream(__DIR__ . "/log.txt"); $logger->addWriter($fileWriter); $logger->err($e->getMessage()); die; } //$reader->transactionReceived('12U1QLFTMTyAFqEzrsH4G4jS8EeWbB1EnJ');
/** * Reads configuration from INI file. * @param string file name * @return array * @throws Nette\InvalidStateException */ public static function load($file) { if (!is_file($file) || !is_readable($file)) { throw new Nette\FileNotFoundException("File '{$file}' is missing or is not readable."); } Nette\Diagnostics\Debugger::tryError(); $ini = parse_ini_file($file, TRUE); if (Nette\Diagnostics\Debugger::catchError($e)) { throw new Nette\InvalidStateException('parse_ini_file(): ' . $e->getMessage(), 0, $e); } $separator = trim(self::$sectionSeparator); $data = array(); foreach ($ini as $secName => $secData) { // is section? if (is_array($secData)) { if (substr($secName, -1) === self::$rawSection) { $secName = substr($secName, 0, -1); } elseif (self::$keySeparator) { // process key separators (key1> key2> key3) $tmp = array(); foreach ($secData as $key => $val) { $cursor =& $tmp; foreach (explode(self::$keySeparator, $key) as $part) { if (!isset($cursor[$part]) || is_array($cursor[$part])) { $cursor =& $cursor[$part]; } else { throw new Nette\InvalidStateException("Invalid key '{$key}' in section [{$secName}] in file '{$file}'."); } } $cursor = $val; } $secData = $tmp; } // process extends sections like [staging < production] (with special support for separator ':') $parts = $separator ? explode($separator, strtr($secName, ':', $separator)) : array($secName); if (count($parts) > 1) { $parent = trim($parts[1]); if (!isset($data[$parent]) || !is_array($data[$parent])) { throw new Nette\InvalidStateException("Missing parent section [{$parent}] in file '{$file}'."); } $secData = array_reverse(Nette\Utils\Arrays::mergeTree(array_reverse($secData, TRUE), array_reverse($data[$parent], TRUE)), TRUE); $secName = trim($parts[0]); if ($secName === '') { throw new Nette\InvalidStateException("Invalid empty section name in file '{$file}'."); } } } if (self::$keySeparator) { $cursor =& $data; foreach (explode(self::$keySeparator, $secName) as $part) { if (!isset($cursor[$part]) || is_array($cursor[$part])) { $cursor =& $cursor[$part]; } else { throw new Nette\InvalidStateException("Invalid section [{$secName}] in file '{$file}'."); } } } else { $cursor =& $data[$secName]; } if (is_array($secData) && is_array($cursor)) { $secData = Nette\Utils\Arrays::mergeTree($secData, $cursor); } $cursor = $secData; } return $data; }
/** * @param array|string $post * @param array $files * * @throws NotSupportedException * @return CurlWrapper */ public function setPost($post = array(), array $files = NULL) { if ($files) { if (!is_array($post)) { throw new NotSupportedException("Not implemented."); } array_walk_recursive($files, function (&$item) { if (PHP_VERSION_ID >= 50500) { $pathname = realpath($item); $type = finfo_file(finfo_open(FILEINFO_MIME_TYPE), $pathname); $item = new \CurlFile($pathname, strpos($type, '/') ? $type : 'application/octet-stream', basename($item)); } else { $item = '@' . realpath($item); } }); $post = Nette\Utils\Arrays::mergeTree($post, $files); $this->setHeader('Content-Type', 'multipart/form-data'); } if ($post) { return $this->setOptions(array('post' => TRUE, 'postFields' => is_array($post) ? Helpers::flattenArray($post) : $post)); } return $this->setOptions(array('post' => NULL, 'postFields' => NULL)); }