code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
public function onKernelRequest(GetResponseEvent $event): void { if (!$event->isMasterRequest()) { return; } $request = $event->getRequest(); $currentRoute = $request->attributes->get('_route', ''); if (mb_stripos($currentRoute, self::API_ROUTE_PREFIX) !== 0) { return; } $request->attributes->set(self::API_FLAG_NAME, true); }
Sets the self::API_FLAG_NAME flag if this is a REST API request.
private function buildConstraintFields( ParameterStruct $parameterStruct, ParameterStructConstraint $constraint ): Generator { foreach ($constraint->parameterDefinitions->getParameterDefinitions() as $parameterDefinition) { $constraints = $this->getParameterConstraints($parameterDefinition, $parameterStruct); if (!$parameterDefinition->isRequired()) { $constraints = new Constraints\Optional($constraints); } yield $parameterDefinition->getName() => $constraints; if ($parameterDefinition instanceof CompoundParameterDefinition) { foreach ($parameterDefinition->getParameterDefinitions() as $subParameterDefinition) { yield $subParameterDefinition->getName() => new Constraints\Optional( // Sub parameter values are always optional (either missing or set to null) // so we don't have to validate empty values $this->getParameterConstraints($subParameterDefinition, $parameterStruct, false) ); } } } }
Builds the "fields" array of the Collection constraint from provided parameters and parameter values.
private function getParameterConstraints( ParameterDefinition $parameterDefinition, ParameterStruct $parameterStruct, bool $validateEmptyValue = true ): array { $parameterValue = $parameterStruct->getParameterValue( $parameterDefinition->getName() ); if (!$validateEmptyValue && $parameterValue === null) { return []; } return $parameterDefinition->getType()->getConstraints( $parameterDefinition, $parameterValue ); }
Returns all constraints applied on a parameter coming directly from parameter type. If $validateEmptyValue is false, values equal to null will not be validated and will simply return an empty array of constraints.
private function getRuntimeParameterConstraints( ParameterDefinition $parameterDefinition, $parameterValue, array $allParameterValues ): Generator { foreach ($parameterDefinition->getConstraints() as $constraint) { if ($constraint instanceof Closure) { $constraint = $constraint($parameterValue, $allParameterValues, $parameterDefinition); } if ($constraint instanceof Constraint) { yield $constraint; } } }
Returns all constraints applied on a parameter coming from the parameter definition. @param mixed $parameterValue
public function onRenderView(CollectViewParametersEvent $event): void { $view = $event->getView(); if (!$view instanceof BlockViewInterface) { return; } $block = $view->getBlock(); $blockDefinition = $block->getDefinition(); if (!$blockDefinition instanceof TwigBlockDefinitionInterface) { return; } $twigContent = $this->getTwigBlockContent( $blockDefinition, $block, $view->getParameters() ); $event->addParameter('twig_content', $twigContent); }
Adds a parameter to the view with the Twig block content.
private function getTwigBlockContent( TwigBlockDefinitionInterface $blockDefinition, Block $block, array $parameters ): string { if (!isset($parameters['twig_template'])) { return ''; } if (!$parameters['twig_template'] instanceof ContextualizedTwigTemplate) { return ''; } return $parameters['twig_template']->renderBlock( $blockDefinition->getTwigBlockName($block) ); }
Returns the Twig block content from the provided block.
public function createLayout(array $data): Layout { $createStruct = $this->layoutService->newLayoutCreateStruct( $this->layoutTypeRegistry->getLayoutType($data['type_identifier']), sprintf('%s (Imported on %s)', $data['name'], date('D, d M Y H:i:s')), $data['main_locale'] ); $createStruct->description = $data['description']; $createStruct->shared = $data['is_shared']; return $this->layoutService->transaction( function () use ($createStruct, $data): Layout { $layoutDraft = $this->layoutService->createLayout($createStruct); $this->addTranslations($layoutDraft, $data); $this->processZones($layoutDraft, $data); return $this->layoutService->publishLayout($layoutDraft); } ); }
Create and return layout from the given serialized $data.
private function processZones(Layout $layout, array $layoutData): void { foreach ($layout->getZones() as $zone) { if (!array_key_exists($zone->getIdentifier(), $layoutData['zones'])) { throw new RuntimeException( sprintf('Missing data for zone "%s"', $zone->getIdentifier()) ); } $this->processZone($zone, $layoutData['zones'][$zone->getIdentifier()]); } }
Processes zones in the given $layout from the $layoutData. @throws \Netgen\BlockManager\Exception\RuntimeException If data is not consistent
private function addTranslations(Layout $layout, array $layoutData): void { $translationLocales = $this->extractTranslationLocales($layoutData); foreach ($translationLocales as $locale) { $this->layoutService->addTranslation($layout, $locale, $layoutData['main_locale']); } }
Add translations to the $layout from the given $layoutData.
private function updateBlockTranslations(Block $block, array $translationsData): void { $mainLocale = $block->getMainLocale(); foreach ($block->getAvailableLocales() as $locale) { if ($locale === $mainLocale) { continue; } if (!array_key_exists($locale, $translationsData)) { throw new RuntimeException( sprintf('Could not find locale "%s" in the given block data', $locale) ); } $this->updateBlockTranslation($block, $translationsData[$locale], $locale); } }
Update all translations of the given block with the $translationsData. $translationsData is an array of parameters, indexed by translation locale. @throws \Netgen\BlockManager\Exception\RuntimeException If translation data is not consistent
private function updateBlockTranslation(Block $block, array $parameterData, string $locale): void { $updateStruct = $this->blockService->newBlockUpdateStruct($locale, $block); $updateStruct->fillParametersFromHash($block->getDefinition(), $parameterData, true); $this->blockService->updateBlock($block, $updateStruct); }
Update given $block with $parameterData for the $locale.
private function updateQueryTranslations(Query $query, array $translationsData): void { $mainLocale = $query->getMainLocale(); foreach ($query->getAvailableLocales() as $locale) { if ($locale === $mainLocale) { continue; } if (!array_key_exists($locale, $translationsData)) { throw new RuntimeException( sprintf('Could not find locale "%s" in the given query data', $locale) ); } $this->updateQueryTranslation($query, $translationsData[$locale], $locale); } }
Update all translations of the given query with $translationsData. $translationsData is an array of query parameters indexed by translation locale. @throws \Netgen\BlockManager\Exception\RuntimeException If translation data is not consistent
private function updateQueryTranslation(Query $query, array $parameterData, string $locale): void { $updateStruct = $this->collectionService->newQueryUpdateStruct($locale, $query); $updateStruct->fillParametersFromHash($query->getQueryType(), $parameterData, true); $this->collectionService->updateQuery($query, $updateStruct); }
Update given $query with $parameterData for the $locale.
private function processZone(Zone $zone, array $zoneData): void { $this->createBlocks($zone, $zoneData['blocks']); if (is_array($zoneData['linked_zone'])) { $this->linkZone($zone, $zoneData['linked_zone']); } }
Creates blocks in the given $zone or links linked zone to it.
private function linkZone(Zone $zone, array $zoneData): void { $linkedZoneLayout = $this->layoutService->loadLayout($zoneData['layout_id']); $linkedZone = $linkedZoneLayout->getZone($zoneData['identifier']); $this->layoutService->linkZone($zone, $linkedZone); }
Link given $zone with the zone given in $zoneData.
private function createBlocks(Zone $zone, array $blocksData): void { foreach ($blocksData as $blockData) { $this->createBlockInZone($zone, $blockData); } }
Create blocks in the given $zone from the given $blocksData.
private function createBlockInZone(Zone $zone, array $blockData): Block { $blockCreateStruct = $this->buildBlockCreateStruct($blockData); $block = $this->blockService->createBlockInZone($blockCreateStruct, $zone); $this->updateBlockTranslations($block, $blockData['parameters']); $this->processPlaceholderBlocks($block, $blockData['placeholders']); $this->processCollections($block, $blockData['collections']); return $block; }
Create a block in the given $zone from the given $blockData.
private function createBlock(Block $targetBlock, string $placeholder, array $blockData): Block { $blockCreateStruct = $this->buildBlockCreateStruct($blockData); $block = $this->blockService->createBlock($blockCreateStruct, $targetBlock, $placeholder); $this->updateBlockTranslations($block, $blockData['parameters']); $this->processPlaceholderBlocks($block, $blockData['placeholders']); $this->processCollections($block, $blockData['collections']); return $block; }
Create a block in the given $targetBlock and $placeholder from the given $blockData.
private function processPlaceholderBlocks(Block $targetBlock, array $data): void { foreach ($data as $placeholder => $placeholderData) { foreach ($placeholderData['blocks'] as $blockData) { $this->createBlock($targetBlock, $placeholder, $blockData); } } }
Creates sub-blocks in $targetBlock from provided placeholder $data.
private function buildBlockCreateStruct(array $blockData): BlockCreateStruct { if (!array_key_exists($blockData['main_locale'], $blockData['parameters'])) { throw new RuntimeException( sprintf('Missing data for block main locale "%s"', $blockData['main_locale']) ); } $blockDefinition = $this->blockDefinitionRegistry->getBlockDefinition($blockData['definition_identifier']); $blockCreateStruct = $this->blockService->newBlockCreateStruct($blockDefinition); $blockCreateStruct->name = $blockData['name']; $blockCreateStruct->viewType = $blockData['view_type']; $blockCreateStruct->itemViewType = $blockData['item_view_type']; $blockCreateStruct->isTranslatable = $blockData['is_translatable']; $blockCreateStruct->alwaysAvailable = $blockData['is_always_available']; $blockCreateStruct->fillParametersFromHash($blockData['parameters'][$blockData['main_locale']], true); $this->setConfigStructs($blockCreateStruct, $blockDefinition, $blockData['configuration'] ?? []); $this->setCollectionStructs($blockCreateStruct, $blockData['collections']); return $blockCreateStruct; }
Builds the block create struct from provided $blockData.
private function setCollectionStructs(BlockCreateStruct $blockCreateStruct, array $data): void { foreach ($data as $collectionIdentifier => $collectionData) { $queryCreateStruct = null; if (is_array($collectionData['query'])) { if (!array_key_exists($collectionData['main_locale'], $collectionData['query']['parameters'])) { throw new RuntimeException( sprintf('Missing data for query main locale "%s"', $collectionData['main_locale']) ); } $queryType = $this->queryTypeRegistry->getQueryType($collectionData['query']['query_type']); $queryCreateStruct = $this->collectionService->newQueryCreateStruct($queryType); $queryCreateStruct->fillParametersFromHash($collectionData['query']['parameters'][$collectionData['main_locale']], true); } $collectionCreateStruct = $this->collectionService->newCollectionCreateStruct($queryCreateStruct); $collectionCreateStruct->offset = $collectionData['offset']; $collectionCreateStruct->limit = $collectionData['limit']; $blockCreateStruct->addCollectionCreateStruct($collectionIdentifier, $collectionCreateStruct); } }
Set collection structs to the given $blockCreateStruct.
private function setConfigStructs( ConfigAwareStruct $configAwareStruct, ConfigDefinitionAwareInterface $configDefinitionAware, array $configurationData ): void { $configDefinitions = $configDefinitionAware->getConfigDefinitions(); foreach ($configurationData as $configKey => $hash) { $configStruct = new ConfigStruct(); $configStruct->fillParametersFromHash($configDefinitions[$configKey], $hash, true); $configAwareStruct->setConfigStruct($configKey, $configStruct); } }
Set configuration structs to the given $blockCreateStruct.
private function processCollections(Block $block, array $collectionsData): void { foreach ($block->getCollections() as $identifier => $collection) { $collectionData = $collectionsData[$identifier]; $collectionQuery = $collection->getQuery(); if ($collectionQuery instanceof Query && is_array($collectionData['query'])) { $this->updateQueryTranslations( $collectionQuery, $collectionData['query']['parameters'] ); } $this->createItems($collection, $collectionData['items']); } }
Process collections in the given $block.
private function createItems(Collection $collection, array $collectionItemsData): void { foreach ($collectionItemsData as $collectionItemData) { $itemDefinition = $this->itemDefinitionRegistry->getItemDefinition($collectionItemData['value_type']); $item = $this->cmsItemLoader->loadByRemoteId( $collectionItemData['value'], $collectionItemData['value_type'] ); $itemCreateStruct = $this->collectionService->newItemCreateStruct( $itemDefinition, $item->getValue() ); $this->setConfigStructs( $itemCreateStruct, $itemDefinition, $collectionItemData['configuration'] ?? [] ); $this->collectionService->addItem($collection, $itemCreateStruct, $collectionItemData['position']); } }
Create items in the $collection from the given $collectionItemsData.
public function validateRuleCreateStruct(RuleCreateStruct $ruleCreateStruct): void { if ($ruleCreateStruct->layoutId !== null) { $this->validate( $ruleCreateStruct->layoutId, [ new Constraints\NotBlank(), new Constraints\Type(['type' => 'scalar']), ], 'layoutId' ); } if ($ruleCreateStruct->priority !== null) { $this->validate( $ruleCreateStruct->priority, [ new Constraints\Type(['type' => 'int']), ], 'priority' ); } if ($ruleCreateStruct->enabled !== null) { $this->validate( $ruleCreateStruct->enabled, [ new Constraints\Type(['type' => 'bool']), ], 'enabled' ); } if ($ruleCreateStruct->comment !== null) { $this->validate( $ruleCreateStruct->comment, [ new Constraints\Type(['type' => 'string']), ], 'comment' ); } }
Validates the provided rule create struct. @throws \Netgen\BlockManager\Exception\Validation\ValidationException If the validation failed
public function validateRuleUpdateStruct(RuleUpdateStruct $ruleUpdateStruct): void { if ($ruleUpdateStruct->layoutId !== null) { $this->validate( $ruleUpdateStruct->layoutId, [ new Constraints\NotBlank(), new Constraints\Type(['type' => 'scalar']), ], 'layoutId' ); } if ($ruleUpdateStruct->comment !== null) { $this->validate( $ruleUpdateStruct->comment, [ new Constraints\Type(['type' => 'string']), ], 'comment' ); } }
Validates the provided rule update struct. @throws \Netgen\BlockManager\Exception\Validation\ValidationException If the validation failed
public function validateRuleMetadataUpdateStruct(RuleMetadataUpdateStruct $ruleUpdateStruct): void { if ($ruleUpdateStruct->priority !== null) { $this->validate( $ruleUpdateStruct->priority, [ new Constraints\NotBlank(), new Constraints\Type(['type' => 'int']), ], 'priority' ); } }
Validates the provided rule metadata update struct. @throws \Netgen\BlockManager\Exception\Validation\ValidationException If the validation failed
public function validateTargetCreateStruct(TargetCreateStruct $targetCreateStruct): void { $this->validate( $targetCreateStruct->type, [ new Constraints\NotBlank(), new Constraints\Type(['type' => 'string']), ], 'type' ); $targetType = $this->targetTypeRegistry->getTargetType($targetCreateStruct->type); $this->validate( $targetCreateStruct->value, $targetType->getConstraints(), 'value' ); }
Validates the provided target create struct. @throws \Netgen\BlockManager\Exception\Validation\ValidationException If the validation failed
public function validateTargetUpdateStruct(Target $target, TargetUpdateStruct $targetUpdateStruct): void { $targetType = $target->getTargetType(); $this->validate( $targetUpdateStruct->value, $targetType->getConstraints(), 'value' ); }
Validates the provided target update struct. @throws \Netgen\BlockManager\Exception\Validation\ValidationException If the validation failed
public function validateConditionCreateStruct(ConditionCreateStruct $conditionCreateStruct): void { $this->validate( $conditionCreateStruct->type, [ new Constraints\NotBlank(), new Constraints\Type(['type' => 'string']), ], 'type' ); $conditionType = $this->conditionTypeRegistry->getConditionType($conditionCreateStruct->type); $this->validate( $conditionCreateStruct->value, $conditionType->getConstraints(), 'value' ); }
Validates the provided condition create struct. @throws \Netgen\BlockManager\Exception\Validation\ValidationException If the validation failed
public function validateConditionUpdateStruct(Condition $condition, ConditionUpdateStruct $conditionUpdateStruct): void { $conditionType = $condition->getConditionType(); $this->validate( $conditionUpdateStruct->value, $conditionType->getConstraints(), 'value' ); }
Validates the provided condition update struct. @throws \Netgen\BlockManager\Exception\Validation\ValidationException If the validation failed
public function mapZone(PersistenceZone $zone): Zone { $zoneData = [ 'identifier' => $zone->identifier, 'layoutId' => $zone->layoutId, 'status' => $zone->status, 'linkedZone' => function () use ($zone): ?Zone { if ($zone->linkedLayoutId === null || $zone->linkedZoneIdentifier === null) { return null; } try { // We're always using published versions of linked zones $linkedZone = $this->layoutHandler->loadZone( $zone->linkedLayoutId, PersistenceValue::STATUS_PUBLISHED, $zone->linkedZoneIdentifier ); return $this->mapZone($linkedZone); } catch (NotFoundException $e) { return null; } }, ]; return Zone::fromArray($zoneData); }
Builds the API zone value from persistence one.
public function mapLayout(PersistenceLayout $layout): Layout { try { $layoutType = $this->layoutTypeRegistry->getLayoutType($layout->type); } catch (LayoutTypeException $e) { $layoutType = new NullLayoutType($layout->type); } $layoutData = [ 'id' => $layout->id, 'layoutType' => $layoutType, 'name' => $layout->name, 'description' => $layout->description, 'created' => DateTimeUtils::createFromTimestamp($layout->created), 'modified' => DateTimeUtils::createFromTimestamp($layout->modified), 'status' => $layout->status, 'shared' => $layout->shared, 'mainLocale' => $layout->mainLocale, 'availableLocales' => $layout->availableLocales, 'zones' => new LazyCollection( function () use ($layout): array { return array_map( function (PersistenceZone $zone): Zone { return $this->mapZone($zone); }, $this->layoutHandler->loadLayoutZones($layout) ); } ), ]; return Layout::fromArray($layoutData); }
Builds the API layout value from persistence one.
public function loadRuleData($ruleId, int $status): array { $query = $this->getRuleSelectQuery(); $query->where( $query->expr()->eq('r.id', ':id') ) ->setParameter('id', $ruleId, Type::INTEGER); $this->applyStatusCondition($query, $status, 'r.status'); return $query->execute()->fetchAll(PDO::FETCH_ASSOC); }
Returns all data for specified rule. @param int|string $ruleId @param int $status @return array
public function loadRulesData(int $status, ?Layout $layout = null, int $offset = 0, ?int $limit = null): array { $query = $this->getRuleSelectQuery(); if ($layout instanceof Layout) { $query->andWhere( $query->expr()->eq('layout_id', ':layout_id') ) ->setParameter('layout_id', $layout->id, Type::INTEGER); } $query->addOrderBy('rd.priority', 'DESC'); $this->applyStatusCondition($query, $status, 'r.status'); $this->applyOffsetAndLimit($query, $offset, $limit); return $query->execute()->fetchAll(PDO::FETCH_ASSOC); }
Returns all data for all rules.
public function getRuleCount(int $ruleStatus, ?Layout $layout = null): int { $query = $this->connection->createQueryBuilder(); $query->select('count(*) AS count') ->from('ngbm_rule'); if ($layout instanceof Layout) { $query->andWhere( $query->expr()->eq('layout_id', ':layout_id') ) ->setParameter('layout_id', $layout->id, Type::INTEGER); } $this->applyStatusCondition($query, $ruleStatus); $data = $query->execute()->fetchAll(PDO::FETCH_ASSOC); return (int) ($data[0]['count'] ?? 0); }
Returns the number of rules.
public function matchRules(string $targetType, $targetValue): array { $query = $this->getRuleSelectQuery(); $query ->innerJoin( 'r', 'ngbm_rule_target', 'rt', $query->expr()->eq('r.id', 'rt.rule_id') ) ->where( $query->expr()->eq('rd.enabled', ':enabled'), $query->expr()->eq('rt.type', ':target_type') ) ->setParameter('target_type', $targetType, Type::STRING) ->setParameter('enabled', true, Type::BOOLEAN) ->addOrderBy('rd.priority', 'DESC'); $this->applyStatusCondition($query, Value::STATUS_PUBLISHED, 'r.status'); $this->applyStatusCondition($query, Value::STATUS_PUBLISHED, 'rt.status'); if (!isset($this->targetHandlers[$targetType])) { throw TargetHandlerException::noTargetHandler('Doctrine', $targetType); } $this->targetHandlers[$targetType]->handleQuery($query, $targetValue); return $query->execute()->fetchAll(PDO::FETCH_ASSOC); }
Returns all rule data for rules that match specified target type and value. @param string $targetType @param mixed $targetValue @return array
public function loadTargetData($targetId, int $status): array { $query = $this->getTargetSelectQuery(); $query->where( $query->expr()->eq('id', ':id') ) ->setParameter('id', $targetId, Type::INTEGER); $this->applyStatusCondition($query, $status); return $query->execute()->fetchAll(PDO::FETCH_ASSOC); }
Returns all data for specified target. @param int|string $targetId @param int $status @return array
public function loadRuleTargetsData(Rule $rule): array { $query = $this->getTargetSelectQuery(); $query->where( $query->expr()->eq('rule_id', ':rule_id') ) ->setParameter('rule_id', $rule->id, Type::INTEGER) ->orderBy('id', 'ASC'); $this->applyStatusCondition($query, $rule->status); return $query->execute()->fetchAll(PDO::FETCH_ASSOC); }
Returns all data for all rule targets.
public function getTargetCount(Rule $rule): int { $query = $this->connection->createQueryBuilder(); $query->select('count(*) AS count') ->from('ngbm_rule_target') ->where( $query->expr()->eq('rule_id', ':rule_id') ) ->setParameter('rule_id', $rule->id, Type::INTEGER); $this->applyStatusCondition($query, $rule->status); $data = $query->execute()->fetchAll(PDO::FETCH_ASSOC); return (int) ($data[0]['count'] ?? 0); }
Returns the number of targets within the rule.
public function loadConditionData($conditionId, int $status): array { $query = $this->getConditionSelectQuery(); $query->where( $query->expr()->eq('id', ':id') ) ->setParameter('id', $conditionId, Type::INTEGER); $this->applyStatusCondition($query, $status); return $query->execute()->fetchAll(PDO::FETCH_ASSOC); }
Returns all data for specified condition. @param int|string $conditionId @param int $status @return array
public function getLowestRulePriority(): ?int { $query = $this->connection->createQueryBuilder(); $query->select('priority') ->from('ngbm_rule_data'); $query->addOrderBy('priority', 'ASC'); $this->applyOffsetAndLimit($query, 0, 1); $data = $query->execute()->fetchAll(PDO::FETCH_ASSOC); return isset($data[0]['priority']) ? (int) $data[0]['priority'] : null; }
Returns the lowest priority from the list of all the rules.
public function createRule(Rule $rule): Rule { $query = $this->connection->createQueryBuilder() ->insert('ngbm_rule') ->values( [ 'id' => ':id', 'status' => ':status', 'layout_id' => ':layout_id', 'comment' => ':comment', ] ) ->setValue( 'id', $rule->id !== null ? (int) $rule->id : $this->connectionHelper->getAutoIncrementValue('ngbm_rule') ) ->setParameter('status', $rule->status, Type::INTEGER) ->setParameter('layout_id', $rule->layoutId, Type::INTEGER) ->setParameter('comment', $rule->comment, Type::STRING); $query->execute(); if ($rule->id === null) { $rule->id = (int) $this->connectionHelper->lastInsertId('ngbm_rule'); $query = $this->connection->createQueryBuilder() ->insert('ngbm_rule_data') ->values( [ 'rule_id' => ':rule_id', 'enabled' => ':enabled', 'priority' => ':priority', ] ) ->setParameter('rule_id', $rule->id, Type::INTEGER) ->setParameter('enabled', $rule->enabled, Type::BOOLEAN) ->setParameter('priority', $rule->priority, Type::INTEGER); $query->execute(); } return $rule; }
Creates a rule.
public function updateRule(Rule $rule): void { $query = $this->connection->createQueryBuilder(); $query ->update('ngbm_rule') ->set('layout_id', ':layout_id') ->set('comment', ':comment') ->where( $query->expr()->eq('id', ':id') ) ->setParameter('id', $rule->id, Type::INTEGER) ->setParameter('layout_id', $rule->layoutId, Type::INTEGER) ->setParameter('comment', $rule->comment, Type::STRING); $this->applyStatusCondition($query, $rule->status); $query->execute(); }
Updates a rule.
public function updateRuleData(Rule $rule): void { $query = $this->connection->createQueryBuilder(); $query ->update('ngbm_rule_data') ->set('enabled', ':enabled') ->set('priority', ':priority') ->where( $query->expr()->eq('rule_id', ':rule_id') ) ->setParameter('rule_id', $rule->id, Type::INTEGER) ->setParameter('enabled', $rule->enabled, Type::BOOLEAN) ->setParameter('priority', $rule->priority, Type::INTEGER); $query->execute(); }
Updates rule data which is independent of statuses.
public function deleteRule($ruleId, ?int $status = null): void { $query = $this->connection->createQueryBuilder(); $query->delete('ngbm_rule') ->where( $query->expr()->eq('id', ':id') ) ->setParameter('id', $ruleId, Type::INTEGER); if ($status !== null) { $this->applyStatusCondition($query, $status); } $query->execute(); if (!$this->ruleExists($ruleId)) { $query = $this->connection->createQueryBuilder(); $query->delete('ngbm_rule_data') ->where( $query->expr()->eq('rule_id', ':rule_id') ) ->setParameter('rule_id', $ruleId, Type::INTEGER); $query->execute(); } }
Deletes a rule. @param int|string $ruleId @param int $status
public function addTarget(Target $target): Target { $query = $this->connection->createQueryBuilder() ->insert('ngbm_rule_target') ->values( [ 'id' => ':id', 'status' => ':status', 'rule_id' => ':rule_id', 'type' => ':type', 'value' => ':value', ] ) ->setValue( 'id', $target->id !== null ? (int) $target->id : $this->connectionHelper->getAutoIncrementValue('ngbm_rule_target') ) ->setParameter('status', $target->status, Type::INTEGER) ->setParameter('rule_id', $target->ruleId, Type::INTEGER) ->setParameter('type', $target->type, Type::STRING) ->setParameter('value', $target->value, is_array($target->value) ? Type::JSON_ARRAY : Type::STRING); $query->execute(); $target->id = $target->id ?? (int) $this->connectionHelper->lastInsertId('ngbm_rule_target'); return $target; }
Adds a target.
public function updateTarget(Target $target): void { $query = $this->connection->createQueryBuilder(); $query ->update('ngbm_rule_target') ->set('rule_id', ':rule_id') ->set('type', ':type') ->set('value', ':value') ->where( $query->expr()->eq('id', ':id') ) ->setParameter('id', $target->id, Type::INTEGER) ->setParameter('rule_id', $target->ruleId, Type::INTEGER) ->setParameter('type', $target->type, Type::STRING) ->setParameter('value', $target->value, is_array($target->value) ? Type::JSON_ARRAY : Type::STRING); $this->applyStatusCondition($query, $target->status); $query->execute(); }
Updates a target.
public function addCondition(Condition $condition): Condition { $query = $this->connection->createQueryBuilder() ->insert('ngbm_rule_condition') ->values( [ 'id' => ':id', 'status' => ':status', 'rule_id' => ':rule_id', 'type' => ':type', 'value' => ':value', ] ) ->setValue( 'id', $condition->id !== null ? (int) $condition->id : $this->connectionHelper->getAutoIncrementValue('ngbm_rule_condition') ) ->setParameter('status', $condition->status, Type::INTEGER) ->setParameter('rule_id', $condition->ruleId, Type::INTEGER) ->setParameter('type', $condition->type, Type::STRING) ->setParameter('value', json_encode($condition->value), Type::STRING); $query->execute(); $condition->id = $condition->id ?? (int) $this->connectionHelper->lastInsertId('ngbm_rule_condition'); return $condition; }
Adds a condition.
public function updateCondition(Condition $condition): void { $query = $this->connection->createQueryBuilder(); $query ->update('ngbm_rule_condition') ->set('rule_id', ':rule_id') ->set('type', ':type') ->set('value', ':value') ->where( $query->expr()->eq('id', ':id') ) ->setParameter('id', $condition->id, Type::INTEGER) ->setParameter('rule_id', $condition->ruleId, Type::INTEGER) ->setParameter('type', $condition->type, Type::STRING) ->setParameter('value', json_encode($condition->value), Type::STRING); $this->applyStatusCondition($query, $condition->status); $query->execute(); }
Updates a condition.
private function getRuleSelectQuery(): QueryBuilder { $query = $this->connection->createQueryBuilder(); $query->select('DISTINCT r.*', 'rd.*') ->from('ngbm_rule', 'r') ->innerJoin( 'r', 'ngbm_rule_data', 'rd', $query->expr()->eq('rd.rule_id', 'r.id') ); return $query; }
Builds and returns a rule database SELECT query.
private function getTargetSelectQuery(): QueryBuilder { $query = $this->connection->createQueryBuilder(); $query->select('DISTINCT ngbm_rule_target.*') ->from('ngbm_rule_target'); return $query; }
Builds and returns a target database SELECT query.
private function getConditionSelectQuery(): QueryBuilder { $query = $this->connection->createQueryBuilder(); $query->select('DISTINCT ngbm_rule_condition.*') ->from('ngbm_rule_condition'); return $query; }
Builds and returns a condition database SELECT query.
public function getZone(string $zoneIdentifier): APIZone { if ($this->hasZone($zoneIdentifier)) { return $this->zones->get($zoneIdentifier); } throw LayoutException::noZone($zoneIdentifier); }
Returns the specified zone. @throws \Netgen\BlockManager\Exception\API\LayoutException If the zone does not exist
public function validateLayoutCreateStruct(LayoutCreateStruct $layoutCreateStruct): void { $layoutName = is_string($layoutCreateStruct->name) ? trim($layoutCreateStruct->name) : $layoutCreateStruct->name; $this->validate( $layoutName, [ new Constraints\NotBlank(), new Constraints\Type(['type' => 'string']), ], 'name' ); if ($layoutCreateStruct->description !== null) { $this->validate( $layoutCreateStruct->description, [ new Constraints\Type(['type' => 'string']), ], 'description' ); } $this->validate( $layoutCreateStruct->layoutType, [ new Constraints\NotBlank(), new Constraints\Type(['type' => LayoutTypeInterface::class]), ], 'layoutType' ); $this->validateLocale($layoutCreateStruct->mainLocale, 'mainLocale'); if ($layoutCreateStruct->shared !== null) { $this->validate( $layoutCreateStruct->shared, [ new Constraints\Type(['type' => 'bool']), ], 'shared' ); } }
Validates the provided layout create struct. @throws \Netgen\BlockManager\Exception\Validation\ValidationException If the validation failed
public function validateLayoutUpdateStruct(LayoutUpdateStruct $layoutUpdateStruct): void { $layoutName = is_string($layoutUpdateStruct->name) ? trim($layoutUpdateStruct->name) : $layoutUpdateStruct->name; if ($layoutName !== null) { $this->validate( $layoutName, [ new Constraints\NotBlank(), new Constraints\Type(['type' => 'string']), ], 'name' ); } if ($layoutUpdateStruct->description !== null) { $this->validate( $layoutUpdateStruct->description, [ new Constraints\Type(['type' => 'string']), ], 'description' ); } }
Validates the provided layout update struct. @throws \Netgen\BlockManager\Exception\Validation\ValidationException If the validation failed
public function validateLayoutCopyStruct(LayoutCopyStruct $layoutCopyStruct): void { $layoutName = is_string($layoutCopyStruct->name) ? trim($layoutCopyStruct->name) : $layoutCopyStruct->name; $this->validate( $layoutName, [ new Constraints\NotBlank(), new Constraints\Type(['type' => 'string']), ], 'name' ); if ($layoutCopyStruct->description !== null) { $this->validate( $layoutCopyStruct->description, [ new Constraints\Type(['type' => 'string']), ], 'description' ); } }
Validates the provided layout copy struct. @throws \Netgen\BlockManager\Exception\Validation\ValidationException If the validation failed
public function validateChangeLayoutType(Layout $layout, LayoutTypeInterface $targetLayoutType, array $zoneMappings, bool $preserveSharedZones = true): void { $seenZones = []; foreach ($zoneMappings as $newZone => $oldZones) { if (!$targetLayoutType->hasZone($newZone)) { throw ValidationException::validationFailed( 'zoneMappings', sprintf( 'Zone "%s" does not exist in "%s" layout type.', $newZone, $targetLayoutType->getIdentifier() ) ); } if (!is_array($oldZones)) { throw ValidationException::validationFailed( 'zoneMappings', sprintf( 'The list of mapped zones for "%s" zone must be an array.', $newZone ) ); } $oldLayoutZones = []; foreach ($oldZones as $oldZone) { if (in_array($oldZone, $seenZones, true)) { throw ValidationException::validationFailed( 'zoneMappings', sprintf( 'Zone "%s" is specified more than once.', $oldZone ) ); } $seenZones[] = $oldZone; $oldLayoutZones[] = $layout->getZone($oldZone); } if ($preserveSharedZones && count($oldLayoutZones) > 1) { foreach ($oldLayoutZones as $oldZone) { if ($oldZone->getLinkedZone() instanceof Zone) { throw ValidationException::validationFailed( 'zoneMappings', sprintf( 'When preserving shared layout zones, mapping for zone "%s" needs to be 1:1.', $newZone ) ); } } } } }
Validates zone mappings for changing the provided layout type. @throws \Netgen\BlockManager\Exception\Validation\ValidationException If the validation failed
public function onBuildView(CollectViewParametersEvent $event): void { $view = $event->getView(); if (!$view instanceof LayoutViewInterface) { return; } if ($view->getContext() !== ViewInterface::CONTEXT_ADMIN) { return; } $layout = $view->getLayout(); $relatedLayoutsCount = 0; if ($layout->isShared() && $layout->isPublished()) { $relatedLayoutsCount = $this->layoutService->getRelatedLayoutsCount($layout); } $event->addParameter('related_layouts_count', $relatedLayoutsCount); }
Injects the number of layouts connected to the shared layout provided by the event.
public function fillParametersFromHash(ConfigDefinitionInterface $configDefinition, array $values, bool $doImport = false): void { $this->fillFromHash($configDefinition, $values, $doImport); }
Fills the parameter values based on provided array of values. If any of the parameters is missing from the input array, the default value based on parameter definition from the config definition will be used. The values in the array need to be in hash format of the value i.e. the format acceptable by the ParameterTypeInterface::fromHash method. If $doImport is set to true, the values will be considered as coming from an import, meaning it will be processed using ParameterTypeInterface::import method instead of ParameterTypeInterface::fromHash method.
public function onKernelRequest(GetResponseEvent $event): void { if (!$event->isMasterRequest()) { return; } $request = $event->getRequest(); if ($request->attributes->get('_route') !== 'ngbm_ajax_block') { return; } if ($request->attributes->has('ngbmContextUri')) { return; } // This is a naive implementation which removes the need to deconstruct // the URI with parse_url/parse_str and then rebuilding it, just to remove // a single query parameter with a known name and format. $requestUri = preg_replace( ['/&page=\d+/', '/\?page=\d+&/', '/\?page=\d+/'], ['', '?', ''], $request->getRequestUri() ); $request->attributes->set('ngbmContextUri', $requestUri); }
Removes the "page" query parameter from the AJAX block request URI in order to remove the need to hash the page number, which greatly simplifies generating URIs to single pages of AJAX block request. If we were to hash the page parameter too, JavaScript code would not be able to generate the link to a single page simply by changing the page number.
private function getZones(Layout $layout, LayoutTypeInterface $layoutType): Generator { foreach ($layout as $zoneIdentifier => $zone) { $linkedZone = $zone->getLinkedZone(); yield [ 'identifier' => $zoneIdentifier, 'name' => $this->getZoneName($zone, $layoutType), 'block_ids' => $this->blockService->loadZoneBlocks($zone)->getBlockIds(), 'allowed_block_definitions' => $this->getAllowedBlocks( $zone, $layoutType ), 'linked_layout_id' => $linkedZone ? $linkedZone->getLayoutId() : null, 'linked_zone_identifier' => $linkedZone ? $linkedZone->getIdentifier() : null, ]; } }
Returns the array with layout zones.
private function getZoneName(Zone $zone, LayoutTypeInterface $layoutType): string { if ($layoutType->hasZone($zone->getIdentifier())) { return $layoutType->getZone($zone->getIdentifier())->getName(); } return $zone->getIdentifier(); }
Returns provided zone name.
private function getAllowedBlocks(Zone $zone, LayoutTypeInterface $layoutType) { if ($layoutType->hasZone($zone->getIdentifier())) { $layoutTypeZone = $layoutType->getZone($zone->getIdentifier()); $allowedBlockDefinitions = $layoutTypeZone->getAllowedBlockDefinitions(); if (count($allowedBlockDefinitions) > 0) { return $allowedBlockDefinitions; } } return true; }
Returns all allowed block definitions from provided zone or true if all block definitions are allowed. @param \Netgen\BlockManager\API\Values\Layout\Zone $zone @param \Netgen\BlockManager\Layout\Type\LayoutTypeInterface $layoutType @return string[]|bool
private function generateBlockTypeGroupConfig(array $blockTypeGroups, array $blockTypes): array { $missingBlockTypes = []; // We will add all blocks which are not located in any group to a custom group // if it exists if (isset($blockTypeGroups['custom'])) { foreach (array_keys($blockTypes) as $blockType) { foreach ($blockTypeGroups as $blockTypeGroup) { if (in_array($blockType, $blockTypeGroup['block_types'], true)) { continue 2; } } $missingBlockTypes[] = $blockType; } $blockTypeGroups['custom']['block_types'] = array_merge( $blockTypeGroups['custom']['block_types'], $missingBlockTypes ); } return $blockTypeGroups; }
Generates the block type group configuration from provided block types.
private function buildBlockTypeGroups(ContainerBuilder $container, array $blockTypeGroups, array $blockTypes): Generator { foreach ($blockTypeGroups as $identifier => $blockTypeGroup) { $serviceIdentifier = sprintf('netgen_block_manager.block.block_type_group.%s', $identifier); $blockTypeReferences = []; foreach ($blockTypeGroup['block_types'] as $blockTypeIdentifier) { if (isset($blockTypes[$blockTypeIdentifier])) { $blockTypeReferences[] = new Reference( sprintf( 'netgen_block_manager.block.block_type.%s', $blockTypeIdentifier ) ); } } $container->register($serviceIdentifier, BlockTypeGroup::class) ->setArguments([$identifier, $blockTypeGroup, $blockTypeReferences]) ->setLazy(true) ->setPublic(true) ->setFactory([BlockTypeGroupFactory::class, 'buildBlockTypeGroup']); yield $identifier => new Reference($serviceIdentifier); } }
Builds the block type group objects from provided configuration.
public function loadBlockData($blockId, int $status): array { $query = $this->getBlockSelectQuery(); $query->where( $query->expr()->eq('b.id', ':id') ) ->setParameter('id', $blockId, Type::INTEGER); $this->applyStatusCondition($query, $status, 'b.status'); return $query->execute()->fetchAll(PDO::FETCH_ASSOC); }
Loads all block data. @param int|string $blockId @param int $status @return array
public function loadCollectionReferencesData(Block $block, ?string $identifier = null): array { $query = $this->connection->createQueryBuilder(); $query->select('block_id', 'block_status', 'collection_id', 'collection_status', 'identifier') ->from('ngbm_block_collection') ->where( $query->expr()->eq('block_id', ':block_id') ) ->setParameter('block_id', $block->id, Type::INTEGER) ->orderBy('identifier', 'ASC'); $this->applyStatusCondition($query, $block->status, 'block_status'); if ($identifier !== null) { $query->andWhere($query->expr()->eq('identifier', ':identifier')) ->setParameter('identifier', $identifier, Type::STRING); } return $query->execute()->fetchAll(PDO::FETCH_ASSOC); }
Loads all collection reference data.
public function loadLayoutBlocksData(Layout $layout): array { $query = $this->getBlockSelectQuery(); $query->where( $query->expr()->eq('b.layout_id', ':layout_id') ) ->setParameter('layout_id', $layout->id, Type::INTEGER); $this->applyStatusCondition($query, $layout->status, 'b.status'); return $query->execute()->fetchAll(PDO::FETCH_ASSOC); }
Loads all layout block data.
public function loadZoneBlocksData(Zone $zone): array { $query = $this->getBlockSelectQuery(); $query->where( $query->expr()->like('b.path', ':path') ) ->setParameter('path', '%/' . $zone->rootBlockId . '/%', Type::STRING); $this->applyStatusCondition($query, $zone->status, 'b.status'); return $query->execute()->fetchAll(PDO::FETCH_ASSOC); }
Loads all zone block data.
public function loadChildBlocksData(Block $block, ?string $placeholder = null): array { $query = $this->getBlockSelectQuery(); $query->where( $query->expr()->eq('b.parent_id', ':parent_id') ) ->setParameter('parent_id', $block->id, Type::INTEGER) ->addOrderBy('b.placeholder', 'ASC') ->addOrderBy('b.position', 'ASC'); if ($placeholder !== null) { $query->andWhere( $query->expr()->eq('b.placeholder', ':placeholder') ) ->setParameter('placeholder', $placeholder, Type::STRING); } $this->applyStatusCondition($query, $block->status, 'b.status'); return $query->execute()->fetchAll(PDO::FETCH_ASSOC); }
Loads all child block data from specified block, optionally filtered by placeholder.
public function createBlockTranslation(Block $block, string $locale): void { $query = $this->connection->createQueryBuilder() ->insert('ngbm_block_translation') ->values( [ 'block_id' => ':block_id', 'status' => ':status', 'locale' => ':locale', 'parameters' => ':parameters', ] ) ->setParameter('block_id', $block->id, Type::INTEGER) ->setParameter('status', $block->status, Type::INTEGER) ->setParameter('locale', $locale, Type::STRING) ->setParameter('parameters', $block->parameters[$locale], Type::JSON_ARRAY); $query->execute(); }
Creates a block translation.
public function createCollectionReference(CollectionReference $collectionReference): void { $query = $this->connection->createQueryBuilder(); $query->insert('ngbm_block_collection') ->values( [ 'block_id' => ':block_id', 'block_status' => ':block_status', 'collection_id' => ':collection_id', 'collection_status' => ':collection_status', 'identifier' => ':identifier', ] ) ->setParameter('block_id', $collectionReference->blockId, Type::INTEGER) ->setParameter('block_status', $collectionReference->blockStatus, Type::INTEGER) ->setParameter('collection_id', $collectionReference->collectionId, Type::INTEGER) ->setParameter('collection_status', $collectionReference->collectionStatus, Type::INTEGER) ->setParameter('identifier', $collectionReference->identifier, Type::STRING); $query->execute(); }
Creates the collection reference.
public function updateBlock(Block $block): void { $query = $this->connection->createQueryBuilder(); $query ->update('ngbm_block') ->set('layout_id', ':layout_id') ->set('depth', ':depth') ->set('path', ':path') ->set('parent_id', ':parent_id') ->set('placeholder', ':placeholder') ->set('position', ':position') ->set('definition_identifier', ':definition_identifier') ->set('view_type', ':view_type') ->set('item_view_type', ':item_view_type') ->set('name', ':name') ->set('translatable', ':translatable') ->set('main_locale', ':main_locale') ->set('always_available', ':always_available') ->set('config', ':config') ->where( $query->expr()->eq('id', ':id') ) ->setParameter('id', $block->id, Type::INTEGER) ->setParameter('layout_id', $block->layoutId, Type::INTEGER) ->setParameter('depth', $block->depth, Type::STRING) ->setParameter('path', $block->path, Type::STRING) ->setParameter('parent_id', $block->parentId, Type::INTEGER) ->setParameter('placeholder', $block->placeholder, Type::STRING) ->setParameter('position', $block->position, Type::INTEGER) ->setParameter('definition_identifier', $block->definitionIdentifier, Type::STRING) ->setParameter('view_type', $block->viewType, Type::STRING) ->setParameter('item_view_type', $block->itemViewType, Type::STRING) ->setParameter('name', $block->name, Type::STRING) ->setParameter('translatable', $block->isTranslatable, Type::BOOLEAN) ->setParameter('main_locale', $block->mainLocale, Type::STRING) ->setParameter('always_available', $block->alwaysAvailable, Type::BOOLEAN) ->setParameter('config', $block->config, Type::JSON_ARRAY); $this->applyStatusCondition($query, $block->status); $query->execute(); }
Updates a block.
public function updateBlockTranslation(Block $block, string $locale): void { $query = $this->connection->createQueryBuilder(); $query ->update('ngbm_block_translation') ->set('parameters', ':parameters') ->where( $query->expr()->andX( $query->expr()->eq('block_id', ':block_id'), $query->expr()->eq('locale', ':locale') ) ) ->setParameter('block_id', $block->id, Type::INTEGER) ->setParameter('locale', $locale, Type::STRING) ->setParameter('parameters', $block->parameters[$locale], Type::JSON_ARRAY); $this->applyStatusCondition($query, $block->status); $query->execute(); }
Updates a block translation.
public function moveBlock(Block $block, Block $targetBlock, string $placeholder, int $position): void { $query = $this->connection->createQueryBuilder(); $query ->update('ngbm_block') ->set('position', ':position') ->set('parent_id', ':parent_id') ->set('placeholder', ':placeholder') ->where( $query->expr()->eq('id', ':id') ) ->setParameter('id', $block->id, Type::INTEGER) ->setParameter('position', $position, Type::INTEGER) ->setParameter('parent_id', $targetBlock->id, Type::INTEGER) ->setParameter('placeholder', $placeholder, Type::STRING); $this->applyStatusCondition($query, $block->status); $query->execute(); $depthDifference = $block->depth - ($targetBlock->depth + 1); $query = $this->connection->createQueryBuilder(); $query ->update('ngbm_block') ->set('layout_id', ':layout_id') ->set('depth', 'depth - :depth_difference') ->set('path', 'replace(path, :old_path, :new_path)') ->where( $query->expr()->like('path', ':path') ) ->setParameter('layout_id', $targetBlock->layoutId, Type::INTEGER) ->setParameter('depth_difference', $depthDifference, Type::INTEGER) ->setParameter('old_path', $block->path, Type::STRING) ->setParameter('new_path', $targetBlock->path . $block->id . '/', Type::STRING) ->setParameter('path', $block->path . '%', Type::STRING); $this->applyStatusCondition($query, $block->status); $query->execute(); }
Moves a block. If the target block is not provided, the block is only moved within its current parent ID and placeholder.
public function deleteCollectionReferences(array $blockIds, ?int $status = null): void { $query = $this->connection->createQueryBuilder(); $query->delete('ngbm_block_collection') ->where( $query->expr()->in('block_id', [':block_id']) ) ->setParameter('block_id', $blockIds, Connection::PARAM_INT_ARRAY); if ($status !== null) { $this->applyStatusCondition($query, $status, 'block_status', 'block_status'); } $query->execute(); }
Deletes the collection reference.
public function loadSubBlockIds($blockId, ?int $status = null): array { $query = $this->connection->createQueryBuilder(); $query->select('DISTINCT id') ->from('ngbm_block') ->where( $query->expr()->like('path', ':path') ) ->setParameter('path', '%/' . (int) $blockId . '/%', Type::STRING); if ($status !== null) { $this->applyStatusCondition($query, $status); } $result = $query->execute()->fetchAll(PDO::FETCH_ASSOC); return array_column($result, 'id'); }
Loads all sub block IDs. @param int|string $blockId @param int $status @return array
public function loadLayoutBlockIds($layoutId, ?int $status = null): array { $query = $this->connection->createQueryBuilder(); $query->select('DISTINCT id') ->from('ngbm_block') ->where( $query->expr()->eq('layout_id', ':layout_id') ) ->setParameter('layout_id', $layoutId, Type::INTEGER); if ($status !== null) { $this->applyStatusCondition($query, $status); } $result = $query->execute()->fetchAll(PDO::FETCH_ASSOC); return array_column($result, 'id'); }
Loads all layout block IDs. @param int|string $layoutId @param int $status @return array
public function loadBlockCollectionIds(array $blockIds, ?int $status = null): array { $query = $this->connection->createQueryBuilder(); $query->select('DISTINCT bc.collection_id') ->from('ngbm_block_collection', 'bc') ->where( $query->expr()->in('bc.block_id', [':block_id']) ) ->setParameter('block_id', $blockIds, Connection::PARAM_INT_ARRAY); if ($status !== null) { $this->applyStatusCondition($query, $status, 'bc.block_status', 'block_status'); } $result = $query->execute()->fetchAll(PDO::FETCH_ASSOC); return array_column($result, 'collection_id'); }
Loads all block collection IDs.
private function getStatusString(Value $value): string { switch ($value->getStatus()) { case Value::STATUS_DRAFT: return 'DRAFT'; case Value::STATUS_PUBLISHED: return 'PUBLISHED'; case Value::STATUS_ARCHIVED: return 'ARCHIVED'; } throw new RuntimeException(sprintf("Unknown status '%s'", var_export($value->getStatus(), true))); }
Return status string representation for the given $value. @throws \Netgen\BlockManager\Exception\RuntimeException If status is not recognized
private function buildViewValues(iterable $values, int $version): Generator { foreach ($values as $key => $value) { yield $key => new View($value, $version); } }
Builds the list of View objects for provided list of values.
public static function buildLayoutType(string $identifier, array $config): LayoutTypeInterface { $zones = []; foreach ($config['zones'] as $zoneIdentifier => $zoneConfig) { $zones[$zoneIdentifier] = Zone::fromArray( [ 'identifier' => $zoneIdentifier, 'name' => $zoneConfig['name'], 'allowedBlockDefinitions' => $zoneConfig['allowed_block_definitions'], ] ); } return LayoutType::fromArray( [ 'identifier' => $identifier, 'isEnabled' => $config['enabled'], 'name' => $config['name'], 'icon' => $config['icon'], 'zones' => $zones, ] ); }
Builds the layout type.
public function validateBlockCreateStruct(BlockCreateStruct $blockCreateStruct): void { $this->validate( $blockCreateStruct, [ new BlockCreateStructConstraint(), ] ); $this->validate( $blockCreateStruct, new ConfigAwareStructConstraint( [ 'payload' => $blockCreateStruct->getDefinition(), ] ) ); $collectionCreateStructs = $blockCreateStruct->getCollectionCreateStructs(); if (count($collectionCreateStructs) > 0) { foreach ($collectionCreateStructs as $collectionCreateStruct) { $this->collectionValidator->validateCollectionCreateStruct($collectionCreateStruct); } } }
Validates the provided block create struct. @throws \Netgen\BlockManager\Exception\Validation\ValidationException If the validation failed
public function validateBlockUpdateStruct(Block $block, BlockUpdateStruct $blockUpdateStruct): void { $this->validate( $blockUpdateStruct, [ new BlockUpdateStructConstraint( [ 'payload' => $block, ] ), ] ); $this->validate( $blockUpdateStruct, new ConfigAwareStructConstraint( [ 'payload' => $block->getDefinition(), 'allowMissingFields' => true, ] ) ); }
Validates the provided block update struct. @throws \Netgen\BlockManager\Exception\Validation\ValidationException If the validation failed
private function visitTargets(Rule $rule, VisitorInterface $subVisitor): Generator { foreach ($rule->getTargets() as $target) { yield $target->getId() => $subVisitor->visit($target); } }
Visit the given $rule targets into hash representation.
private function visitConditions(Rule $rule, VisitorInterface $subVisitor): Generator { foreach ($rule->getConditions() as $condition) { yield $condition->getId() => $subVisitor->visit($condition); } }
Visit the given $rule conditions into hash representation.
public function isValidQueryType(string $queryType): bool { if (!is_array($this->validQueryTypes)) { return true; } return in_array($queryType, $this->validQueryTypes, true); }
Returns if the provided query type is valid.
public function isValidItemType(string $itemType): bool { if (!is_array($this->validItemTypes)) { return true; } return in_array($itemType, $this->validItemTypes, true); }
Returns if the provided item type is valid.
public function newCollectionCreateStruct(?QueryCreateStruct $queryCreateStruct = null): CollectionCreateStruct { $struct = new CollectionCreateStruct(); $struct->queryCreateStruct = $queryCreateStruct; return $struct; }
Creates a new collection create struct.
public function newCollectionUpdateStruct(?Collection $collection = null): CollectionUpdateStruct { $collectionUpdateStruct = new CollectionUpdateStruct(); if ($collection !== null) { $collectionUpdateStruct->offset = $collection->getOffset(); $collectionUpdateStruct->limit = $collection->getLimit() ?? 0; } return $collectionUpdateStruct; }
Creates a new collection update struct. If collection is provided, initial data is copied from the collection.
public function newItemCreateStruct(ItemDefinitionInterface $itemDefinition, $value): ItemCreateStruct { $struct = new ItemCreateStruct(); $struct->definition = $itemDefinition; $struct->value = $value; return $struct; }
Creates a new item create struct from provided values. @param \Netgen\BlockManager\Collection\Item\ItemDefinitionInterface $itemDefinition @param int|string $value @return \Netgen\BlockManager\API\Values\Collection\ItemCreateStruct
public function newItemUpdateStruct(?Item $item = null): ItemUpdateStruct { $itemUpdateStruct = new ItemUpdateStruct(); if (!$item instanceof Item) { return $itemUpdateStruct; } $this->configStructBuilder->buildConfigUpdateStructs($item, $itemUpdateStruct); return $itemUpdateStruct; }
Creates a new item update struct. If item is provided, initial data is copied from the item.
public function newQueryUpdateStruct(string $locale, ?Query $query = null): QueryUpdateStruct { $queryUpdateStruct = new QueryUpdateStruct(); $queryUpdateStruct->locale = $locale; if (!$query instanceof Query) { return $queryUpdateStruct; } $queryUpdateStruct->fillParametersFromQuery($query); return $queryUpdateStruct; }
Creates a new query update struct for provided locale. If query is provided, initial data is copied from the query.
public function applyStatusCondition(QueryBuilder $query, ?int $status, string $statusColumn = 'status', string $paramName = 'status'): void { $query->andWhere($query->expr()->eq($statusColumn, ':' . $paramName)) ->setParameter($paramName, $status, Type::INTEGER); }
Applies status condition to the query.
public function applyOffsetAndLimit(QueryBuilder $query, ?int $offset, ?int $limit): void { $query->setFirstResult($offset ?? 0); if (is_int($limit) && $limit > 0) { $query->setMaxResults($limit); } }
Applies offset and limit to the query.
private function buildItems(LayoutList $layouts): Generator { foreach ($layouts as $layout) { yield $this->buildItem($layout); } }
Builds the items from provided layouts.
public function getBlockTypes(bool $onlyEnabled = false): array { if (!$onlyEnabled) { return $this->blockTypes; } return array_values( array_filter( $this->blockTypes, static function (BlockType $blockType): bool { return $blockType->isEnabled(); } ) ); }
Returns the block types in this group. @param bool $onlyEnabled @return \Netgen\BlockManager\Block\BlockType\BlockType[]
public function getCollectionRunner(Collection $collection, int $flags = 0): CollectionRunnerInterface { $collectionQuery = $collection->getQuery(); if ($collectionQuery instanceof Query) { $queryRunner = $this->getQueryRunner($collectionQuery, $flags); return new DynamicCollectionRunner($queryRunner, $this->visibilityResolver); } return new ManualCollectionRunner($this->visibilityResolver); }
Builds and returns the collection runner for provided collection.
private function getQueryRunner(Query $query, int $flags = 0): QueryRunnerInterface { $showContextualSlots = (bool) ($flags & ResultSet::INCLUDE_UNKNOWN_ITEMS); if ($showContextualSlots && $query->isContextual()) { return new ContextualQueryRunner(); } return new QueryRunner($this->cmsItemBuilder); }
Builds the query runner for the provided query based on provided flags.