code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
public function hydrate(array $data, $object) { if (!is_object($object)) { throw new RuntimeException( sprintf('%s expects the provided $object to be a PHP object', __METHOD__) ); } return (function (array $data) { foreach ($data as $property => $value) { if (!property_exists($this, $property)) { throw new RuntimeException( sprintf( 'Property "%s" does not exist in "%s" class.', $property, get_class($this) ) ); } $this->{$property} = $value; } return $this; })->call($object, $data); }
Hydrate $object with the provided $data. @param array<string, mixed> $data @param object $object @return mixed
private function filterUntranslatedBlocks(iterable $blocks, ?array $locales, bool $useMainLocale): Generator { foreach ($blocks as $block) { try { yield $this->mapper->mapBlock($block, $locales, $useMainLocale); } catch (NotFoundException $e) { // Block does not have the translation, skip it } } }
Returns all blocks from provided input, with all untranslated blocks filtered out.
private function internalMoveBlock(PersistenceBlock $block, PersistenceBlock $targetBlock, string $placeholder, int $position): PersistenceBlock { return $this->transaction( function () use ($block, $targetBlock, $placeholder, $position): PersistenceBlock { if ($block->parentId === $targetBlock->id && $block->placeholder === $placeholder) { return $this->blockHandler->moveBlockToPosition($block, $position); } return $this->blockHandler->moveBlock( $block, $targetBlock, $placeholder, $position ); } ); }
Moves a block to specified target block and placeholder and position. This is an internal method unifying moving a block to a zone and to a parent block.
private function internalDisableTranslations(PersistenceBlock $block): PersistenceBlock { $block = $this->blockHandler->updateBlock( $block, BlockUpdateStruct::fromArray( [ 'isTranslatable' => false, ] ) ); foreach ($block->availableLocales as $locale) { if ($locale !== $block->mainLocale) { $block = $this->blockHandler->deleteBlockTranslation( $block, $locale ); } } foreach ($this->blockHandler->loadChildBlocks($block) as $childBlock) { $this->internalDisableTranslations($childBlock); } return $block; }
Disables the translations on provided block and removes all translations keeping only the main one.
public function mapCollection(PersistenceCollection $collection, ?array $locales = null, bool $useMainLocale = true): Collection { $locales = is_array($locales) && count($locales) > 0 ? $locales : [$collection->mainLocale]; if ($useMainLocale && $collection->alwaysAvailable) { $locales[] = $collection->mainLocale; } $validLocales = array_unique(array_intersect($locales, $collection->availableLocales)); if (count($validLocales) === 0) { throw new NotFoundException('collection', $collection->id); } $collectionData = [ 'id' => $collection->id, 'status' => $collection->status, 'offset' => $collection->offset, 'limit' => $collection->limit, 'items' => new LazyCollection( function () use ($collection): array { return array_map( function (PersistenceItem $item): Item { return $this->mapItem($item); }, $this->collectionHandler->loadCollectionItems($collection) ); } ), 'query' => function () use ($collection, $locales): ?Query { try { $persistenceQuery = $this->collectionHandler->loadCollectionQuery($collection); } catch (NotFoundException $e) { return null; } return $this->mapQuery($persistenceQuery, $locales, false); }, 'isTranslatable' => $collection->isTranslatable, 'mainLocale' => $collection->mainLocale, 'alwaysAvailable' => $collection->alwaysAvailable, 'availableLocales' => $collection->availableLocales, 'locale' => array_values($validLocales)[0], ]; return Collection::fromArray($collectionData); }
Builds the API collection value from persistence one. If not empty, the first available locale in $locales array will be returned. If the collection is always available and $useMainLocale is set to true, collection in main locale will be returned if none of the locales in $locales array are found. @throws \Netgen\BlockManager\Exception\NotFoundException If the collection does not have any requested translations
public function mapItem(PersistenceItem $item): Item { try { $itemDefinition = $this->itemDefinitionRegistry->getItemDefinition($item->valueType); } catch (ItemDefinitionException $e) { $itemDefinition = new NullItemDefinition($item->valueType); } $itemData = [ 'id' => $item->id, 'status' => $item->status, 'definition' => $itemDefinition, 'collectionId' => $item->collectionId, 'position' => $item->position, 'value' => $item->value, 'configs' => iterator_to_array( $this->configMapper->mapConfig( $item->config, $itemDefinition->getConfigDefinitions() ) ), 'cmsItem' => function () use ($item, $itemDefinition): CmsItemInterface { $valueType = $itemDefinition instanceof NullItemDefinition ? 'null' : $itemDefinition->getValueType(); return $this->cmsItemLoader->load($item->value, $valueType); }, ]; return Item::fromArray($itemData); }
Builds the API item value from persistence one.
public function mapQuery(PersistenceQuery $query, ?array $locales = null, bool $useMainLocale = true): Query { try { $queryType = $this->queryTypeRegistry->getQueryType($query->type); } catch (QueryTypeException $e) { $queryType = new NullQueryType($query->type); } $locales = is_array($locales) && count($locales) > 0 ? $locales : [$query->mainLocale]; if ($useMainLocale && $query->alwaysAvailable) { $locales[] = $query->mainLocale; } $validLocales = array_unique(array_intersect($locales, $query->availableLocales)); if (count($validLocales) === 0) { throw new NotFoundException('query', $query->id); } /** @var string $queryLocale */ $queryLocale = array_values($validLocales)[0]; $untranslatableParams = iterator_to_array( $this->parameterMapper->extractUntranslatableParameters( $queryType, $query->parameters[$query->mainLocale] ) ); $queryData = [ 'id' => $query->id, 'status' => $query->status, 'collectionId' => $query->collectionId, 'queryType' => $queryType, 'isTranslatable' => $query->isTranslatable, 'mainLocale' => $query->mainLocale, 'alwaysAvailable' => $query->alwaysAvailable, 'availableLocales' => $query->availableLocales, 'locale' => $queryLocale, 'parameters' => iterator_to_array( $this->parameterMapper->mapParameters( $queryType, $untranslatableParams + $query->parameters[$queryLocale] ) ), ]; return Query::fromArray($queryData); }
Builds the API query value from persistence one. If not empty, the first available locale in $locales array will be returned. If the query is always available and $useMainLocale is set to true, query in main locale will be returned if none of the locales in $locales array are found. @throws \Netgen\BlockManager\Exception\NotFoundException If the query does not have any requested locales
public function onKernelRequest(GetResponseEvent $event): void { foreach ($this->extensions as $extension) { if (!class_exists($extension) || !is_a($extension, ExtensionInterface::class, true)) { continue; } if ($this->twig->hasExtension($extension)) { continue; } $this->twig->addExtension(new $extension()); } }
Adds the Twig extensions to the environment if they don't already exist.
public function renderItem(array $context, CmsItemInterface $item, string $viewType, array $parameters = [], ?string $viewContext = null): string { try { return $this->renderer->renderValue( $item, $this->getViewContext($context, $viewContext), ['view_type' => $viewType] + $parameters ); } catch (Throwable $t) { $message = sprintf( 'Error rendering an item with value "%s" and value type "%s"', $item->getValue(), $item->getValueType() ); $this->errorHandler->handleError($t, $message); } return ''; }
Renders the provided item.
public function renderValue(array $context, $value, array $parameters = [], ?string $viewContext = null): string { try { return $this->renderer->renderValue( $value, $this->getViewContext($context, $viewContext), $parameters ); } catch (Throwable $t) { $message = sprintf( 'Error rendering a value of type "%s"', is_object($value) ? get_class($value) : gettype($value) ); $this->errorHandler->handleError($t, $message, ['object' => $value]); } return ''; }
Renders the provided value. @param array<string, mixed> $context @param mixed $value @param array<string, mixed> $parameters @param string $viewContext @return string
public function displayZone(Layout $layout, string $zoneIdentifier, string $viewContext, ContextualizedTwigTemplate $twigTemplate): void { $locales = null; $request = $this->requestStack->getCurrentRequest(); if ($request instanceof Request) { $locales = $this->localeProvider->getRequestLocales($request); } $zone = $layout->getZone($zoneIdentifier); $linkedZone = $zone->getLinkedZone(); $blocks = $this->blockService->loadZoneBlocks( $linkedZone instanceof Zone ? $linkedZone : $zone, $locales ); echo $this->renderValue( [], new ZoneReference($layout, $zoneIdentifier), [ 'blocks' => $blocks, 'twig_template' => $twigTemplate, ], $viewContext ); }
Displays the provided zone.
public function renderBlock(array $context, Block $block, array $parameters = [], ?string $viewContext = null): string { try { return $this->renderer->renderValue( $block, $this->getViewContext($context, $viewContext), [ 'twig_template' => $context['twig_template'] ?? null, ] + $parameters ); } catch (Throwable $t) { $message = sprintf('Error rendering a block with ID "%s"', $block->getId()); $this->errorHandler->handleError($t, $message); } return ''; }
Renders the provided block.
public function renderStringTemplate(string $string, array $parameters = []): string { try { $parameters = iterator_to_array($this->getTemplateVariables($parameters)); $environment = new Environment(new ArrayLoader()); $template = $environment->createTemplate($string); return $environment->resolveTemplate($template)->render($parameters); } catch (Throwable $t) { return ''; } }
Renders the provided template, with a reduced set of variables from the provided parameters list. Variables included are only those which can be safely printed.
private function getViewContext(array $context, ?string $viewContext = null): string { return $viewContext ?? $context['view_context'] ?? ViewInterface::CONTEXT_DEFAULT; }
Returns the correct view context based on provided Twig context and view context provided through function call.
private function getTemplateVariables(array $parameters): Generator { foreach ($parameters as $name => $value) { if ($value instanceof ContextualizedTwigTemplate) { yield from $this->getTemplateVariables($value->getContext()); } } foreach ($parameters as $name => $value) { if ($value instanceof Template || $value instanceof TemplateWrapper) { continue; } if (is_scalar($value) || (is_object($value) && method_exists($value, '__toString'))) { yield $name => $value; } } }
Returns all safely printable variables: scalars and objects with __toString method. If the context has an instance of ContextualizedTwigTemplate, its context is also included in the output. Any variables from the main context will override variables from ContextualizedTwigTemplate objects.
public function isContextual(): bool { $collectionQuery = $this->collection->getQuery(); if (!$collectionQuery instanceof Query) { return false; } return $collectionQuery->isContextual(); }
Returns if the result set is dependent on a context, i.e. current request.
public function getLocaleName(string $locale, ?string $displayLocale = null): ?string { return Locales::getName($locale, $displayLocale); }
Returns the locale name in specified locale. If $displayLocale is specified, name translated in that locale will be returned.
public function getLayoutName($layoutId): string { try { $layout = $this->layoutService->loadLayout($layoutId); return $layout->getName(); } catch (Throwable $t) { return ''; } }
Returns the layout name for specified layout ID. @param int|string $layoutId
public function getCountryFlag(string $countryCode): string { try { return FlagGenerator::fromCountryCode($countryCode); } catch (Throwable $t) { return $countryCode; } }
Returns the country flag as an emoji string for provided country code. If the flag cannot be generated, the country code is returned as is. @param string $countryCode
public function validateId($id, ?string $propertyPath = null): void { $this->validate( $id, [ new Constraints\NotBlank(), new Constraints\Type(['type' => 'scalar']), ], $propertyPath ); }
Validates the provided ID to be an integer or string. Use the $propertyPath to change the name of the validated property in the error message. @param int|string $id @param string $propertyPath @throws \Netgen\BlockManager\Exception\Validation\ValidationException If the validation failed
public function validateIdentifier(string $identifier, ?string $propertyPath = null): void { $constraints = [ new Constraints\NotBlank(), new Constraints\Regex( [ 'pattern' => '/^[A-Za-z0-9_]*[A-Za-z][A-Za-z0-9_]*$/', ] ), ]; $this->validate($identifier, $constraints, $propertyPath); }
Validates the provided identifier to be a string. If $isRequired is set to false, null value is also allowed. Use the $propertyPath to change the name of the validated property in the error message. @throws \Netgen\BlockManager\Exception\Validation\ValidationException If the validation failed
public function validatePosition(?int $position, ?string $propertyPath = null, bool $isRequired = false): void { if (!$isRequired && $position === null) { return; } $constraints = [ new Constraints\NotBlank(), new Constraints\GreaterThanOrEqual(0), ]; $this->validate($position, $constraints, $propertyPath); }
Validates the provided position to be an integer greater than or equal to 0. If $isRequired is set to false, null value is also allowed. Use the $propertyPath to change the name of the validated property in the error message. @throws \Netgen\BlockManager\Exception\Validation\ValidationException If the validation failed
public function validateOffsetAndLimit(?int $offset, ?int $limit): void { $this->validate( $offset, [ new Constraints\NotBlank(), ], 'offset' ); if ($limit !== null) { $this->validate( $limit, [ new Constraints\NotBlank(), ], 'limit' ); } }
Validates the provided offset and limit values to be integers. @throws \Netgen\BlockManager\Exception\Validation\ValidationException If the validation failed
public function validateLocale(string $locale, ?string $propertyPath = null): void { $this->validate( $locale, [ new Constraints\NotBlank(), new LocaleConstraint(), ], $propertyPath ); }
Validates the provided locale. @throws \Netgen\BlockManager\Exception\Validation\ValidationException If the validation failed
public function mapBlocks(array $data): array { $blocks = []; foreach ($data as $dataItem) { $blockId = (int) $dataItem['id']; $locale = $dataItem['locale']; if (!isset($blocks[$blockId])) { $blocks[$blockId] = [ 'id' => $blockId, 'layoutId' => (int) $dataItem['layout_id'], 'depth' => (int) $dataItem['depth'], 'path' => $dataItem['path'], 'parentId' => $dataItem['parent_id'] > 0 ? (int) $dataItem['parent_id'] : null, 'placeholder' => $dataItem['placeholder'], 'position' => $dataItem['parent_id'] > 0 ? (int) $dataItem['position'] : null, 'definitionIdentifier' => $dataItem['definition_identifier'], 'viewType' => $dataItem['view_type'], 'itemViewType' => $dataItem['item_view_type'], 'name' => $dataItem['name'], 'isTranslatable' => (bool) $dataItem['translatable'], 'mainLocale' => $dataItem['main_locale'], 'alwaysAvailable' => (bool) $dataItem['always_available'], 'status' => (int) $dataItem['status'], 'config' => $this->buildParameters((string) $dataItem['config']), ]; } $blocks[$blockId]['parameters'][$locale] = $this->buildParameters((string) $dataItem['parameters']); $blocks[$blockId]['availableLocales'][] = $locale; } return array_values( array_map( static function (array $blockData): Block { ksort($blockData['parameters']); sort($blockData['availableLocales']); return Block::fromArray($blockData); }, $blocks ) ); }
Maps data from database to block values. @return \Netgen\BlockManager\Persistence\Values\Block\Block[]
public function mapCollectionReferences(array $data): array { $collectionReferences = []; foreach ($data as $dataItem) { $collectionReferences[] = CollectionReference::fromArray( [ 'blockId' => (int) $dataItem['block_id'], 'blockStatus' => (int) $dataItem['block_status'], 'collectionId' => (int) $dataItem['collection_id'], 'collectionStatus' => (int) $dataItem['collection_status'], 'identifier' => $dataItem['identifier'], ] ); } return $collectionReferences; }
Maps data from database to collection reference values. @return \Netgen\BlockManager\Persistence\Values\Block\CollectionReference[]
public function getAutoIncrementValue(string $table, string $column = 'id') { $databaseServer = $this->connection->getDatabasePlatform()->getName(); if (isset($this->databaseSpecificHelpers[$databaseServer])) { return $this->databaseSpecificHelpers[$databaseServer] ->getAutoIncrementValue($table, $column); } return 'null'; }
Returns the auto increment value. Returns the value used for autoincrement tables. Usually this will just be null. In case for sequence based RDBMS, this method can return a proper value for the given column. @return mixed
public function lastInsertId(string $table, string $column = 'id') { $databaseServer = $this->connection->getDatabasePlatform()->getName(); if (isset($this->databaseSpecificHelpers[$databaseServer])) { return $this->databaseSpecificHelpers[$databaseServer] ->lastInsertId($table, $column); } return $this->connection->lastInsertId($table); }
Returns the last inserted ID. @return mixed
private function getRulePriority(RuleCreateStruct $ruleCreateStruct): int { if (is_int($ruleCreateStruct->priority)) { return $ruleCreateStruct->priority; } $lowestRulePriority = $this->queryHandler->getLowestRulePriority(); if ($lowestRulePriority !== null) { return $lowestRulePriority - 10; } return 0; }
Returns the rule priority when creating a new rule. If priority is specified in the struct, it is used automatically. Otherwise, the returned priority is the lowest available priority subtracted by 10 (to allow inserting rules in between). If no rules exist, priority is 0.
public function buildQueryType( string $type, QueryTypeHandlerInterface $handler, array $config ): QueryTypeInterface { $parameterBuilder = $this->parameterBuilderFactory->createParameterBuilder(); $handler->buildParameters($parameterBuilder); $parameterDefinitions = $parameterBuilder->buildParameterDefinitions(); return QueryType::fromArray( [ 'type' => $type, 'isEnabled' => $config['enabled'], 'name' => $config['name'] ?? '', 'handler' => $handler, 'parameterDefinitions' => $parameterDefinitions, ] ); }
Builds the query type.
private function getViewProvider($value): ViewProviderInterface { foreach ($this->viewProviders as $viewProvider) { if ($viewProvider->supports($value)) { return $viewProvider; } } throw ViewProviderException::noViewProvider(get_class($value)); }
Returns the view provider that supports the given value. @param mixed $value @return \Netgen\BlockManager\View\Provider\ViewProviderInterface
public function renderBlock(string $blockName): string { if (!$this->template->hasBlock($blockName, $this->context, $this->blocks)) { return ''; } $level = ob_get_level(); ob_start(); try { $this->template->displayBlock($blockName, $this->context, $this->blocks); } catch (Throwable $t) { while (ob_get_level() > $level) { ob_end_clean(); } throw $t; } return (string) ob_get_clean(); }
Renders the provided block. If block does not exist, an empty string will be returned. @throws \Throwable
public function getSource($name): string { return $this->innerLoader->getSourceContext($this->getRealName($name))->getCode(); }
@deprecated Used for compatibility with Twig 1.x @param mixed $name @return string
private function getRealName(string $name): string { if (mb_strpos($name, '@ngbm/') !== 0) { return $name; } if (!isset($this->templateMap[$name])) { $this->templateMap[$name] = str_replace( '@ngbm/', '@ngbm_' . $this->configuration->getParameter('design') . '/', $name ); } return $this->templateMap[$name]; }
Returns the name of the template converted from the virtual Twig namespace ("@ngbm") to the real currently defined design name.
private function getThemeDirs(ContainerBuilder $container, array $themeList): array { $paths = array_map( static function (array $bundleMetadata): string { return $bundleMetadata['path'] . '/Resources/views/ngbm/themes'; }, // Reversing the list of bundles so bundles added at end have higher priority // when searching for a template array_reverse($container->getParameter('kernel.bundles_metadata')) ); $paths = array_values(array_filter($paths, 'is_dir')); if ($container->hasParameter('twig.default_path')) { $defaultTwigDir = $container->getParameterBag()->resolveValue($container->getParameter('twig.default_path')) . '/ngbm/themes'; if (is_dir($defaultTwigDir)) { array_unshift($paths, $defaultTwigDir); } } $appDir = $this->getAppDir($container) . '/Resources/views/ngbm/themes'; if (is_dir($appDir)) { array_unshift($paths, $appDir); } $themeDirs = []; foreach ($paths as $path) { foreach ($themeList as $themeName) { $themeDirs[$themeName][] = $path . '/' . $themeName; } } return $themeDirs; }
Returns an array with all found paths for provided theme list.
private function getAppDir(ContainerBuilder $container): string { if ($container->hasParameter('kernel.project_dir')) { return (string) $container->getParameter('kernel.project_dir') . '/' . (string) $container->getParameter('kernel.name'); } return (string) $container->getParameter('kernel.root_dir'); }
Returns the current app dir, abstracting Symfony 3.3+, where kernel.project_dir is available, and Symfony 2.8 support, where only kernel.root_dir exists.
private function buildVersionedValues(iterable $values, int $version): Generator { foreach ($values as $key => $value) { yield $key => new VersionedValue($value, $version); } }
Builds the list of VersionedValue objects for provided list of values.
public function setConfigStruct(string $configKey, ConfigStruct $configStruct): void { $this->configStructs[$configKey] = $configStruct; }
Sets the config struct to this struct.
public function getConfigStruct(string $configKey): ConfigStruct { if (!$this->hasConfigStruct($configKey)) { throw ConfigException::noConfigStruct($configKey); } return $this->configStructs[$configKey]; }
Gets the config struct with provided config key. @throws \Netgen\BlockManager\Exception\API\ConfigException If config struct does not exist
private function isCollectionDynamic(Collection $collection): bool { try { $this->loadCollectionQuery($collection); } catch (NotFoundException $e) { return false; } return true; }
Returns if the provided collection is a dynamic collection (i.e. if it has a query).
private function createItemPosition(Collection $collection, ?int $newPosition): int { if (!$this->isCollectionDynamic($collection)) { return $this->positionHelper->createPosition( $this->getPositionHelperItemConditions( $collection->id, $collection->status ), $newPosition ); } if ($newPosition === null) { throw new BadStateException('collection', 'When adding items to dynamic collections, position is mandatory.'); } return $this->incrementItemPositions($collection, $newPosition); }
Creates space for a new manual item by shifting positions of other items below the new position. In case of a manual collection, the case is simple, all items below the position are incremented. In case of a dynamic collection, the items below are incremented, but only up until the first break in positions.
private function moveItemToPosition(Collection $collection, Item $item, int $newPosition): int { if (!$this->isCollectionDynamic($collection)) { return $this->positionHelper->moveToPosition( $this->getPositionHelperItemConditions( $collection->id, $collection->status ), $item->position, $newPosition ); } return $this->incrementItemPositions($collection, $newPosition, $item->position); }
Moves the item to provided position. In case of a manual collection, the case is simple, only positions between the old and new position are ever updated. In case of a dynamic collection, the items below the new position are incremented, but only up until the first break in positions. The positions are never decremented.
private function incrementItemPositions(Collection $collection, int $startPosition, ?int $maxPosition = null): int { $items = $this->loadCollectionItems($collection); $endPosition = $startPosition - 1; foreach ($items as $item) { if ($item->position < $startPosition) { // Skip all items located before the start position, // we don't need to touch those. continue; } if ($item->position - $endPosition > 1 || $item->position === $maxPosition) { // Once we reach a break in positions, or if we we've come to the maximum // allowed position, we simply stop. break; } $endPosition = $item->position; } if ($endPosition < $startPosition) { return $startPosition; } return $this->positionHelper->createPosition( $this->getPositionHelperItemConditions( $collection->id, $collection->status ), $startPosition, $endPosition, true ); }
Creates space for a new manual item by shifting positions of other items below the new position, but only up until the first break in positions, or up to $maxPosition if provided.
private function importData(string $data): int { $errorCount = 0; foreach ($this->importer->importData($data) as $index => $result) { if ($result instanceof SuccessResult) { $this->io->note( sprintf( 'Imported %1$s #%2$d into %1$s ID %3$d', $result->getEntityType(), $index + 1, $result->getEntityId() ) ); continue; } if ($result instanceof ErrorResult) { $this->io->error(sprintf('Could not import %s #%d', $result->getEntityType(), $index + 1)); $this->io->section('Error stack:'); $this->renderThrowableStack($result->getError()); $this->io->newLine(); ++$errorCount; continue; } } return $errorCount; }
Import new entities from the given data and returns the error count.
private function renderThrowableStack(Throwable $throwable, int $number = 0): void { $this->io->writeln(sprintf(' #%d:', $number)); $throwableClass = get_class($throwable); $this->io->writeln(sprintf(' - <comment>exception:</comment> %s', $throwableClass)); $this->io->writeln(sprintf(' - <comment>file:</comment> <info>%s</info>', $throwable->getFile())); $this->io->writeln(sprintf(' - <comment>line:</comment> %d', $throwable->getLine())); $this->io->writeln(sprintf(' - <comment>message:</comment> %s', $throwable->getMessage())); $previous = $throwable->getPrevious(); if ($previous !== null) { $this->renderThrowableStack($previous, $number + 1); } }
Renders all stacked exception messages for the given $throwable.
public function hasItem(int $position): bool { return $this->items->exists( static function ($key, APIItem $item) use ($position): bool { return $item->getPosition() === $position; } ); }
Returns if the item exists at specified position.
public function getItem(int $position): ?APIItem { foreach ($this->items as $item) { if ($item->getPosition() === $position) { return $item; } } return null; }
Returns the item at specified position.
public function onRenderView(CollectViewParametersEvent $event): void { $currentRequest = $this->requestStack->getCurrentRequest(); if (!$currentRequest instanceof Request) { return; } $view = $event->getView(); if (!$view instanceof BlockViewInterface || !$view->hasParameter('collection_identifier')) { return; } if (!in_array($view->getContext(), $this->enabledContexts, true)) { return; } $block = $view->getBlock(); $collectionIdentifier = $view->getParameter('collection_identifier'); $resultPager = $this->pagerFactory->getPager( $block->getCollection($collectionIdentifier), $currentRequest->query->getInt('page', 1), $this->getMaxPages($block) ); $event->addParameter('collection', $resultPager->getCurrentPageResults()); $event->addParameter('pager', $resultPager); }
Adds a parameter to the view with results built from all block collections.
private function getMaxPages(Block $block): ?int { if (!$block->getDefinition()->hasPlugin(PagedCollectionsPlugin::class)) { return null; } if ($block->getParameter('paged_collections:enabled')->getValue() !== true) { return null; } return $block->getParameter('paged_collections:max_pages')->getValue(); }
Returns the maximum number of the pages for the provided block, if paging is enabled and maximum number of pages is set for a block.
public function buildItemDefinition(string $valueType, array $configDefinitionHandlers): ItemDefinitionInterface { $configDefinitions = []; foreach ($configDefinitionHandlers as $configKey => $configDefinitionHandler) { $configDefinitions[$configKey] = $this->configDefinitionFactory->buildConfigDefinition( $configKey, $configDefinitionHandler ); } return ItemDefinition::fromArray( [ 'valueType' => $valueType, 'configDefinitions' => $configDefinitions, ] ); }
Builds the item definition. @param string $valueType @param \Netgen\BlockManager\Config\ConfigDefinitionHandlerInterface[] $configDefinitionHandlers @return \Netgen\BlockManager\Collection\Item\ItemDefinitionInterface
public function onBuildView(CollectViewParametersEvent $event): void { $view = $event->getView(); if (!$view instanceof RuleViewInterface) { return; } $layout = $layout = $view->getRule()->getLayout(); $ruleCount = 0; if ($layout instanceof Layout && $layout->isPublished()) { $ruleCount = $this->layoutResolverService->getRuleCount($layout); } $event->addParameter('rule_count', $ruleCount); }
Injects the number of rules mapped to the layout in the rule provided by the event.
public function newBlockCreateStruct(BlockDefinitionInterface $blockDefinition): BlockCreateStruct { $viewTypeIdentifier = $blockDefinition->getViewTypeIdentifiers()[0]; $viewType = $blockDefinition->getViewType($viewTypeIdentifier); $itemViewTypeIdentifier = $viewType->getItemViewTypeIdentifiers()[0]; $blockCreateStruct = new BlockCreateStruct($blockDefinition); $blockCreateStruct->viewType = $viewTypeIdentifier; $blockCreateStruct->itemViewType = $itemViewTypeIdentifier; $blockCreateStruct->isTranslatable = $blockDefinition->isTranslatable(); $blockCreateStruct->alwaysAvailable = true; return $blockCreateStruct; }
Creates a new block create struct from data found in provided block definition.
public function newBlockUpdateStruct(string $locale, ?Block $block = null): BlockUpdateStruct { $blockUpdateStruct = new BlockUpdateStruct(); $blockUpdateStruct->locale = $locale; if (!$block instanceof Block) { return $blockUpdateStruct; } $blockUpdateStruct->viewType = $block->getViewType(); $blockUpdateStruct->itemViewType = $block->getItemViewType(); $blockUpdateStruct->name = $block->getName(); $blockUpdateStruct->alwaysAvailable = $block->isAlwaysAvailable(); $blockUpdateStruct->fillParametersFromBlock($block); $this->configStructBuilder->buildConfigUpdateStructs($block, $blockUpdateStruct); return $blockUpdateStruct; }
Creates a new block update struct in specified locale. If block is provided, initial data is copied from the block.
private function getNodes(): array { return [ new ConfigurationNode\ViewNode(), new ConfigurationNode\DesignNode(), new ConfigurationNode\DesignListNode(), new ConfigurationNode\DefaultViewTemplatesNode(), new ConfigurationNode\HttpCacheNode(), new ConfigurationNode\BlockDefinitionNode(), new ConfigurationNode\BlockTypeNode(), new ConfigurationNode\BlockTypeGroupNode(), new ConfigurationNode\LayoutTypeNode(), new ConfigurationNode\QueryTypeNode(), new ConfigurationNode\PageLayoutNode(), new ConfigurationNode\ApiKeysNode(), new ConfigurationNode\ValueTypeNode(), new ConfigurationNode\DebugNode(), ]; }
Returns available configuration nodes for the bundle. @return \Netgen\Bundle\BlockManagerBundle\DependencyInjection\ConfigurationNodeInterface[]
public function onException(GetResponseForExceptionEvent $event): void { if (!$event->isMasterRequest()) { return; } $attributes = $event->getRequest()->attributes; if ($attributes->get(SetIsApiRequestListener::API_FLAG_NAME) !== true) { return; } $exception = $event->getException(); if (!$exception instanceof HttpExceptionInterface || $exception->getStatusCode() >= 500) { $this->logger->critical( sprintf( 'Uncaught PHP Exception %s: "%s" at %s line %s', get_class($exception), $exception->getMessage(), $exception->getFile(), $exception->getLine() ), ['exception' => $exception] ); } $response = new JsonResponse(); $response->setContent($this->serializer->serialize($exception, 'json')); $event->setResponse($response); }
Serializes the exception if SetIsApiRequestListener::API_FLAG_NAME is set to true.
private function updateLayoutModifiedDate(Layout $layout): void { $updatedLayout = clone $layout; $updatedLayout->modified = time(); $this->queryHandler->updateLayout($updatedLayout); }
Updates the layout modified date to the current timestamp.
private function setTotalCount(ResultSet $result): void { $this->totalCount = $result->getTotalCount() - $this->startingOffset; $this->totalCount = $this->totalCount > 0 ? $this->totalCount : 0; if ($this->maxTotalCount !== null && $this->totalCount >= $this->maxTotalCount) { $this->totalCount = $this->maxTotalCount; } }
Sets the total count of the results to the adapter, while taking into account the injected maximum number of pages to use.
public function onView(GetResponseForControllerResultEvent $event): void { if (!$event->isMasterRequest()) { return; } $controllerResult = $event->getControllerResult(); if (!$controllerResult instanceof ViewInterface) { return; } $event->getRequest()->attributes->set('ngbmView', $controllerResult); }
Sets the Netgen Layouts view provided by the controller to the request.
public function convertToRemoteId(string $link): string { $link = parse_url($link); if (!is_array($link) || !isset($link['host'], $link['scheme'])) { return self::NULL_LINK; } $item = $this->cmsItemLoader->load($link['host'], str_replace('-', '_', $link['scheme'])); if ($item instanceof NullCmsItem) { return self::NULL_LINK; } return $link['scheme'] . '://' . $item->getRemoteId(); }
Converts the value_type://value format of the item reference to value_type://remote_id. This is useful for various export/import operations between different systems. If the conversion cannot be done, (for example, because item does not exist), a reference to the so called null item will be returned.
public function convertFromRemoteId(string $link): string { $link = parse_url($link); if (!is_array($link) || !isset($link['host'], $link['scheme'])) { return self::NULL_LINK; } $item = $this->cmsItemLoader->loadByRemoteId($link['host'], str_replace('-', '_', $link['scheme'])); if ($item instanceof NullCmsItem) { return self::NULL_LINK; } return $link['scheme'] . '://' . $item->getValue(); }
Converts the value_type://remote_id format of the item reference to value_type://value. This is useful for various export/import operations between different systems. If the conversion cannot be done, (for example, because item does not exist), a reference to the so called null item will be returned.
private function parseJson(string $data): stdClass { $data = json_decode($data); if ($data instanceof stdClass) { return $data; } $errorCode = json_last_error(); if ($errorCode !== JSON_ERROR_NONE) { throw JsonValidationException::parseError(json_last_error_msg(), $errorCode); } throw JsonValidationException::notAcceptable( sprintf('Expected a JSON object, got %s', gettype($data)) ); }
Parses JSON data. @throws \Netgen\BlockManager\Exception\Transfer\JsonValidationException
public function getAutoIncrementValue(string $table, string $column = 'id') { return "nextval('" . $this->connection->getDatabasePlatform()->getIdentitySequenceName($table, $column) . "')"; }
Returns the auto increment value. Returns the value used for autoincrement tables. Usually this will just be null. In case for sequence based RDBMS, this method can return a proper value for the given column. @return mixed
public function lastInsertId(string $table, string $column = 'id') { return $this->connection->lastInsertId( $this->connection->getDatabasePlatform()->getIdentitySequenceName($table, $column) ); }
Returns the last inserted ID. @return mixed
public function visit($value, ?VisitorInterface $subVisitor = null) { if ($subVisitor === null) { throw new RuntimeException('Implementation requires sub-visitor'); } return [ 'id' => $value->getId(), 'is_translatable' => $value->isTranslatable(), 'is_always_available' => $value->isAlwaysAvailable(), 'main_locale' => $value->getMainLocale(), 'available_locales' => $value->getAvailableLocales(), 'parameters' => $this->visitParameters($value, $subVisitor), 'query_type' => $value->getQueryType()->getType(), ]; }
@param \Netgen\BlockManager\API\Values\Collection\Query $value @param \Netgen\BlockManager\Transfer\Output\VisitorInterface|null $subVisitor @return mixed
private function visitParameters(Query $query, VisitorInterface $subVisitor): array { $parametersByLanguage = [ $query->getLocale() => iterator_to_array( $this->visitTranslationParameters($query, $subVisitor) ), ]; foreach ($query->getAvailableLocales() as $availableLocale) { if ($availableLocale === $query->getLocale()) { continue; } $translatedQuery = $this->collectionService->loadQuery( $query->getId(), [$availableLocale], false ); $parametersByLanguage[$availableLocale] = iterator_to_array( $this->visitTranslationParameters( $translatedQuery, $subVisitor ) ); } ksort($parametersByLanguage); return $parametersByLanguage; }
Visit the given $query parameters into hash representation.
private function visitTranslationParameters(Query $query, VisitorInterface $subVisitor): Generator { foreach ($query->getParameters() as $parameter) { yield $parameter->getName() => $subVisitor->visit($parameter); } }
Return parameters for the given $query.
public function buildConfigUpdateStructs(ConfigAwareValue $configAwareValue, ConfigAwareStruct $configAwareStruct): void { foreach ($configAwareValue->getConfigs() as $configKey => $config) { $configStruct = new ConfigStruct(); $configStruct->fillParametersFromConfig($config); $configAwareStruct->setConfigStruct($configKey, $configStruct); } }
Fills the provided config aware struct with config structs, according to the provided value.
public static function buildValueType(string $identifier, array $config): ValueType { return ValueType::fromArray( [ 'identifier' => $identifier, 'isEnabled' => $config['enabled'], 'name' => $config['name'], ] ); }
Builds the value type.
public function setVoters(array $voters): void { $this->voters = array_filter( $voters, static function (VisibilityVoterInterface $voter): bool { return true; } ); }
Sets the available voters. @param \Netgen\BlockManager\Collection\Item\VisibilityVoterInterface[] $voters
public function onRenderView(CollectViewParametersEvent $event): void { $view = $event->getView(); if (!$view instanceof BlockViewInterface) { return; } if (!in_array($view->getContext(), $this->enabledContexts, true)) { return; } $flags = 0; if ($view->getContext() === ViewInterface::CONTEXT_API) { $flags = ResultSet::INCLUDE_UNKNOWN_ITEMS; } $block = $view->getBlock(); $collections = []; $pagers = []; foreach ($block->getCollections() as $identifier => $collection) { // In non AJAX scenarios, we're always rendering the first page of the collection // as specified by offset and limit in the collection itself $pager = $this->pagerFactory->getPager( $collection, 1, $this->getMaxPages($block), $flags ); $collections[$identifier] = $pager->getCurrentPageResults(); $pagers[$identifier] = $pager; } $event->addParameter('collections', $collections); $event->addParameter('pagers', $pagers); }
Adds a parameter to the view with results built from all block collections.
public function loadLayoutData($layoutId, int $status): array { $query = $this->getLayoutSelectQuery(); $query->where( $query->expr()->eq('l.id', ':id') ) ->setParameter('id', $layoutId, Type::INTEGER); $this->applyStatusCondition($query, $status, 'l.status'); return $query->execute()->fetchAll(PDO::FETCH_ASSOC); }
Loads all data for layout with specified ID. @param int|string $layoutId @param int $status @return array
public function loadLayoutIds(bool $includeDrafts, ?bool $shared = null, int $offset = 0, ?int $limit = null): array { $query = $this->connection->createQueryBuilder(); $query->select('DISTINCT l.id, l.name') ->from('ngbm_layout', 'l'); if ($includeDrafts) { $query->leftJoin( 'l', 'ngbm_layout', 'l2', $query->expr()->andX( $query->expr()->eq('l.id', 'l2.id'), $query->expr()->eq('l2.status', ':status') ) ); } if ($shared !== null) { $query->where( $query->expr()->eq('l.shared', ':shared') ); } $statusExpr = $query->expr()->eq('l.status', ':status'); if ($includeDrafts) { $statusExpr = $query->expr()->orX( $statusExpr, $query->expr()->isNull('l2.id') ); } $query->andWhere($statusExpr); if ($shared !== null) { $query->setParameter('shared', $shared, Type::BOOLEAN); } $query->setParameter('status', Value::STATUS_PUBLISHED, Type::INTEGER); $this->applyOffsetAndLimit($query, $offset, $limit); $query->orderBy('l.name', 'ASC'); $result = $query->execute()->fetchAll(PDO::FETCH_ASSOC); return array_column($result, 'id'); }
Loads all layout IDs for provided parameters. If $includeDrafts is set to true, drafts which have no published status will also be included.
public function getLayoutsCount(bool $includeDrafts, ?bool $shared = null): int { $query = $this->connection->createQueryBuilder(); $query->select('count(DISTINCT l.id) AS count') ->from('ngbm_layout', 'l'); if ($includeDrafts) { $query->leftJoin( 'l', 'ngbm_layout', 'l2', $query->expr()->andX( $query->expr()->eq('l.id', 'l2.id'), $query->expr()->eq('l2.status', ':status') ) ); } if ($shared !== null) { $query->where( $query->expr()->eq('l.shared', ':shared') ); } $statusExpr = $query->expr()->eq('l.status', ':status'); if ($includeDrafts) { $statusExpr = $query->expr()->orX( $statusExpr, $query->expr()->isNull('l2.id') ); } $query->andWhere($statusExpr); if ($shared !== null) { $query->setParameter('shared', $shared, Type::BOOLEAN); } $query->setParameter('status', Value::STATUS_PUBLISHED, Type::INTEGER); $data = $query->execute()->fetchAll(PDO::FETCH_ASSOC); return (int) ($data[0]['count'] ?? 0); }
Loads all layout IDs for provided parameters. If $includeDrafts is set to true, drafts which have no published status will also be included.
public function loadLayoutsData(array $layoutIds, bool $includeDrafts): array { $query = $this->getLayoutSelectQuery(); if ($includeDrafts) { $query->leftJoin( 'l', 'ngbm_layout', 'l2', $query->expr()->andX( $query->expr()->eq('l.id', 'l2.id'), $query->expr()->eq('l2.status', ':status') ) ); } $query->where( $query->expr()->in('l.id', [':layout_ids']) ); $statusExpr = $query->expr()->eq('l.status', ':status'); if ($includeDrafts) { $statusExpr = $query->expr()->orX( $statusExpr, $query->expr()->isNull('l2.id') ); } $query->andWhere($statusExpr); $query->setParameter('layout_ids', $layoutIds, Connection::PARAM_INT_ARRAY); $query->setParameter('status', Value::STATUS_PUBLISHED, Type::INTEGER); $query->orderBy('l.name', 'ASC'); return $query->execute()->fetchAll(PDO::FETCH_ASSOC); }
Loads all data for layouts with provided IDs. If $includeDrafts is set to true, drafts which have no published status will also be included. @param array<int|string> $layoutIds @param bool $includeDrafts @return array
public function loadRelatedLayoutsData(Layout $sharedLayout): array { $query = $this->getLayoutSelectQuery(); $query->innerJoin( 'l', 'ngbm_zone', 'z', $query->expr()->andX( $query->expr()->eq('z.layout_id', 'l.id'), $query->expr()->eq('z.status', 'l.status'), $query->expr()->eq('z.linked_layout_id', ':linked_layout_id') ) ) ->where( $query->expr()->andX( $query->expr()->eq('l.shared', ':shared'), $query->expr()->eq('l.status', ':status') ) ) ->setParameter('shared', false, Type::BOOLEAN) ->setParameter('status', Value::STATUS_PUBLISHED, Type::INTEGER) ->setParameter('linked_layout_id', $sharedLayout->id, Type::INTEGER); $query->orderBy('l.name', 'ASC'); return $query->execute()->fetchAll(PDO::FETCH_ASSOC); }
Loads all data for layouts related to provided shared layout.
public function getRelatedLayoutsCount(Layout $sharedLayout): int { $query = $this->connection->createQueryBuilder(); $query->select('count(DISTINCT ngbm_layout.id) AS count') ->from('ngbm_layout') ->innerJoin( 'ngbm_layout', 'ngbm_zone', 'z', $query->expr()->andX( $query->expr()->eq('z.layout_id', 'ngbm_layout.id'), $query->expr()->eq('z.status', 'ngbm_layout.status'), $query->expr()->eq('z.linked_layout_id', ':linked_layout_id') ) ) ->where( $query->expr()->andX( $query->expr()->eq('ngbm_layout.shared', ':shared'), $query->expr()->eq('ngbm_layout.status', ':status') ) ) ->setParameter('shared', false, Type::BOOLEAN) ->setParameter('status', Value::STATUS_PUBLISHED, Type::INTEGER) ->setParameter('linked_layout_id', $sharedLayout->id, Type::INTEGER); $data = $query->execute()->fetchAll(PDO::FETCH_ASSOC); return (int) ($data[0]['count'] ?? 0); }
Loads the count of layouts related to provided shared layout.
public function loadZoneData($layoutId, int $status, string $identifier): array { $query = $this->getZoneSelectQuery(); $query->where( $query->expr()->andX( $query->expr()->eq('layout_id', ':layout_id'), $query->expr()->eq('identifier', ':identifier') ) ) ->setParameter('layout_id', $layoutId, Type::INTEGER) ->setParameter('identifier', $identifier, Type::STRING); $this->applyStatusCondition($query, $status); return $query->execute()->fetchAll(PDO::FETCH_ASSOC); }
Loads all zone data with provided identifier. @param int|string $layoutId @param int $status @param string $identifier @return array
public function loadLayoutZonesData(Layout $layout): array { $query = $this->getZoneSelectQuery(); $query->where( $query->expr()->eq('layout_id', ':layout_id') ) ->setParameter('layout_id', $layout->id, Type::INTEGER) ->orderBy('identifier', 'ASC'); $this->applyStatusCondition($query, $layout->status); return $query->execute()->fetchAll(PDO::FETCH_ASSOC); }
Loads all data for zones that belong to provided layout.
public function zoneExists($layoutId, int $status, string $identifier): bool { $query = $this->connection->createQueryBuilder(); $query->select('count(*) AS count') ->from('ngbm_zone') ->where( $query->expr()->andX( $query->expr()->eq('identifier', ':identifier'), $query->expr()->eq('layout_id', ':layout_id') ) ) ->setParameter('identifier', $identifier, Type::STRING) ->setParameter('layout_id', $layoutId, Type::INTEGER); $this->applyStatusCondition($query, $status); $data = $query->execute()->fetchAll(PDO::FETCH_ASSOC); return (int) ($data[0]['count'] ?? 0) > 0; }
Returns if the zone exists. @param int|string $layoutId @param int $status @param string $identifier @return bool
public function layoutNameExists(string $name, $excludedLayoutId = null): bool { $query = $this->connection->createQueryBuilder(); $query->select('count(*) AS count') ->from('ngbm_layout') ->where( $query->expr()->andX( $query->expr()->eq('name', ':name') ) ) ->setParameter('name', trim($name), Type::STRING); if ($excludedLayoutId !== null) { $query->andWhere($query->expr()->neq('id', ':layout_id')) ->setParameter('layout_id', $excludedLayoutId, Type::INTEGER); } $data = $query->execute()->fetchAll(PDO::FETCH_ASSOC); return (int) ($data[0]['count'] ?? 0) > 0; }
Returns if the layout with provided name exists. @param string $name @param int|string $excludedLayoutId @return bool
public function createLayout(Layout $layout): Layout { $query = $this->connection->createQueryBuilder() ->insert('ngbm_layout') ->values( [ 'id' => ':id', 'status' => ':status', 'type' => ':type', 'name' => ':name', 'description' => ':description', 'created' => ':created', 'modified' => ':modified', 'shared' => ':shared', 'main_locale' => ':main_locale', ] ) ->setValue( 'id', $layout->id !== null ? (int) $layout->id : $this->connectionHelper->getAutoIncrementValue('ngbm_layout') ) ->setParameter('status', $layout->status, Type::INTEGER) ->setParameter('type', $layout->type, Type::STRING) ->setParameter('name', $layout->name, Type::STRING) ->setParameter('description', $layout->description, Type::STRING) ->setParameter('created', $layout->created, Type::INTEGER) ->setParameter('modified', $layout->modified, Type::INTEGER) ->setParameter('shared', $layout->shared, Type::BOOLEAN) ->setParameter('main_locale', $layout->mainLocale, Type::STRING); $query->execute(); $layout->id = $layout->id ?? (int) $this->connectionHelper->lastInsertId('ngbm_layout'); return $layout; }
Creates a layout.
public function createLayoutTranslation(Layout $layout, string $locale): void { $query = $this->connection->createQueryBuilder() ->insert('ngbm_layout_translation') ->values( [ 'layout_id' => ':layout_id', 'status' => ':status', 'locale' => ':locale', ] ) ->setParameter('layout_id', $layout->id, Type::INTEGER) ->setParameter('status', $layout->status, Type::INTEGER) ->setParameter('locale', $locale, Type::STRING); $query->execute(); }
Creates a layout translation.
public function createZone(Zone $zone): void { $query = $this->connection->createQueryBuilder() ->insert('ngbm_zone') ->values( [ 'identifier' => ':identifier', 'layout_id' => ':layout_id', 'status' => ':status', 'root_block_id' => ':root_block_id', 'linked_layout_id' => ':linked_layout_id', 'linked_zone_identifier' => ':linked_zone_identifier', ] ) ->setParameter('identifier', $zone->identifier, Type::STRING) ->setParameter('layout_id', $zone->layoutId, Type::INTEGER) ->setParameter('status', $zone->status, Type::INTEGER) ->setParameter('root_block_id', $zone->rootBlockId, Type::INTEGER) ->setParameter('linked_layout_id', $zone->linkedLayoutId, Type::INTEGER) ->setParameter('linked_zone_identifier', $zone->linkedZoneIdentifier, Type::STRING); $query->execute(); }
Creates a zone.
public function updateLayout(Layout $layout): void { $query = $this->connection->createQueryBuilder(); $query ->update('ngbm_layout') ->set('type', ':type') ->set('name', ':name') ->set('description', ':description') ->set('created', ':created') ->set('modified', ':modified') ->set('shared', ':shared') ->set('main_locale', ':main_locale') ->where( $query->expr()->eq('id', ':id') ) ->setParameter('id', $layout->id, Type::INTEGER) ->setParameter('type', $layout->type, Type::STRING) ->setParameter('name', $layout->name, Type::STRING) ->setParameter('description', $layout->description, Type::STRING) ->setParameter('created', $layout->created, Type::INTEGER) ->setParameter('modified', $layout->modified, Type::INTEGER) ->setParameter('shared', $layout->shared, Type::BOOLEAN) ->setParameter('main_locale', $layout->mainLocale, Type::STRING); $this->applyStatusCondition($query, $layout->status); $query->execute(); }
Updates a layout.
public function updateZone(Zone $zone): void { $query = $this->connection->createQueryBuilder(); $query ->update('ngbm_zone') ->set('root_block_id', ':root_block_id') ->set('linked_layout_id', ':linked_layout_id') ->set('linked_zone_identifier', ':linked_zone_identifier') ->where( $query->expr()->andX( $query->expr()->eq('layout_id', ':layout_id'), $query->expr()->eq('identifier', ':identifier') ) ) ->setParameter('layout_id', $zone->layoutId, Type::INTEGER) ->setParameter('identifier', $zone->identifier, Type::STRING) ->setParameter('root_block_id', $zone->rootBlockId, Type::INTEGER) ->setParameter('linked_layout_id', $zone->linkedLayoutId, Type::INTEGER) ->setParameter('linked_zone_identifier', $zone->linkedZoneIdentifier, Type::STRING); $this->applyStatusCondition($query, $zone->status); $query->execute(); }
Updates a zone.
public function deleteLayoutZones($layoutId, ?int $status = null): void { $query = $this->connection->createQueryBuilder(); $query->delete('ngbm_zone') ->where( $query->expr()->eq('layout_id', ':layout_id') ) ->setParameter('layout_id', $layoutId, Type::INTEGER); if ($status !== null) { $this->applyStatusCondition($query, $status); } $query->execute(); }
Deletes all layout zones. @param int|string $layoutId @param int $status
public function deleteZone($layoutId, string $zoneIdentifier, ?int $status = null): void { $query = $this->connection->createQueryBuilder(); $query->delete('ngbm_zone') ->where( $query->expr()->andX( $query->expr()->eq('layout_id', ':layout_id'), $query->expr()->eq('identifier', ':identifier') ) ) ->setParameter('layout_id', $layoutId, Type::INTEGER) ->setParameter('identifier', $zoneIdentifier, Type::STRING); if ($status !== null) { $this->applyStatusCondition($query, $status); } $query->execute(); }
Deletes the zone. @param int|string $layoutId @param string $zoneIdentifier @param int $status
private function getZoneSelectQuery(): QueryBuilder { $query = $this->connection->createQueryBuilder(); $query->select('DISTINCT ngbm_zone.*') ->from('ngbm_zone'); return $query; }
Builds and returns a zone database SELECT query.
private function validateAddItems(Block $block, string $collectionIdentifier, $items): void { $this->validate( $items, [ new Constraints\Type(['type' => 'array']), new Constraints\NotBlank(), new Constraints\All( [ 'constraints' => new Constraints\Collection( [ 'fields' => [ 'value' => [ new Constraints\NotNull(), new Constraints\Type(['type' => 'scalar']), ], 'value_type' => [ new Constraints\NotBlank(), new Constraints\Type(['type' => 'string']), ], 'position' => new Constraints\Optional( [ new Constraints\NotNull(), new Constraints\Type(['type' => 'int']), ] ), ], ] ), ] ), ], 'items' ); $blockDefinition = $block->getDefinition(); if (!$blockDefinition->hasCollection($collectionIdentifier)) { return; } $collectionConfig = $blockDefinition->getCollection($collectionIdentifier); foreach ($items as $item) { if (!$collectionConfig->isValidItemType($item['value_type'])) { throw ValidationException::validationFailed( 'value_type', sprintf( 'Value type "%s" is not allowed in selected block.', $item['value_type'] ) ); } } }
Validates item creation parameters from the request. @param \Netgen\BlockManager\API\Values\Block\Block $block @param string $collectionIdentifier @param mixed $items
private function validateCreateLayout(ParameterBag $data): void { $this->validate( $data->get('layout_type'), [ new Constraints\NotBlank(), new Constraints\Type(['type' => 'string']), ], 'layout_type' ); $this->validate( $data->get('locale'), [ new Constraints\NotBlank(), new Constraints\Type(['type' => 'string']), new LocaleConstraint(), ], 'locale' ); }
Validates layout creation parameters from the request. @throws \Netgen\BlockManager\Exception\Validation\ValidationException If validation failed
private function getTimeZoneList(): array { if (count($this->timeZoneList) === 0) { $this->timeZoneList = DateTimeUtils::getTimeZoneList(); } return $this->timeZoneList; }
Returns the formatted list of all timezones, separated by regions.
public function validateCollectionCreateStruct(CollectionCreateStruct $collectionCreateStruct): void { if ($collectionCreateStruct->queryCreateStruct !== null) { $this->validate( $collectionCreateStruct->queryCreateStruct, [ new Constraints\Type(['type' => QueryCreateStruct::class]), ], 'queryCreateStruct' ); $this->validateQueryCreateStruct($collectionCreateStruct->queryCreateStruct); } $offsetConstraints = [ new Constraints\NotBlank(), new Constraints\Type(['type' => 'int']), ]; $offsetConstraints[] = $collectionCreateStruct->queryCreateStruct !== null ? new Constraints\GreaterThanOrEqual(['value' => 0]) : new Constraints\EqualTo(['value' => 0]); $this->validate( $collectionCreateStruct->offset, $offsetConstraints, 'offset' ); if ($collectionCreateStruct->limit !== null) { $this->validate( $collectionCreateStruct->limit, [ new Constraints\Type(['type' => 'int']), new Constraints\GreaterThan(['value' => 0]), ], 'limit' ); } }
Validates the provided collection create struct. @throws \Netgen\BlockManager\Exception\Validation\ValidationException If the validation failed
public function validateCollectionUpdateStruct(Collection $collection, CollectionUpdateStruct $collectionUpdateStruct): void { if ($collectionUpdateStruct->offset !== null) { $offsetConstraints = [ new Constraints\NotBlank(), new Constraints\Type(['type' => 'int']), ]; $offsetConstraints[] = $collection->hasQuery() ? new Constraints\GreaterThanOrEqual(['value' => 0]) : new Constraints\EqualTo(['value' => 0]); $this->validate( $collectionUpdateStruct->offset, $offsetConstraints, 'offset' ); } if ($collectionUpdateStruct->limit !== null) { $this->validate( $collectionUpdateStruct->limit, [ new Constraints\NotBlank(), new Constraints\Type(['type' => 'int']), new Constraints\GreaterThanOrEqual(['value' => 0]), ], 'limit' ); } }
Validates the provided collection update struct. @throws \Netgen\BlockManager\Exception\Validation\ValidationException If the validation failed
public function validateItemCreateStruct(ItemCreateStruct $itemCreateStruct): void { $this->validate( $itemCreateStruct->definition, [ new Constraints\NotNull(), new Constraints\Type(['type' => ItemDefinitionInterface::class]), ], 'definition' ); if ($itemCreateStruct->value !== null) { $this->validate( $itemCreateStruct->value, [ new Constraints\Type(['type' => 'scalar']), ], 'value' ); } $this->validate( $itemCreateStruct, new ConfigAwareStructConstraint( [ 'payload' => $itemCreateStruct->definition, ] ) ); }
Validates the provided item create struct. @throws \Netgen\BlockManager\Exception\Validation\ValidationException If the validation failed
public function validateItemUpdateStruct(Item $item, ItemUpdateStruct $itemUpdateStruct): void { $this->validate( $itemUpdateStruct, new ConfigAwareStructConstraint( [ 'payload' => $item->getDefinition(), 'allowMissingFields' => true, ] ) ); }
Validates the provided item update struct. @throws \Netgen\BlockManager\Exception\Validation\ValidationException If the validation failed
public function validateQueryCreateStruct(QueryCreateStruct $queryCreateStruct): void { $this->validate( $queryCreateStruct, [ new ParameterStruct( [ 'parameterDefinitions' => $queryCreateStruct->getQueryType(), ] ), ], 'parameterValues' ); }
Validates the provided query create struct. @throws \Netgen\BlockManager\Exception\Validation\ValidationException If the validation failed
public function validateQueryUpdateStruct(Query $query, QueryUpdateStruct $queryUpdateStruct): void { $this->validate( $queryUpdateStruct, [ new QueryUpdateStructConstraint( [ 'payload' => $query, ] ), ] ); }
Validates the provided query update struct. @throws \Netgen\BlockManager\Exception\Validation\ValidationException If the validation failed
public function visit($value, ?VisitorInterface $subVisitor = null) { if ($subVisitor === null) { throw new RuntimeException('Implementation requires sub-visitor'); } return [ 'id' => $value->getId(), 'position' => $value->getPosition(), 'value' => $value->getCmsItem()->getRemoteId(), 'value_type' => $value->getDefinition()->getValueType(), 'configuration' => iterator_to_array($this->visitConfiguration($value, $subVisitor)), ]; }
@param \Netgen\BlockManager\API\Values\Collection\Item $value @param \Netgen\BlockManager\Transfer\Output\VisitorInterface|null $subVisitor @return mixed
private function visitConfiguration(Item $item, VisitorInterface $subVisitor): Generator { foreach ($item->getConfigs() as $config) { yield $config->getConfigKey() => $subVisitor->visit($config); } }
Visit the given $item configuration into hash representation.
private function buildValueTypes(ContainerBuilder $container, array $valueTypes): Generator { foreach ($valueTypes as $identifier => $valueType) { $this->validateBrowserType($container, $identifier); $serviceIdentifier = sprintf('netgen_block_manager.item.value_type.%s', $identifier); $container->register($serviceIdentifier, ValueType::class) ->setArguments([$identifier, $valueType]) ->setLazy(true) ->setPublic(true) ->setFactory([ValueTypeFactory::class, 'buildValueType']); yield $identifier => new Reference($serviceIdentifier); } }
Builds the value type objects from provided configuration.