code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
private function validateBrowserType(ContainerBuilder $container, string $valueType): void { if ($container->has(sprintf('netgen_content_browser.config.%s', $valueType))) { return; } throw new RuntimeException( sprintf( 'Netgen Content Browser backend for "%s" value type does not exist.', $valueType ) ); }
Validates that the provided Content Browser item type exists in the system.
public function getOption(string $option) { if (!$this->hasOption($option)) { throw ParameterException::noOption($option); } return $this->options[$option]; }
Returns the provided parameter option. @throws \Netgen\BlockManager\Exception\Parameters\ParameterException If option does not exist @return mixed
public function getParameterDefinition(string $parameterName): ParameterDefinition { if (!$this->hasParameterDefinition($parameterName)) { throw ParameterException::noParameterDefinition($parameterName); } return $this->parameterDefinitions[$parameterName]; }
Returns the parameter definition with provided name. @throws \Netgen\BlockManager\Exception\Parameters\ParameterException If the requested parameter definition does not exist
public static function createFromTimestamp(?int $timestamp = null, ?string $timeZone = null): DateTimeInterface { $dateTimeZone = is_string($timeZone) ? new DateTimeZone($timeZone) : null; $timestamp = is_int($timestamp) ? $timestamp : time(); $dateTime = new DateTimeImmutable('now', $dateTimeZone); return $dateTime->setTimestamp($timestamp); }
Creates a new \DateTimeImmutable instance from provided timestamp and timezone identifiers. Current timestamp and timezones are used if not provided.
public static function createFromArray(array $datetime): ?DateTimeInterface { $dateAndTime = $datetime['datetime'] ?? ''; $timeZone = $datetime['timezone'] ?? ''; if ($dateAndTime === '' || !is_string($dateAndTime)) { return null; } if ($timeZone === '' || !is_string($timeZone)) { return null; } return new DateTimeImmutable($dateAndTime, new DateTimeZone($timeZone)); }
Creates a new \DateTimeImmutable instance from provided array. The array needs to contain two keys with string values: 1) "datetime" - for date & time in one of the valid formats 2) "timezone" - a valid timezone identifier Returns null if provided array is not of valid format.
public static function isBetweenDates(?DateTimeInterface $date = null, ?DateTimeInterface $from = null, ?DateTimeInterface $to = null): bool { $date = $date ?? self::createFromTimestamp(); if ($from instanceof DateTimeInterface && $date < $from) { return false; } if ($to instanceof DateTimeInterface && $date > $to) { return false; } return true; }
Returns if the provided DateTime instance is between the provided dates.
public static function getTimeZoneList(): array { $timeZoneList = []; foreach (DateTimeZone::listIdentifiers() as $timeZone) { [$region, $name] = self::parseTimeZone($timeZone); $offset = self::buildOffsetString($timeZone); $name = sprintf('%s (%s)', str_replace('_', ' ', $name), $offset); $timeZoneList[$region][$name] = $timeZone; } return $timeZoneList; }
Returns the formatted list of all timezones, separated by regions.
private static function parseTimeZone(string $timeZone): array { $parts = explode('/', $timeZone); if (count($parts) > 2) { return [$parts[0], $parts[1] . ' / ' . $parts[2]]; } if (count($parts) > 1) { return [$parts[0], $parts[1]]; } return ['Other', $parts[0]]; }
Returns the array with human readable region and timezone name for the provided timezone identifier.
private static function buildOffsetString(string $timeZone): string { $offset = self::createFromTimestamp(null, $timeZone)->getOffset(); $hours = intdiv($offset, 3600); $minutes = intdiv($offset % 3600, 60); return sprintf('%s%02d:%02d', $offset >= 0 ? '+' : '-', abs($hours), abs($minutes)); }
Returns the formatted UTC offset for the provided timezone identifier in the form of (+/-)HH:mm.
public function getLayoutView() { $currentRequest = $this->requestStack->getCurrentRequest(); $masterRequest = $this->requestStack->getMasterRequest(); if (!$currentRequest instanceof Request || !$masterRequest instanceof Request) { return null; } if ($masterRequest->attributes->has('ngbmExceptionLayoutView')) { if ($currentRequest !== $masterRequest || !$masterRequest->attributes->has('ngbmLayoutView')) { return $masterRequest->attributes->get('ngbmExceptionLayoutView'); } } return $masterRequest->attributes->get('ngbmLayoutView'); }
Returns the currently resolved layout view. Since the regular Symfony exceptions are rendered only in sub-requests, we can return the resolved non-error layout for master requests even if the exception layout is resolved too (that might happen if an error or exception happened inside a user implemented sub-request, like rendering a block item). In other words, we return the resolved exception layout only in case of a sub-request (this case happens if an error/exception happens during the rendering of the page) or in case of a master request if non-error layout is NOT resolved (this case happens if an error/exception happens before the rendering of the page). All other cases receive the non-error layout if it exists. @return \Netgen\BlockManager\View\View\LayoutViewInterface|false|null
public function getLayout(): ?Layout { $layoutView = $this->getLayoutView(); if (!$layoutView instanceof LayoutViewInterface) { return null; } return $layoutView->getLayout(); }
Returns the currently resolved layout or null if no layout was resolved.
public function getRule(): ?Rule { $layoutView = $this->getLayoutView(); if (!$layoutView instanceof LayoutViewInterface) { return null; } return $layoutView->getParameter('rule'); }
Returns the rule used to resolve the current layout or null if no layout was resolved.
public function getPageLayoutTemplate(): string { $this->pageLayoutTemplate = $this->pageLayoutTemplate ?? $this->pageLayoutResolver->resolvePageLayout(); return $this->pageLayoutTemplate; }
Returns the pagelayout template.
public function getLayoutTemplate(string $context = ViewInterface::CONTEXT_DEFAULT): ?string { $layoutView = $this->buildLayoutView($context); if (!$layoutView instanceof LayoutViewInterface) { return $this->getPageLayoutTemplate(); } return $layoutView->getTemplate(); }
Returns the currently valid layout template, or base pagelayout if no layout was resolved.
private function buildLayoutView(string $context = ViewInterface::CONTEXT_DEFAULT) { $currentRequest = $this->requestStack->getCurrentRequest(); $masterRequest = $this->requestStack->getMasterRequest(); if (!$currentRequest instanceof Request || !$masterRequest instanceof Request) { return null; } if ($masterRequest->attributes->has('ngbmExceptionLayoutView')) { // After an exception layout is resolved, this case either means that // the main layout does not exist at all (because the error // happened before the rendering) or that it is already resolved // (if the error happened in subrequest), so this is a subsequent // call where we can safely return null in all cases. return null; } if ( !$currentRequest->attributes->has('exception') && $masterRequest->attributes->has('ngbmLayoutView') ) { // This is the case where we request the main layout more than once // within the regular page display, without the exception, so again // we return null. return null; } // Once we're here, we either request the main layout when there's no // exception, or the exception layout (both of those for the first time). $layoutView = false; $resolvedRule = $this->layoutResolver->resolveRule(); if ($resolvedRule instanceof Rule) { $layoutView = $this->viewBuilder->buildView( $resolvedRule->getLayout(), $context, [ 'rule' => $resolvedRule, ] ); } $masterRequest->attributes->set( $currentRequest->attributes->has('exception') ? 'ngbmExceptionLayoutView' : 'ngbmLayoutView', $layoutView ); return $layoutView; }
Resolves the used layout, based on current conditions. Only resolves and returns the layout view once per request for regular page, and once if an exception happens. Subsequent calls will simply return null. See class docs for more details. @return \Netgen\BlockManager\View\ViewInterface|false|null
public function newLayoutCreateStruct(LayoutTypeInterface $layoutType, string $name, string $mainLocale): LayoutCreateStruct { $struct = new LayoutCreateStruct(); $struct->layoutType = $layoutType; $struct->name = $name; $struct->mainLocale = $mainLocale; return $struct; }
Creates a new layout create struct from the provided values.
public function newLayoutUpdateStruct(?Layout $layout = null): LayoutUpdateStruct { $layoutUpdateStruct = new LayoutUpdateStruct(); if (!$layout instanceof Layout) { return $layoutUpdateStruct; } $layoutUpdateStruct->name = $layout->getName(); $layoutUpdateStruct->description = $layout->getDescription(); return $layoutUpdateStruct; }
Creates a new layout update struct. If the layout is provided, initial data is copied from the layout.
public function newLayoutCopyStruct(?Layout $layout = null): LayoutCopyStruct { $layoutCopyStruct = new LayoutCopyStruct(); if (!$layout instanceof Layout) { return $layoutCopyStruct; } $layoutCopyStruct->name = $layout->getName() . ' (copy)'; return $layoutCopyStruct; }
Creates a new layout copy struct. If the layout is provided, initial data is copied from the layout.
public function newTargetCreateStruct(string $type): TargetCreateStruct { $struct = new TargetCreateStruct(); $struct->type = $type; return $struct; }
Creates a new target create struct from the provided values.
public function newConditionCreateStruct(string $type): ConditionCreateStruct { $struct = new ConditionCreateStruct(); $struct->type = $type; return $struct; }
Creates a new condition create struct from the provided values.
private function disableUntranslatableForms(FormBuilderInterface $builder): void { foreach ($builder as $form) { /** @var \Symfony\Component\Form\FormBuilderInterface $form */ $innerType = $form->getType()->getInnerType(); $disabled = !$innerType instanceof ParametersType; $parameterDefinition = $form->getOption('ngbm_parameter_definition'); if ($parameterDefinition instanceof ParameterDefinition) { $disabled = $parameterDefinition->getOption('translatable') !== true; } $form->setDisabled($disabled); if ($parameterDefinition instanceof ParameterDefinition) { continue; } $this->disableUntranslatableForms($form); } }
Disables all inputs for parameters which are not translatable.
public function loadCollectionData($collectionId, int $status): array { $query = $this->getCollectionSelectQuery(); $query->where( $query->expr()->eq('c.id', ':id') ) ->setParameter('id', $collectionId, Type::INTEGER); $this->applyStatusCondition($query, $status, 'c.status'); return $query->execute()->fetchAll(PDO::FETCH_ASSOC); }
Loads all collection data for collection with specified ID. @param int|string $collectionId @param int $status @return array
public function loadItemData($itemId, int $status): array { $query = $this->getItemSelectQuery(); $query->where( $query->expr()->eq('id', ':id') ) ->setParameter('id', $itemId, Type::INTEGER); $this->applyStatusCondition($query, $status); return $query->execute()->fetchAll(PDO::FETCH_ASSOC); }
Loads all data for an item. @param int|string $itemId @param int $status @return array
public function loadItemWithPositionData(Collection $collection, int $position): array { $query = $this->getItemSelectQuery(); $query->where( $query->expr()->andX( $query->expr()->eq('collection_id', ':collection_id'), $query->expr()->eq('position', ':position') ) ) ->setParameter('collection_id', $collection->id, Type::INTEGER) ->setParameter('position', $position, Type::INTEGER); $this->applyStatusCondition($query, $collection->status); return $query->execute()->fetchAll(PDO::FETCH_ASSOC); }
Loads an item with specified position in specified collection.
public function loadQueryData($queryId, int $status): array { $query = $this->getQuerySelectQuery(); $query->where( $query->expr()->eq('q.id', ':id') ) ->setParameter('id', $queryId, Type::INTEGER); $this->applyStatusCondition($query, $status, 'q.status'); return $query->execute()->fetchAll(PDO::FETCH_ASSOC); }
Loads all data for a query. @param int|string $queryId @param int $status @return array
public function loadCollectionItemsData(Collection $collection): array { $query = $this->getItemSelectQuery(); $query->where( $query->expr()->eq('collection_id', ':collection_id') ) ->setParameter('collection_id', $collection->id, Type::INTEGER); $this->applyStatusCondition($query, $collection->status); $query->addOrderBy('position', 'ASC'); return $query->execute()->fetchAll(PDO::FETCH_ASSOC); }
Loads all data for items that belong to collection with specified ID.
public function loadCollectionQueryData(Collection $collection): array { $query = $this->getQuerySelectQuery(); $query->where( $query->expr()->eq('q.collection_id', ':collection_id') ) ->setParameter('collection_id', $collection->id, Type::INTEGER); $this->applyStatusCondition($query, $collection->status, 'q.status'); return $query->execute()->fetchAll(PDO::FETCH_ASSOC); }
Loads all data for queries that belong to collection with specified ID.
public function collectionExists($collectionId, int $status): bool { $query = $this->connection->createQueryBuilder(); $query->select('count(*) AS count') ->from('ngbm_collection') ->where( $query->expr()->eq('id', ':id') ) ->setParameter('id', $collectionId, Type::INTEGER); $this->applyStatusCondition($query, $status); $data = $query->execute()->fetchAll(PDO::FETCH_ASSOC); return (int) ($data[0]['count'] ?? 0) > 0; }
Returns if the collection exists. @param int|string $collectionId @param int $status @return bool
public function createCollection(Collection $collection): Collection { $query = $this->connection->createQueryBuilder() ->insert('ngbm_collection') ->values( [ 'id' => ':id', 'status' => ':status', 'start' => ':start', 'length' => ':length', 'translatable' => ':translatable', 'main_locale' => ':main_locale', 'always_available' => ':always_available', ] ) ->setValue( 'id', $collection->id !== null ? (int) $collection->id : $this->connectionHelper->getAutoIncrementValue('ngbm_collection') ) ->setParameter('status', $collection->status, Type::INTEGER) ->setParameter('start', $collection->offset, Type::INTEGER) ->setParameter('length', $collection->limit, Type::INTEGER) ->setParameter('translatable', $collection->isTranslatable, Type::BOOLEAN) ->setParameter('main_locale', $collection->mainLocale, Type::STRING) ->setParameter('always_available', $collection->alwaysAvailable, Type::BOOLEAN); $query->execute(); $collection->id = $collection->id ?? (int) $this->connectionHelper->lastInsertId('ngbm_collection'); return $collection; }
Creates a collection.
public function createCollectionTranslation(Collection $collection, string $locale): void { $query = $this->connection->createQueryBuilder() ->insert('ngbm_collection_translation') ->values( [ 'collection_id' => ':collection_id', 'status' => ':status', 'locale' => ':locale', ] ) ->setParameter('collection_id', $collection->id, Type::INTEGER) ->setParameter('status', $collection->status, Type::INTEGER) ->setParameter('locale', $locale, Type::STRING); $query->execute(); }
Creates a collection translation.
public function updateCollection(Collection $collection): void { $query = $this->connection->createQueryBuilder(); $query ->update('ngbm_collection') ->set('start', ':start') ->set('length', ':length') ->set('translatable', ':translatable') ->set('main_locale', ':main_locale') ->set('always_available', ':always_available') ->where( $query->expr()->eq('id', ':id') ) ->setParameter('id', $collection->id, Type::INTEGER) ->setParameter('start', $collection->offset, Type::INTEGER) ->setParameter('length', $collection->limit, Type::INTEGER) ->setParameter('translatable', $collection->isTranslatable, Type::BOOLEAN) ->setParameter('main_locale', $collection->mainLocale, Type::STRING) ->setParameter('always_available', $collection->alwaysAvailable, Type::BOOLEAN); $this->applyStatusCondition($query, $collection->status); $query->execute(); }
Updates a collection.
public function deleteCollection($collectionId, ?int $status = null): void { // Delete all connections between blocks and collections $query = $this->connection->createQueryBuilder(); $query ->delete('ngbm_block_collection') ->where( $query->expr()->eq('collection_id', ':collection_id') ) ->setParameter('collection_id', $collectionId, Type::INTEGER); if ($status !== null) { $this->applyStatusCondition($query, $status, 'collection_status'); } $query->execute(); // Then delete the collection itself $query = $this->connection->createQueryBuilder(); $query->delete('ngbm_collection') ->where( $query->expr()->eq('id', ':id') ) ->setParameter('id', $collectionId, Type::INTEGER); if ($status !== null) { $this->applyStatusCondition($query, $status); } $query->execute(); }
Deletes a collection. @param int|string $collectionId @param int $status
public function deleteCollectionTranslations($collectionId, ?int $status = null, ?string $locale = null): void { $query = $this->connection->createQueryBuilder(); $query->delete('ngbm_collection_translation') ->where( $query->expr()->eq('collection_id', ':collection_id') ) ->setParameter('collection_id', $collectionId, Type::INTEGER); if ($status !== null) { $this->applyStatusCondition($query, $status); } if ($locale !== null) { $query ->andWhere($query->expr()->eq('locale', ':locale')) ->setParameter(':locale', $locale, Type::STRING); } $query->execute(); }
Deletes collection translations. @param int|string $collectionId @param int $status @param string $locale
public function addItem(Item $item): Item { $query = $this->connection->createQueryBuilder() ->insert('ngbm_collection_item') ->values( [ 'id' => ':id', 'status' => ':status', 'collection_id' => ':collection_id', 'position' => ':position', 'value' => ':value', 'value_type' => ':value_type', 'config' => ':config', ] ) ->setValue( 'id', $item->id !== null ? (int) $item->id : $this->connectionHelper->getAutoIncrementValue('ngbm_collection_item') ) ->setParameter('status', $item->status, Type::INTEGER) ->setParameter('collection_id', $item->collectionId, Type::INTEGER) ->setParameter('position', $item->position, Type::INTEGER) ->setParameter('value', $item->value, Type::STRING) ->setParameter('value_type', $item->valueType, Type::STRING) ->setParameter('config', $item->config, Type::JSON_ARRAY); $query->execute(); $item->id = $item->id ?? (int) $this->connectionHelper->lastInsertId('ngbm_collection_item'); return $item; }
Adds an item.
public function updateItem(Item $item): void { $query = $this->connection->createQueryBuilder(); $query ->update('ngbm_collection_item') ->set('collection_id', ':collection_id') ->set('position', ':position') ->set('value', ':value') ->set('value_type', ':value_type') ->set('config', ':config') ->where( $query->expr()->eq('id', ':id') ) ->setParameter('id', $item->id, Type::INTEGER) ->setParameter('collection_id', $item->collectionId, Type::INTEGER) ->setParameter('position', $item->position, Type::INTEGER) ->setParameter('value', $item->value, Type::STRING) ->setParameter('value_type', $item->valueType, Type::STRING) ->setParameter('config', $item->config, Type::JSON_ARRAY); $this->applyStatusCondition($query, $item->status); $query->execute(); }
Updates an item.
public function createQuery(Query $query): Query { $dbQuery = $this->connection->createQueryBuilder() ->insert('ngbm_collection_query') ->values( [ 'id' => ':id', 'status' => ':status', 'collection_id' => ':collection_id', 'type' => ':type', ] ) ->setValue( 'id', $query->id !== null ? (int) $query->id : $this->connectionHelper->getAutoIncrementValue('ngbm_collection_query') ) ->setParameter('status', $query->status, Type::INTEGER) ->setParameter('collection_id', $query->collectionId, Type::INTEGER) ->setParameter('type', $query->type, Type::STRING); $dbQuery->execute(); $query->id = $query->id ?? (int) $this->connectionHelper->lastInsertId('ngbm_collection_query'); return $query; }
Creates a query.
public function createQueryTranslation(Query $query, string $locale): void { $dbQuery = $this->connection->createQueryBuilder() ->insert('ngbm_collection_query_translation') ->values( [ 'query_id' => ':query_id', 'status' => ':status', 'locale' => ':locale', 'parameters' => ':parameters', ] ) ->setParameter('query_id', $query->id, Type::INTEGER) ->setParameter('status', $query->status, Type::INTEGER) ->setParameter('locale', $locale, Type::STRING) ->setParameter('parameters', $query->parameters[$locale], Type::JSON_ARRAY); $dbQuery->execute(); }
Creates a query translation.
public function updateQueryTranslation(Query $query, string $locale): void { $dbQuery = $this->connection->createQueryBuilder(); $dbQuery ->update('ngbm_collection_query_translation') ->set('parameters', ':parameters') ->where( $dbQuery->expr()->andX( $dbQuery->expr()->eq('query_id', ':query_id'), $dbQuery->expr()->eq('locale', ':locale') ) ) ->setParameter('query_id', $query->id, Type::INTEGER) ->setParameter('locale', $locale, Type::STRING) ->setParameter('parameters', $query->parameters[$locale], Type::JSON_ARRAY); $this->applyStatusCondition($dbQuery, $query->status); $dbQuery->execute(); }
Updates a query translation.
public function deleteQueryTranslations(array $queryIds, ?int $status = null, ?string $locale = null): void { $query = $this->connection->createQueryBuilder(); $query->delete('ngbm_collection_query_translation') ->where( $query->expr()->in('query_id', [':query_id']) ) ->setParameter('query_id', $queryIds, Connection::PARAM_INT_ARRAY); if ($status !== null) { $this->applyStatusCondition($query, $status); } if ($locale !== null) { $query ->andWhere($query->expr()->eq('locale', ':locale')) ->setParameter(':locale', $locale, Type::STRING); } $query->execute(); }
Deletes the query translations with provided query IDs.
private function getItemSelectQuery(): QueryBuilder { $query = $this->connection->createQueryBuilder(); $query->select('DISTINCT ngbm_collection_item.*') ->from('ngbm_collection_item'); return $query; }
Builds and returns an item database SELECT query.
private function getQuerySelectQuery(): QueryBuilder { $query = $this->connection->createQueryBuilder(); $query->select('DISTINCT q.*, qt.*') ->from('ngbm_collection_query', 'q') ->innerJoin( 'q', 'ngbm_collection_query_translation', 'qt', $query->expr()->andX( $query->expr()->eq('qt.query_id', 'q.id'), $query->expr()->eq('qt.status', 'q.status') ) ); return $query; }
Builds and returns a block database SELECT query.
public function mapRules(array $data): array { $rules = []; foreach ($data as $dataItem) { $rules[] = Rule::fromArray( [ 'id' => (int) $dataItem['id'], 'status' => (int) $dataItem['status'], 'layoutId' => $dataItem['layout_id'] !== null ? (int) $dataItem['layout_id'] : null, 'enabled' => (bool) $dataItem['enabled'], 'priority' => (int) $dataItem['priority'], 'comment' => $dataItem['comment'], ] ); } return $rules; }
Maps data from database to rule values. @return \Netgen\BlockManager\Persistence\Values\LayoutResolver\Rule[]
public function mapTargets(array $data): array { $targets = []; foreach ($data as $dataItem) { $targets[] = Target::fromArray( [ 'id' => (int) $dataItem['id'], 'status' => (int) $dataItem['status'], 'ruleId' => (int) $dataItem['rule_id'], 'type' => $dataItem['type'], 'value' => $dataItem['value'], ] ); } return $targets; }
Maps data from database to target values. @return \Netgen\BlockManager\Persistence\Values\LayoutResolver\Target[]
public function mapConditions(array $data): array { $conditions = []; foreach ($data as $dataItem) { $conditions[] = Condition::fromArray( [ 'id' => (int) $dataItem['id'], 'status' => (int) $dataItem['status'], 'ruleId' => (int) $dataItem['rule_id'], 'type' => $dataItem['type'], 'value' => json_decode($dataItem['value'], true), ] ); } return $conditions; }
Maps data from database to condition values. @return \Netgen\BlockManager\Persistence\Values\LayoutResolver\Condition[]
public static function buildBlockType(string $identifier, array $config, BlockDefinitionInterface $blockDefinition): BlockType { return BlockType::fromArray( [ 'identifier' => $identifier, 'isEnabled' => $config['enabled'], 'name' => $config['name'], 'icon' => $config['icon'], 'definition' => $blockDefinition, 'defaults' => $config['defaults'], ] ); }
Builds the block type.
public function buildBlockDefinition( string $identifier, BlockDefinitionHandlerInterface $handler, array $config, array $configDefinitionHandlers ): BlockDefinitionInterface { $commonData = $this->getCommonBlockDefinitionData( $identifier, $handler, $config, $configDefinitionHandlers ); return BlockDefinition::fromArray($commonData); }
Builds the block definition. @param string $identifier @param \Netgen\BlockManager\Block\BlockDefinition\BlockDefinitionHandlerInterface $handler @param array<string, mixed> $config @param \Netgen\BlockManager\Config\ConfigDefinitionHandlerInterface[] $configDefinitionHandlers @return \Netgen\BlockManager\Block\BlockDefinitionInterface
public function buildTwigBlockDefinition( string $identifier, TwigBlockDefinitionHandlerInterface $handler, array $config, array $configDefinitionHandlers ): TwigBlockDefinitionInterface { $commonData = $this->getCommonBlockDefinitionData( $identifier, $handler, $config, $configDefinitionHandlers ); return TwigBlockDefinition::fromArray($commonData); }
Builds the block definition. @param string $identifier @param \Netgen\BlockManager\Block\BlockDefinition\TwigBlockDefinitionHandlerInterface $handler @param array<string, mixed> $config @param \Netgen\BlockManager\Config\ConfigDefinitionHandlerInterface[] $configDefinitionHandlers @return \Netgen\BlockManager\Block\TwigBlockDefinitionInterface
public function buildContainerDefinition( string $identifier, ContainerDefinitionHandlerInterface $handler, array $config, array $configDefinitionHandlers ): ContainerDefinitionInterface { $commonData = $this->getCommonBlockDefinitionData( $identifier, $handler, $config, $configDefinitionHandlers ); return ContainerDefinition::fromArray($commonData); }
Builds the container definition. @param string $identifier @param \Netgen\BlockManager\Block\BlockDefinition\ContainerDefinitionHandlerInterface $handler @param array<string, mixed> $config @param \Netgen\BlockManager\Config\ConfigDefinitionHandlerInterface[] $configDefinitionHandlers @return \Netgen\BlockManager\Block\ContainerDefinitionInterface
private function getCommonBlockDefinitionData( string $identifier, BlockDefinitionHandlerInterface $handler, array $config, array $configDefinitionHandlers ): array { $parameterBuilder = $this->parameterBuilderFactory->createParameterBuilder(); $handler->buildParameters($parameterBuilder); $handlerPlugins = $this->handlerPluginRegistry->getPlugins(get_class($handler)); foreach ($handlerPlugins as $handlerPlugin) { $handlerPlugin->buildParameters($parameterBuilder); } $parameterDefinitions = $parameterBuilder->buildParameterDefinitions(); $configDefinitions = []; foreach ($configDefinitionHandlers as $configKey => $configDefinitionHandler) { $configDefinitions[$configKey] = $this->configDefinitionFactory->buildConfigDefinition( $configKey, $configDefinitionHandler ); } return [ 'identifier' => $identifier, 'handler' => $handler, 'handlerPlugins' => $handlerPlugins, 'parameterDefinitions' => $parameterDefinitions, 'configDefinitions' => $configDefinitions, ] + $this->processConfig($identifier, $config); }
Returns the data common to all block definition types. @param string $identifier @param \Netgen\BlockManager\Block\BlockDefinition\BlockDefinitionHandlerInterface $handler @param array<string, mixed> $config @param \Netgen\BlockManager\Config\ConfigDefinitionHandlerInterface[] $configDefinitionHandlers @return array<string, mixed>
private function buildErrorCodes(): array { if (count($this->statusCodes) === 0) { foreach (Response::$statusTexts as $statusCode => $statusText) { if ($statusCode >= 400 && $statusCode < 600) { $this->statusCodes[sprintf('%d (%s)', $statusCode, $statusText)] = $statusCode; } } } return $this->statusCodes; }
Builds the formatted list of all available error codes (those which are in 4xx and 5xx range).
private function compileContextNode(Compiler $compiler): void { $contextNode = null; if ($this->hasNode('context')) { $contextNode = $this->getNode('context'); } if ($contextNode instanceof Node) { $compiler ->write('$ngbmContext = ') ->subcompile($this->getNode('context')) ->write(';' . PHP_EOL); return; } $compiler->write('$ngbmContext = ' . ViewInterface::class . '::CONTEXT_DEFAULT;' . PHP_EOL); }
Compiles the context node.
public function renderCollectionPager(Pagerfanta $pagerfanta, Block $block, string $collectionIdentifier, array $options = []): string { $options['block'] = $block; $options['collection_identifier'] = $collectionIdentifier; return $this->pagerfantaView->render($pagerfanta, $this->routeGenerator, $options); }
Renders the provided Pagerfanta view.
public function getCollectionPageUrl(Pagerfanta $pagerfanta, Block $block, string $collectionIdentifier, int $page = 1): string { if ($page < 1 || $page > $pagerfanta->getNbPages()) { throw new InvalidArgumentException( 'page', sprintf('Page %d is out of bounds', $page) ); } return call_user_func($this->routeGenerator, $block, $collectionIdentifier, $page); }
Returns the URL of the provided pager and page number.
public function visit($value, ?VisitorInterface $subVisitor = null) { if ($subVisitor === null) { throw new RuntimeException('Implementation requires sub-visitor'); } return array_map( static function (Parameter $parameter) use ($subVisitor) { return $subVisitor->visit($parameter); }, $value->getParameters() ); }
@param \Netgen\BlockManager\API\Values\Config\Config $value @param \Netgen\BlockManager\Transfer\Output\VisitorInterface|null $subVisitor @return mixed
private function hasLayouts(): bool { $queryBuilder = $this->connection->createQueryBuilder(); $queryBuilder->select('COUNT(id) as count') ->from('ngbm_layout'); $result = $queryBuilder->execute()->fetchAll(PDO::FETCH_ASSOC); return (int) $result[0]['count'] > 0; }
Returns if the database already contains some layouts.
private function askDefaultLocale(): string { $io = new SymfonyStyle(new ArgvInput(), new ConsoleOutput()); return $io->ask( 'Please input the default locale for existing layouts', '', static function (string $locale): string { if (!Locales::exists($locale)) { throw new RuntimeException('Specified locale is not valid'); } return $locale; } ); }
Asks the user for default layout locale and returns it.
public function offsetGet($offset) { if (!$this->offsetExists($offset)) { return null; } if (!is_callable($this->dynamicParameters[$offset])) { return $this->dynamicParameters[$offset]; } return $this->dynamicParameters[$offset](); }
@param mixed $offset @return mixed
public static function buildBlockTypeGroup(string $identifier, array $config, array $blockTypes): BlockTypeGroup { return BlockTypeGroup::fromArray( [ 'identifier' => $identifier, 'isEnabled' => $config['enabled'], 'name' => $config['name'], 'blockTypes' => $blockTypes, ] ); }
Builds the block type group. @param string $identifier @param array<string, mixed> $config @param \Netgen\BlockManager\Block\BlockType\BlockType[] $blockTypes @return \Netgen\BlockManager\Block\BlockType\BlockTypeGroup
public function mapRule(PersistenceRule $rule): Rule { $ruleData = [ 'id' => $rule->id, 'status' => $rule->status, 'layout' => function () use ($rule): ?Layout { try { // Layouts used by rule are always in published status return $rule->layoutId !== null ? $this->layoutService->loadLayout($rule->layoutId) : null; } catch (NotFoundException $e) { return null; } }, 'enabled' => $rule->enabled, 'priority' => $rule->priority, 'comment' => $rule->comment, 'targets' => new LazyCollection( function () use ($rule): array { return array_map( function (PersistenceTarget $target): Target { return $this->mapTarget($target); }, $this->layoutResolverHandler->loadRuleTargets($rule) ); } ), 'conditions' => new LazyCollection( function () use ($rule): array { return array_map( function (PersistenceCondition $condition): Condition { return $this->mapCondition($condition); }, $this->layoutResolverHandler->loadRuleConditions($rule) ); } ), ]; return Rule::fromArray($ruleData); }
Builds the API rule value from persistence one.
public function mapTarget(PersistenceTarget $target): Target { try { $targetType = $this->targetTypeRegistry->getTargetType( $target->type ); } catch (TargetTypeException $e) { $targetType = new NullTargetType(); } $targetData = [ 'id' => $target->id, 'status' => $target->status, 'ruleId' => $target->ruleId, 'targetType' => $targetType, 'value' => $target->value, ]; return Target::fromArray($targetData); }
Builds the API target value from persistence one.
public function mapCondition(PersistenceCondition $condition): Condition { try { $conditionType = $this->conditionTypeRegistry->getConditionType( $condition->type ); } catch (ConditionTypeException $e) { $conditionType = new NullConditionType(); } $conditionData = [ 'id' => $condition->id, 'status' => $condition->status, 'ruleId' => $condition->ruleId, 'conditionType' => $conditionType, 'value' => $condition->value, ]; return Condition::fromArray($conditionData); }
Builds the API condition value from persistence one.
protected function updateRules(ContainerBuilder $container, ?array $allRules): array { $allRules = is_array($allRules) ? $allRules : []; $defaultTemplates = $container->getParameter('netgen_block_manager.default_view_templates'); foreach ($defaultTemplates as $viewName => $viewTemplates) { foreach ($viewTemplates as $context => $template) { $rules = []; if (isset($allRules[$viewName][$context]) && is_array($allRules[$viewName][$context])) { $rules = $allRules[$viewName][$context]; } $rules = $this->addDefaultRule($viewName, $context, $rules, $template); $allRules[$viewName][$context] = $rules; } } return $allRules; }
Updates all view rules to add the default template match.
protected function addDefaultRule(string $viewName, string $context, array $rules, string $defaultTemplate): array { $rules += [ "___{$viewName}_{$context}_default___" => [ 'template' => $defaultTemplate, 'match' => [], 'parameters' => [], ], ]; return $rules; }
Adds the default view template as a fallback to specified view rules.
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) { return; } $exceptionClass = null; foreach ($this->exceptionMap as $sourceException => $targetException) { if (is_a($exception, $sourceException, true)) { $exceptionClass = $targetException; break; } } if ($exceptionClass !== null) { $convertedException = new $exceptionClass( $exception->getMessage(), $exception, $exception->getCode() ); $event->setException($convertedException); } }
Converts exceptions to Symfony HTTP exceptions.
public function onKernelRequest(GetResponseEvent $event): void { if (!$event->isMasterRequest()) { return; } $request = $event->getRequest(); if ($request->attributes->get(SetIsAdminRequestListener::ADMIN_FLAG_NAME) !== true) { return; } if ($this->csrfTokenValidator->validateCsrfToken($request, $this->csrfTokenId)) { return; } throw new AccessDeniedHttpException('Missing or invalid CSRF token'); }
Validates if the current request has a valid token. @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException if no valid token exists
public function getPlaceholder(string $identifier): APIPlaceholder { if ($this->hasPlaceholder($identifier)) { return $this->placeholders[$identifier]; } throw BlockException::noPlaceholder($identifier); }
Returns the specified placeholder. @throws \Netgen\BlockManager\Exception\API\BlockException If the placeholder does not exist
public function getCollection(string $identifier): Collection { if (!$this->hasCollection($identifier)) { throw BlockException::noCollection($identifier); } return $this->collections->get($identifier); }
Returns the specified block collection. @throws \Netgen\BlockManager\Exception\API\BlockException If the block collection does not exist
public function hasDynamicParameter(string $parameter): bool { $this->buildDynamicParameters(); return $this->dynamicParameters->offsetExists($parameter); }
Returns if the object has a specified dynamic parameter.
private function buildDynamicParameters(): void { $this->dynamicParameters = $this->dynamicParameters ?? $this->definition->getDynamicParameters($this); }
Builds the dynamic parameters of the block from the block definition.
private function loadCollections(PersistenceBlock $block): Generator { $collectionReferences = $this->blockHandler->loadCollectionReferences($block); foreach ($collectionReferences as $collectionReference) { yield $collectionReference->identifier => $this->collectionHandler->loadCollection( $collectionReference->collectionId, $collectionReference->collectionStatus ); } }
Loads all persistence collections belonging to the provided block.
private function mapPlaceholders(PersistenceBlock $block, BlockDefinitionInterface $blockDefinition, ?array $locales = null): Generator { if (!$blockDefinition instanceof ContainerDefinitionInterface) { return; } foreach ($blockDefinition->getPlaceholders() as $placeholderIdentifier) { yield $placeholderIdentifier => Placeholder::fromArray( [ 'identifier' => $placeholderIdentifier, 'blocks' => new LazyCollection( function () use ($block, $placeholderIdentifier, $locales): array { return array_map( function (PersistenceBlock $childBlock) use ($locales): Block { return $this->mapBlock($childBlock, $locales, false); }, $this->blockHandler->loadChildBlocks($block, $placeholderIdentifier) ); } ), ] ); } }
Maps the placeholder from persistence parameters.
public function getParameterValue(string $parameterName) { if (!$this->hasParameterValue($parameterName)) { return null; } return $this->parameterValues[$parameterName]; }
Returns the parameter value with provided name or null if parameter does not exist. @return mixed
private function fillDefault(ParameterDefinitionCollectionInterface $definitionCollection): void { foreach ($definitionCollection->getParameterDefinitions() as $name => $definition) { $this->setParameterValue($name, $definition->getDefaultValue()); if ($definition instanceof CompoundParameterDefinition) { $this->fillDefault($definition); } } }
Fills the struct with the default parameter values as defined in provided parameter definition collection.
private function fillFromCollection( ParameterDefinitionCollectionInterface $definitionCollection, ParameterCollectionInterface $parameters ): void { foreach ($definitionCollection->getParameterDefinitions() as $name => $definition) { $value = null; if ($parameters->hasParameter($name)) { $parameter = $parameters->getParameter($name); if ($parameter->getParameterDefinition()->getType()::getIdentifier() === $definition->getType()::getIdentifier()) { $value = $parameter->getValue(); $value = is_object($value) ? clone $value : $value; } } $this->setParameterValue($name, $value); if ($definition instanceof CompoundParameterDefinition) { $this->fillFromCollection($definition, $parameters); } } }
Fills the struct values based on provided parameter collection.
private function fillFromHash( ParameterDefinitionCollectionInterface $definitionCollection, array $values, bool $doImport = false ): void { foreach ($definitionCollection->getParameterDefinitions() as $name => $definition) { $value = $definition->getDefaultValue(); $parameterType = $definition->getType(); if (array_key_exists($name, $values)) { $value = $doImport ? $parameterType->import($definition, $values[$name]) : $parameterType->fromHash($definition, $values[$name]); } $this->setParameterValue($name, $value); if ($definition instanceof CompoundParameterDefinition) { $this->fillFromHash($definition, $values, $doImport); } } }
Fills the struct 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 definition collection 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 getItemViewType(string $itemViewType): ItemViewType { if (!$this->hasItemViewType($itemViewType)) { throw BlockDefinitionException::noItemViewType($this->identifier, $itemViewType); } return $this->itemViewTypes[$itemViewType]; }
Returns the item view type with provided identifier. @throws \Netgen\BlockManager\Exception\Block\BlockDefinitionException If item view type does not exist
public function renderPlugins(array $context, string $pluginName): string { try { return $this->pluginRenderer->renderPlugins( $pluginName, $context ); } catch (Throwable $t) { $this->errorHandler->handleError($t); } return ''; }
Renders all the template plugins with provided name.
public function onKernelRequest(GetResponseEvent $event): void { if (!$event->isMasterRequest()) { return; } $request = $event->getRequest(); if ($request->attributes->get(SetIsApiRequestListener::API_FLAG_NAME) !== true) { return; } if ($this->csrfTokenValidator->validateCsrfToken($request, $this->csrfTokenId)) { return; } throw new AccessDeniedHttpException('Missing or invalid CSRF token'); }
Validates if the current request has a valid token. @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException if no valid token exists
public function buildConfigDefinition( string $configKey, ConfigDefinitionHandlerInterface $handler ): ConfigDefinitionInterface { $parameterBuilder = $this->parameterBuilderFactory->createParameterBuilder(); $handler->buildParameters($parameterBuilder); $parameterDefinitions = $parameterBuilder->buildParameterDefinitions(); return ConfigDefinition::fromArray( [ 'configKey' => $configKey, 'handler' => $handler, 'parameterDefinitions' => $parameterDefinitions, ] ); }
Builds the config definition.
public function getParameter(string $parameterName): Parameter { if (!$this->hasParameter($parameterName)) { throw ParameterException::noParameter($parameterName); } return $this->parameters[$parameterName]; }
Returns the parameter with provided name. @throws \Netgen\BlockManager\Exception\Parameters\ParameterException If the requested parameter does not exist
private function logError(Throwable $throwable, ?string $message = null, array $context = []): void { $context['error'] = $throwable; $this->logger->critical($message ?? $throwable->getMessage(), $context); }
Logs the error.
public function visit($value, ?VisitorInterface $subVisitor = null) { return [ 'id' => $value->getId(), 'type' => $value->getConditionType()::getType(), 'value' => $value->getValue(), ]; }
@param \Netgen\BlockManager\API\Values\LayoutResolver\Condition $value @param \Netgen\BlockManager\Transfer\Output\VisitorInterface|null $subVisitor @return mixed
public function getConfig(string $configKey): APIConfig { if ($this->hasConfig($configKey)) { return $this->configs[$configKey]; } throw ConfigException::noConfig($configKey); }
Returns the config with specified config key. @throws \Netgen\BlockManager\Exception\API\ConfigException If the config does not exist
private function loadLayouts(array $layoutIds): Generator { foreach ($layoutIds as $layoutId) { try { yield $this->layoutService->loadLayout($layoutId); } catch (NotFoundException $e) { continue; } } }
Loads the layouts for provided IDs.
private function loadRules(array $ruleIds): Generator { foreach ($ruleIds as $ruleId) { try { yield $this->layoutResolverService->loadRule($ruleId); } catch (NotFoundException $e) { continue; } } }
Loads the rules for provided IDs.
public function onKernelRequest(GetResponseEvent $event): void { if (!$event->isMasterRequest()) { return; } $request = $event->getRequest(); if ($request->attributes->has('ngbmContext')) { $context = $request->attributes->get('ngbmContext'); $context = is_array($context) ? $context : []; $this->context->add($context); return; } if ($request->query->has('ngbmContext')) { $this->context->add($this->getUriContext($request)); return; } $this->contextBuilder->buildContext($this->context); }
Builds the context object. If the context is available in query parameters and the URI signature is valid, it will be used, otherwise, provided builder will be used.
private function getUriContext(Request $request): array { $context = $request->query->get('ngbmContext'); $context = is_array($context) ? $context : []; if (!$this->uriSigner->check($this->getUri($request))) { return []; } return $context; }
Validates and returns the array with context information filled from the URI.
private function getUri(Request $request): string { if ($request->attributes->has('ngbmContextUri')) { return $request->attributes->get('ngbmContextUri'); } return $request->getRequestUri(); }
Returns the URI with the context from the request. This allows overriding the URI with a value stored in request attributes if, for example, there's need to pre-process the URI before checking the signature.
protected function validate($value, $constraints, ?string $propertyPath = null): void { try { $violations = $this->validator->validate($value, $constraints); } catch (Throwable $t) { throw ValidationException::validationFailed($propertyPath ?? '', $t->getMessage(), $t); } if (count($violations) === 0) { return; } $propertyName = $violations[0]->getPropertyPath() ?? ''; if ($propertyName === '') { $propertyName = $propertyPath ?? ''; } throw ValidationException::validationFailed($propertyName, $violations[0]->getMessage()); }
Validates the value against a set of provided constraints. @param mixed $value @param \Symfony\Component\Validator\Constraint|\Symfony\Component\Validator\Constraint[] $constraints @param string $propertyPath @throws \Netgen\BlockManager\Exception\Validation\ValidationException If the validation failed
public function getConfigDefinition(string $configKey): ConfigDefinitionInterface { if (!$this->hasConfigDefinition($configKey)) { throw ConfigDefinitionException::noConfigDefinition($configKey); } return $this->configDefinitions[$configKey]; }
Returns the config definition with provided config key. @throws \Netgen\BlockManager\Exception\Config\ConfigDefinitionException if config definition does not exist
public function visit($value, ?VisitorInterface $subVisitor = null) { if ($subVisitor === null) { throw new RuntimeException('Implementation requires sub-visitor'); } return [ 'id' => $value->getId(), 'definition_identifier' => $value->getDefinition()->getIdentifier(), 'is_translatable' => $value->isTranslatable(), 'is_always_available' => $value->isAlwaysAvailable(), 'main_locale' => $value->getMainLocale(), 'available_locales' => $value->getAvailableLocales(), 'view_type' => $value->getViewType(), 'item_view_type' => $value->getItemViewType(), 'name' => $value->getName(), 'placeholders' => iterator_to_array($this->visitPlaceholders($value, $subVisitor)), 'parameters' => $this->visitParameters($value, $subVisitor), 'configuration' => iterator_to_array($this->visitConfiguration($value, $subVisitor)), 'collections' => iterator_to_array($this->visitCollections($value, $subVisitor)), ]; }
@param \Netgen\BlockManager\API\Values\Block\Block $value @param \Netgen\BlockManager\Transfer\Output\VisitorInterface|null $subVisitor @return mixed
private function visitPlaceholders(Block $block, VisitorInterface $subVisitor): Generator { foreach ($block->getPlaceholders() as $placeholder) { yield $placeholder->getIdentifier() => $subVisitor->visit($placeholder); } }
Visit the given $block placeholders into hash representation.
private function visitParameters(Block $block, VisitorInterface $subVisitor): array { $parametersByLanguage = [ $block->getLocale() => iterator_to_array( $this->visitTranslationParameters($block, $subVisitor) ), ]; foreach ($block->getAvailableLocales() as $availableLocale) { if ($availableLocale === $block->getLocale()) { continue; } $translatedBlock = $this->blockService->loadBlock( $block->getId(), [$availableLocale], false ); $parametersByLanguage[$availableLocale] = iterator_to_array( $this->visitTranslationParameters( $translatedBlock, $subVisitor ) ); } ksort($parametersByLanguage); return $parametersByLanguage; }
Visit the given $block parameters into hash representation.
private function visitTranslationParameters(Block $block, VisitorInterface $subVisitor): Generator { foreach ($block->getParameters() as $parameter) { yield $parameter->getName() => $subVisitor->visit($parameter); } }
Return parameters for the given $block.
private function visitConfiguration(Block $block, VisitorInterface $subVisitor): Generator { foreach ($block->getConfigs() as $config) { yield $config->getConfigKey() => $subVisitor->visit($config); } }
Visit the given $block configuration into hash representation.
private function visitCollections(Block $block, VisitorInterface $subVisitor): Generator { foreach ($block->getCollections() as $identifier => $collection) { yield $identifier => $subVisitor->visit($collection); } }
Visit the given $block collections into hash representation.
public function onKernelResponse(FilterResponseEvent $event): void { if (!$event->isMasterRequest()) { return; } $layoutView = $event->getRequest()->attributes->get( $this->isExceptionResponse ? 'ngbmExceptionLayoutView' : 'ngbmLayoutView' ); if (!$layoutView instanceof LayoutViewInterface) { return; } $this->tagger->tagLayout($event->getResponse(), $layoutView->getLayout()); }
Tags the response with the data for layout provided by the event.
private function visitLinkedZone(Zone $zone): ?array { $linkedZone = $zone->getLinkedZone(); if (!$linkedZone instanceof Zone) { return null; } return [ 'identifier' => $linkedZone->getIdentifier(), 'layout_id' => $linkedZone->getLayoutId(), ]; }
Visit the given $zone linked zone into hash representation.
private function visitBlocks(Zone $zone, VisitorInterface $subVisitor): Generator { foreach ($this->blockService->loadZoneBlocks($zone) as $block) { yield $subVisitor->visit($block, $subVisitor); } }
Visit the given $zone blocks into hash representation. Note: here we rely on API returning blocks already sorted by their position in the zone.
private function normalizeResultItem(CmsItemInterface $resultItem, int $version, ?string $format = null, array $context = []): array { $collectionItem = null; $cmsItem = $resultItem; $isDynamic = true; if ($resultItem instanceof ManualItem) { $collectionItem = $resultItem->getCollectionItem(); $cmsItem = $collectionItem->getCmsItem(); $isDynamic = false; } $configuration = (function () use ($collectionItem, $version): Generator { $itemConfigs = $collectionItem !== null ? $collectionItem->getConfigs() : []; foreach ($itemConfigs as $configKey => $config) { yield $configKey => $this->buildVersionedValues($config->getParameters(), $version); } })(); $data = [ 'id' => $collectionItem !== null ? $collectionItem->getId() : null, 'collection_id' => $collectionItem !== null ? $collectionItem->getCollectionId() : null, 'visible' => $collectionItem !== null ? $this->visibilityResolver->isVisible($collectionItem) : true, 'is_dynamic' => $isDynamic, 'value' => $cmsItem->getValue(), 'value_type' => $cmsItem->getValueType(), 'name' => $cmsItem->getName(), 'cms_visible' => $cmsItem->isVisible(), 'cms_url' => '', 'config' => $this->normalizer->normalize($configuration, $format, $context), ]; try { $data['cms_url'] = $this->urlGenerator->generate($cmsItem); } catch (ItemException $e) { // Do nothing } return $data; }
Normalizes the provided result item into an array.