/** * @return void */ protected function initializeAction() { $this->objects = $this->widgetConfiguration['objects']; $this->configuration = Arrays::arrayMergeRecursiveOverrule($this->configuration, $this->widgetConfiguration['configuration'], true); $this->numberOfPages = (int) ceil(count($this->objects) / (int) $this->configuration['itemsPerPage']); $this->maximumNumberOfLinks = (int) $this->configuration['maximumNumberOfLinks']; }
/** * * @param string $type * @param boolean $showHiddenProperties if TRUE, the hidden properties are shown as configured in settings "supertypeResolver.hiddenProperties" are shown as well. FALSE by default * @return array * @throws \Neos\Form\Exception\TypeDefinitionNotFoundException if a type definition was not found * @internal */ public function getMergedTypeDefinition($type, $showHiddenProperties = false) { if (!isset($this->configuration[$type])) { throw new \Neos\Form\Exception\TypeDefinitionNotFoundException(sprintf('Type "%s" not found. Probably some configuration is missing.', $type), 1325686909); } $mergedTypeDefinition = array(); if (isset($this->configuration[$type]['superTypes'])) { foreach ($this->configuration[$type]['superTypes'] as $superTypeName => $enabled) { // Skip unset node types if ($enabled === false || $enabled === null) { continue; } // Make this setting backwards compatible with old array schema (deprecated since 2.0) if (!is_bool($enabled)) { $superTypeName = $enabled; } $mergedTypeDefinition = \Neos\Utility\Arrays::arrayMergeRecursiveOverrule($mergedTypeDefinition, $this->getMergedTypeDefinition($superTypeName, $showHiddenProperties)); } } $mergedTypeDefinition = \Neos\Utility\Arrays::arrayMergeRecursiveOverrule($mergedTypeDefinition, $this->configuration[$type]); unset($mergedTypeDefinition['superTypes']); if ($showHiddenProperties === false && isset($this->settings['supertypeResolver']['hiddenProperties']) && is_array($this->settings['supertypeResolver']['hiddenProperties'])) { foreach ($this->settings['supertypeResolver']['hiddenProperties'] as $propertyName) { unset($mergedTypeDefinition[$propertyName]); } } return $mergedTypeDefinition; }
/** * @param Request $httpRequest * @param array $matchResults * @return ActionRequest */ protected function createActionRequest(Request $httpRequest, array $matchResults = null) { $actionRequest = new ActionRequest($httpRequest); if ($matchResults !== null) { $requestArguments = $actionRequest->getArguments(); $mergedArguments = Arrays::arrayMergeRecursiveOverrule($requestArguments, $matchResults); $actionRequest->setArguments($mergedArguments); } return $actionRequest; }
/** * @param string $persistenceIdentifier the persistence identifier for the form. * @param string $factoryClass The fully qualified class name of the factory (which has to implement \Neos\Form\Factory\FormFactoryInterface) * @param string $presetName name of the preset to use * @param array $overrideConfiguration factory specific configuration * @return string the rendered form */ public function render($persistenceIdentifier = null, $factoryClass = \Neos\Form\Factory\ArrayFormFactory::class, $presetName = 'default', array $overrideConfiguration = null) { if (isset($persistenceIdentifier)) { $overrideConfiguration = Arrays::arrayMergeRecursiveOverrule($this->formPersistenceManager->load($persistenceIdentifier), $overrideConfiguration ?: []); } $factory = $this->objectManager->get($factoryClass); $formDefinition = $factory->build($overrideConfiguration, $presetName); $response = new Response($this->controllerContext->getResponse()); $form = $formDefinition->bind($this->controllerContext->getRequest(), $response); return $form->render(); }
/** * @test */ public function ignoredClassesCanBeOverwrittenBySettings() { $object = new ApplicationContext('Development'); $this->assertEquals(sprintf('%s prototype object', ApplicationContext::class), Debugger::renderDump($object, 10, true)); Debugger::clearState(); $currentConfiguration = ObjectAccess::getProperty($this->configurationManager, 'configurations', true); $configurationOverwrite['Settings']['Neos']['Flow']['error']['debugger']['ignoredClasses']['Neos\\\\Flow\\\\Core\\\\.*'] = false; $newConfiguration = Arrays::arrayMergeRecursiveOverrule($currentConfiguration, $configurationOverwrite); ObjectAccess::setProperty($this->configurationManager, 'configurations', $newConfiguration, true); $this->assertContains('rootContextString', Debugger::renderDump($object, 10, true)); }
/** * Merges the given context properties with sane defaults for the context implementation. * * @param array $contextProperties * @return array */ protected function mergeContextPropertiesWithDefaults(array $contextProperties) { $contextProperties = $this->removeDeprecatedProperties($contextProperties); $defaultContextProperties = array('workspaceName' => 'live', 'currentDateTime' => $this->now, 'dimensions' => array(), 'targetDimensions' => array(), 'invisibleContentShown' => false, 'removedContentShown' => false, 'inaccessibleContentShown' => false, 'currentSite' => null, 'currentDomain' => null); if (!isset($contextProperties['currentSite'])) { $defaultContextProperties = $this->setDefaultSiteAndDomainFromCurrentRequest($defaultContextProperties); } $mergedProperties = Arrays::arrayMergeRecursiveOverrule($defaultContextProperties, $contextProperties, true); $this->mergeDimensionValues($contextProperties, $mergedProperties); $this->mergeTargetDimensionContextProperties($contextProperties, $mergedProperties, $defaultContextProperties); return $mergedProperties; }
/** * Iterate through the segments of the current request path * find the corresponding module configuration and set controller & action * accordingly * * @param string $value * @return boolean|integer */ protected function matchValue($value) { $format = pathinfo($value, PATHINFO_EXTENSION); if ($format !== '') { $value = substr($value, 0, strlen($value) - strlen($format) - 1); } $segments = Arrays::trimExplode('/', $value); $currentModuleBase = $this->settings['modules']; if ($segments === array() || !isset($currentModuleBase[$segments[0]])) { return self::MATCHRESULT_NOSUCHMODULE; } $modulePath = array(); $level = 0; $moduleConfiguration = null; $moduleController = null; $moduleAction = 'index'; foreach ($segments as $segment) { if (isset($currentModuleBase[$segment])) { $modulePath[] = $segment; $moduleConfiguration = $currentModuleBase[$segment]; if (isset($moduleConfiguration['controller'])) { $moduleController = $moduleConfiguration['controller']; } else { $moduleController = null; } if (isset($moduleConfiguration['submodules'])) { $currentModuleBase = $moduleConfiguration['submodules']; } else { $currentModuleBase = array(); } } else { if ($level === count($segments) - 1) { $moduleMethods = array_change_key_case(array_flip(get_class_methods($moduleController)), CASE_LOWER); if (array_key_exists($segment . 'action', $moduleMethods)) { $moduleAction = $segment; break; } } return self::MATCHRESULT_NOSUCHMODULE; } $level++; } if ($moduleController === null) { return self::MATCHRESULT_NOCONTROLLER; } $this->value = array('module' => implode('/', $modulePath), 'controller' => $moduleController, 'action' => $moduleAction); if ($format !== '') { $this->value['format'] = $format; } return self::MATCHRESULT_FOUND; }
/** * @return void */ protected function initializeAction() { $this->parentNode = $this->widgetConfiguration['parentNode']; $this->nodes = $this->widgetConfiguration['nodes']; $this->nodeTypeFilter = $this->widgetConfiguration['nodeTypeFilter'] ?: null; $this->configuration = Arrays::arrayMergeRecursiveOverrule($this->configuration, $this->widgetConfiguration['configuration'], true); $this->maximumNumberOfNodes = $this->configuration['maximumNumberOfNodes']; $numberOfNodes = $this->parentNode === null ? count($this->nodes) : $this->parentNode->getNumberOfChildNodes($this->nodeTypeFilter); if ($this->maximumNumberOfNodes > 0 && $numberOfNodes > $this->maximumNumberOfNodes) { $numberOfNodes = $this->maximumNumberOfNodes; } $this->numberOfPages = ceil($numberOfNodes / (int) $this->configuration['itemsPerPage']); $this->maximumNumberOfLinks = (int) $this->configuration['maximumNumberOfLinks']; }
/** * @param array $module * @return mixed * @throws DisabledModuleException */ public function indexAction(array $module) { $moduleRequest = new ActionRequest($this->request); $moduleRequest->setArgumentNamespace('moduleArguments'); $moduleRequest->setControllerObjectName($module['controller']); $moduleRequest->setControllerActionName($module['action']); if (isset($module['format'])) { $moduleRequest->setFormat($module['format']); } if ($this->request->hasArgument($moduleRequest->getArgumentNamespace()) === true && is_array($this->request->getArgument($moduleRequest->getArgumentNamespace()))) { $moduleRequest->setArguments($this->request->getArgument($moduleRequest->getArgumentNamespace())); } foreach ($this->request->getPluginArguments() as $argumentNamespace => $argument) { $moduleRequest->setArgument('--' . $argumentNamespace, $argument); } $modules = explode('/', $module['module']); $moduleConfiguration = Arrays::getValueByPath($this->settings['modules'], implode('.submodules.', $modules)); $moduleConfiguration['path'] = $module['module']; if (!$this->menuHelper->isModuleEnabled($moduleConfiguration['path'])) { throw new DisabledModuleException(sprintf('The module "%s" is disabled. You can enable it with the "enabled" flag in Settings.yaml.', $module['module']), 1437148922); } $moduleBreadcrumb = array(); $path = array(); foreach ($modules as $moduleIdentifier) { array_push($path, $moduleIdentifier); $config = Arrays::getValueByPath($this->settings['modules'], implode('.submodules.', $path)); $moduleBreadcrumb[implode('/', $path)] = $config; } $moduleRequest->setArgument('__moduleConfiguration', $moduleConfiguration); $moduleResponse = new Response($this->response); $this->dispatcher->dispatch($moduleRequest, $moduleResponse); if ($moduleResponse->hasHeader('Location')) { $this->redirectToUri($moduleResponse->getHeader('Location'), 0, $moduleResponse->getStatusCode()); } elseif ($moduleRequest->getFormat() !== 'html') { $mediaType = MediaTypes::getMediaTypeFromFilename('file.' . $moduleRequest->getFormat()); if ($mediaType !== 'application/octet-stream') { $this->controllerContext->getResponse()->setHeader('Content-Type', $mediaType); } return $moduleResponse->getContent(); } else { $user = $this->partyService->getAssignedPartyOfAccount($this->securityContext->getAccount()); $sites = $this->menuHelper->buildSiteList($this->controllerContext); $this->view->assignMultiple(array('moduleClass' => implode('-', $modules), 'moduleContents' => $moduleResponse->getContent(), 'title' => $moduleRequest->hasArgument('title') ? $moduleRequest->getArgument('title') : $moduleConfiguration['label'], 'rootModule' => array_shift($modules), 'submodule' => array_shift($modules), 'moduleConfiguration' => $moduleConfiguration, 'moduleBreadcrumb' => $moduleBreadcrumb, 'user' => $user, 'modules' => $this->menuHelper->buildModuleList($this->controllerContext), 'sites' => $sites)); } }
/** * Iterate through the configured modules, find the matching module and set * the route path accordingly * * @param array $value (contains action, controller and package of the module controller) * @return boolean */ protected function resolveValue($value) { if (is_array($value)) { $this->value = isset($value['@action']) && $value['@action'] !== 'index' ? $value['@action'] : ''; if ($this->value !== '' && isset($value['@format'])) { $this->value .= '.' . $value['@format']; } $exceedingArguments = array(); foreach ($value as $argumentKey => $argumentValue) { if (substr($argumentKey, 0, 1) !== '@' && substr($argumentKey, 0, 2) !== '__') { $exceedingArguments[$argumentKey] = $argumentValue; } } if ($exceedingArguments !== array()) { $exceedingArguments = Arrays::removeEmptyElementsRecursively($exceedingArguments); $exceedingArguments = $this->persistenceManager->convertObjectsToIdentityArrays($exceedingArguments); $queryString = http_build_query(array($this->name => $exceedingArguments), null, '&'); if ($queryString !== '') { $this->value .= '?' . $queryString; } } } return true; }
/** * Checks if the given $nodeType is allowed as a childNode of the given $childNodeName * (which must be auto-created in $this NodeType). * * Only allowed to be called if $childNodeName is auto-created. * * @param string $childNodeName The name of a configured childNode of this NodeType * @param NodeType $nodeType The NodeType to check constraints for. * @return boolean TRUE if the $nodeType is allowed as grandchild node, FALSE otherwise. * @throws \InvalidArgumentException If the given $childNodeName is not configured to be auto-created in $this. */ public function allowsGrandchildNodeType($childNodeName, NodeType $nodeType) { $autoCreatedChildNodes = $this->getAutoCreatedChildNodes(); if (!isset($autoCreatedChildNodes[$childNodeName])) { throw new \InvalidArgumentException('The method "allowsGrandchildNodeType" can only be used on auto-created childNodes, given $childNodeName "' . $childNodeName . '" is not auto-created.', 1403858395); } $constraints = $autoCreatedChildNodes[$childNodeName]->getConfiguration('constraints.nodeTypes') ?: array(); $childNodeConfiguration = []; foreach ($this->getConfiguration('childNodes') as $name => $configuration) { $childNodeConfiguration[Utility::renderValidNodeName($name)] = $configuration; } $childNodeConstraintConfiguration = ObjectAccess::getPropertyPath($childNodeConfiguration, $childNodeName . '.constraints.nodeTypes') ?: array(); $constraints = Arrays::arrayMergeRecursiveOverrule($constraints, $childNodeConstraintConfiguration); return $this->isNodeTypeAllowedByConstraints($nodeType, $constraints); }
/** * Create a new user * * This command creates a new user which has access to the backend user interface. * * More specifically, this command will create a new user and a new account at the same time. The created account * is, by default, a Neos backend account using the the "Typo3BackendProvider" for authentication. The given username * will be used as an account identifier for that new account. * * If an authentication provider name is specified, the new account will be created for that provider instead. * * Roles for the new user can optionally be specified as a comma separated list. For all roles provided by * Neos, the role namespace "Neos.Neos:" can be omitted. * * @param string $username The username of the user to be created, used as an account identifier for the newly created account * @param string $password Password of the user to be created * @param string $firstName First name of the user to be created * @param string $lastName Last name of the user to be created * @param string $roles A comma separated list of roles to assign. Examples: "Editor, Acme.Foo:Reviewer" * @param string $authenticationProvider Name of the authentication provider to use for the new account. Example: "Typo3BackendProvider" * @return void */ public function createCommand($username, $password, $firstName, $lastName, $roles = null, $authenticationProvider = null) { $user = $this->userService->getUser($username, $authenticationProvider); if ($user instanceof User) { $this->outputLine('The username "%s" is already in use', array($username)); $this->quit(1); } try { if ($roles === null) { $user = $this->userService->createUser($username, $password, $firstName, $lastName, null, $authenticationProvider); } else { $roleIdentifiers = Arrays::trimExplode(',', $roles); $user = $this->userService->createUser($username, $password, $firstName, $lastName, $roleIdentifiers, $authenticationProvider); } $roleIdentifiers = array(); foreach ($user->getAccounts() as $account) { /** @var Account $account */ foreach ($account->getRoles() as $role) { /** @var Role $role */ $roleIdentifiers[$role->getIdentifier()] = true; } } $roleIdentifiers = array_keys($roleIdentifiers); if (count($roleIdentifiers) === 0) { $this->outputLine('Created user "%s".', array($username)); $this->outputLine('<b>Please note that this user currently does not have any roles assigned.</b>'); } else { $this->outputLine('Created user "%s" and assigned the following role%s: %s.', array($username, count($roleIdentifiers) > 1 ? 's' : '', implode(', ', $roleIdentifiers))); } } catch (\Exception $exception) { $this->outputLine($exception->getMessage()); $this->quit(1); } }
/** * Assigns a value to a node or a property in the object tree, specified by the object path array. * * @param array $objectPathArray The object path, specifying the node / property to set * @param mixed $value The value to assign, is a non-array type or an array with __eelExpression etc. * @param array $objectTree The current (sub-) tree, used internally - don't specify! * @return array The modified object tree */ protected function setValueInObjectTree(array $objectPathArray, $value, &$objectTree = null) { if ($objectTree === null) { $objectTree =& $this->objectTree; } $currentKey = array_shift($objectPathArray); if ((int) $currentKey > 0) { $currentKey = (int) $currentKey; } if (empty($objectPathArray)) { // last part of the iteration, setting the final value if (isset($objectTree[$currentKey]) && $value === null) { unset($objectTree[$currentKey]); } elseif (isset($objectTree[$currentKey]) && is_array($objectTree[$currentKey])) { if (is_array($value)) { $objectTree[$currentKey] = Arrays::arrayMergeRecursiveOverrule($objectTree[$currentKey], $value); } else { $objectTree[$currentKey]['__value'] = $value; $objectTree[$currentKey]['__eelExpression'] = null; $objectTree[$currentKey]['__objectType'] = null; } } else { $objectTree[$currentKey] = $value; } } else { // we still need to traverse further down if (isset($objectTree[$currentKey]) && !is_array($objectTree[$currentKey])) { // the element one-level-down is already defined, but it is NOT an array. So we need to convert the simple type to __value $objectTree[$currentKey] = array('__value' => $objectTree[$currentKey], '__eelExpression' => null, '__objectType' => null); } elseif (!isset($objectTree[$currentKey])) { $objectTree[$currentKey] = array(); } $this->setValueInObjectTree($objectPathArray, $value, $objectTree[$currentKey]); } return $objectTree; }
/** * Kickstart a new command controller * * Creates a new command controller with the given name in the specified * package. The generated controller class already contains an example command. * * @param string $packageKey The package key of the package for the new controller * @param string $controllerName The name for the new controller. This may also be a comma separated list of controller names. * @param boolean $force Overwrite any existing controller. * @return string * @see neos.kickstarter:kickstart:actioncontroller */ public function commandControllerCommand($packageKey, $controllerName, $force = false) { $this->validatePackageKey($packageKey); if (!$this->packageManager->isPackageAvailable($packageKey)) { $this->outputLine('Package "%s" is not available.', array($packageKey)); exit(2); } $generatedFiles = array(); $controllerNames = Arrays::trimExplode(',', $controllerName); foreach ($controllerNames as $currentControllerName) { $generatedFiles += $this->generatorService->generateCommandController($packageKey, $currentControllerName, $force); } $this->outputLine(implode(PHP_EOL, $generatedFiles)); }
/** * Transforms the convoluted _FILES superglobal into a manageable form. * * @param array $convolutedFiles The _FILES superglobal * @return array Untangled files */ protected function untangleFilesArray(array $convolutedFiles) { $untangledFiles = []; $fieldPaths = []; foreach ($convolutedFiles as $firstLevelFieldName => $fieldInformation) { if (!is_array($fieldInformation['error'])) { $fieldPaths[] = [$firstLevelFieldName]; } else { $newFieldPaths = $this->calculateFieldPaths($fieldInformation['error'], $firstLevelFieldName); array_walk($newFieldPaths, function (&$value) { $value = explode('/', $value); }); $fieldPaths = array_merge($fieldPaths, $newFieldPaths); } } foreach ($fieldPaths as $fieldPath) { if (count($fieldPath) === 1) { $fileInformation = $convolutedFiles[$fieldPath[0]]; } else { $fileInformation = []; foreach ($convolutedFiles[$fieldPath[0]] as $key => $subStructure) { $fileInformation[$key] = Arrays::getValueByPath($subStructure, array_slice($fieldPath, 1)); } } if (isset($fileInformation['error']) && $fileInformation['error'] !== \UPLOAD_ERR_NO_FILE) { $untangledFiles = Arrays::setValueByPath($untangledFiles, $fieldPath, $fileInformation); } } return $untangledFiles; }
/** * @Then /^I can (not )?call the method "([^"]*)" of class "([^"]*)"(?: with arguments "([^"]*)")?$/ */ public function iCanCallTheMethodOfClassWithArguments($not, $methodName, $className, $arguments = '') { if ($this->isolated === true) { $this->callStepInSubProcess(__METHOD__, sprintf(' %s %s %s %s %s %s %s %s', 'string', escapeshellarg(trim($not)), 'string', escapeshellarg($methodName), 'string', escapeshellarg($className), 'string', escapeshellarg($arguments))); } else { $this->setupSecurity(); $instance = $this->objectManager->get($className); try { $result = call_user_func_array([$instance, $methodName], Arrays::trimExplode(',', $arguments)); if ($not === 'not') { Assert::fail('Method should not be callable'); } return $result; } catch (AccessDeniedException $exception) { if ($not !== 'not') { throw $exception; } } } }
/** * Returns an ActionRequest which referred to this request, if any. * * The referring request is not set or determined automatically but must be * explicitly set through the corresponding internal argument "__referrer". * This mechanism is used by Flow's form and validation mechanisms. * * @return ActionRequest the referring request, or NULL if no referrer found */ public function getReferringRequest() { if ($this->referringRequest !== null) { return $this->referringRequest; } if (!isset($this->internalArguments['__referrer'])) { return null; } if (is_array($this->internalArguments['__referrer'])) { $referrerArray = $this->internalArguments['__referrer']; $referringRequest = new ActionRequest($this->getHttpRequest()); $arguments = []; if (isset($referrerArray['arguments'])) { $serializedArgumentsWithHmac = $referrerArray['arguments']; $serializedArguments = $this->hashService->validateAndStripHmac($serializedArgumentsWithHmac); $arguments = unserialize(base64_decode($serializedArguments)); unset($referrerArray['arguments']); } $referringRequest->setArguments(Arrays::arrayMergeRecursiveOverrule($arguments, $referrerArray)); return $referringRequest; } else { $this->referringRequest = $this->internalArguments['__referrer']; } return $this->referringRequest; }
/** * @test */ public function arrayMergeRecursiveCallbackConvertsSimpleValuesWithGivenClosureAndReturnedSimpleTypesOverwrite() { $inputArray1 = ['k1' => 'v1', 'k2' => ['k2.1' => 'v2.1'], 'k3' => ['k3.1' => 'value']]; $inputArray2 = ['k2' => 'v2.2', 'k3' => null]; $expected = ['k1' => 'v1', 'k2' => ['k2.1' => 'v2.1', '__convertedValue' => 'v2.2'], 'k3' => null]; $actual = Arrays::arrayMergeRecursiveOverruleWithCallback($inputArray1, $inputArray2, function ($simpleType) { if ($simpleType === null) { return null; } return ['__convertedValue' => $simpleType]; }); $this->assertSame($expected, $actual); }
/** * Checks whether $routeValues can be resolved to a corresponding uri. * If all Route Parts can resolve one or more of the $routeValues, TRUE is * returned and $this->matchingURI contains the generated URI (excluding * protocol and host). * * @param array $routeValues An array containing key/value pairs to be resolved to uri segments * @return boolean TRUE if this Route corresponds to the given $routeValues, otherwise FALSE * @throws InvalidRoutePartValueException */ public function resolves(array $routeValues) { $this->resolvedUriPath = null; if ($this->uriPattern === null) { return false; } if (!$this->isParsed) { $this->parse(); } $resolvedUriPath = ''; $remainingDefaults = $this->defaults; $requireOptionalRouteParts = false; $matchingOptionalUriPortion = ''; /** @var $routePart RoutePartInterface */ foreach ($this->routeParts as $routePart) { if (!$routePart->resolve($routeValues)) { if (!$routePart->hasDefaultValue()) { return false; } } if ($routePart->getName() !== null) { $remainingDefaults = Arrays::unsetValueByPath($remainingDefaults, $routePart->getName()); } $routePartValue = null; if ($routePart->hasValue()) { $routePartValue = $routePart->getValue(); if (!is_string($routePartValue)) { throw new InvalidRoutePartValueException('RoutePart::getValue() must return a string after calling RoutePart::resolve(), got ' . (is_object($routePartValue) ? get_class($routePartValue) : gettype($routePartValue)) . ' for RoutePart "' . get_class($routePart) . '" in Route "' . $this->getName() . '".'); } } $routePartDefaultValue = $routePart->getDefaultValue(); if ($routePartDefaultValue !== null && !is_string($routePartDefaultValue)) { throw new InvalidRoutePartValueException('RoutePart::getDefaultValue() must return a string, got ' . (is_object($routePartDefaultValue) ? get_class($routePartDefaultValue) : gettype($routePartDefaultValue)) . ' for RoutePart "' . get_class($routePart) . '" in Route "' . $this->getName() . '".'); } if (!$routePart->isOptional()) { $resolvedUriPath .= $routePart->hasValue() ? $routePartValue : $routePartDefaultValue; $requireOptionalRouteParts = false; continue; } if ($routePart->hasValue() && strtolower($routePartValue) !== strtolower($routePartDefaultValue)) { $matchingOptionalUriPortion .= $routePartValue; $requireOptionalRouteParts = true; } else { $matchingOptionalUriPortion .= $routePartDefaultValue; } if ($requireOptionalRouteParts) { $resolvedUriPath .= $matchingOptionalUriPortion; $matchingOptionalUriPortion = ''; } } if ($this->compareAndRemoveMatchingDefaultValues($remainingDefaults, $routeValues) !== true) { return false; } if (isset($routeValues['@format']) && $routeValues['@format'] === '') { unset($routeValues['@format']); } // add query string if (count($routeValues) > 0) { $routeValues = Arrays::removeEmptyElementsRecursively($routeValues); $routeValues = $this->persistenceManager->convertObjectsToIdentityArrays($routeValues); if (!$this->appendExceedingArguments) { $internalArguments = $this->extractInternalArguments($routeValues); if ($routeValues !== []) { return false; } $routeValues = $internalArguments; } $queryString = http_build_query($routeValues, null, '&'); if ($queryString !== '') { $resolvedUriPath .= strpos($resolvedUriPath, '?') !== false ? '&' . $queryString : '?' . $queryString; } } $this->resolvedUriPath = $resolvedUriPath; return true; }
/** * @return string */ public function editPreviewAction() { $this->response->setHeader('Content-Type', 'application/json'); $configuration = new PositionalArraySorter(Arrays::getValueByPath($this->settings, 'userInterface.editPreviewModes')); return json_encode($configuration->toArray()); }
/** * Reconstitues related entities to an unserialized object in __wakeup. * Used in __wakeup methods of proxy classes. * * Note: This method adds code which ignores objects of type Neos\Flow\ResourceManagement\ResourcePointer in order to provide * backwards compatibility data generated with Flow 2.2.x which still provided that class. * * @return void */ private function Flow_setRelatedEntities() { if (property_exists($this, 'Flow_Persistence_RelatedEntities') && is_array($this->Flow_Persistence_RelatedEntities)) { $persistenceManager = Bootstrap::$staticObjectManager->get(PersistenceManagerInterface::class); foreach ($this->Flow_Persistence_RelatedEntities as $entityInformation) { if ($entityInformation['entityType'] === ResourcePointer::class) { continue; } $entity = $persistenceManager->getObjectByIdentifier($entityInformation['identifier'], $entityInformation['entityType'], true); if (isset($entityInformation['entityPath'])) { $this->{$entityInformation['propertyName']} = Arrays::setValueByPath($this->{$entityInformation['propertyName']}, $entityInformation['entityPath'], $entity); } else { $this->{$entityInformation['propertyName']} = $entity; } } unset($this->Flow_Persistence_RelatedEntities); } }
/** * @param array $additionalOptions * @return array * @throws InvalidConfigurationException */ protected function getOptionsMergedWithDefaults(array $additionalOptions = array()) { $defaultOptions = Arrays::getValueByPath($this->settings, 'image.defaultOptions'); if (!is_array($defaultOptions)) { $defaultOptions = array(); } if ($additionalOptions !== array()) { $defaultOptions = Arrays::arrayMergeRecursiveOverrule($defaultOptions, $additionalOptions); } $quality = isset($defaultOptions['quality']) ? (int) $defaultOptions['quality'] : 90; if ($quality < 0 || $quality > 100) { throw new InvalidConfigurationException(sprintf('Setting "Neos.Media.image.defaultOptions.quality" allow only value between 0 and 100, current value: %s', $quality), 1404982574); } $defaultOptions['jpeg_quality'] = $quality; // png_compression_level should be an integer between 0 and 9 and inverse to the quality level given. So quality 100 should result in compression 0. $defaultOptions['png_compression_level'] = 9 - ceil($quality * 9 / 100); return $defaultOptions; }
/** * Invokes the Factory defined in the object configuration of the specified object in order * to build an instance. Arguments which were defined in the object configuration are * passed to the factory method. * * @param string $objectName Name of the object to build * @return object The built object */ protected function buildObjectByFactory($objectName) { $factory = $this->get($this->objects[$objectName]['f'][0]); $factoryMethodName = $this->objects[$objectName]['f'][1]; $factoryMethodArguments = []; foreach ($this->objects[$objectName]['fa'] as $index => $argumentInformation) { switch ($argumentInformation['t']) { case ObjectConfigurationArgument::ARGUMENT_TYPES_SETTING: $settingPath = explode('.', $argumentInformation['v']); $factoryMethodArguments[$index] = Arrays::getValueByPath($this->allSettings, $settingPath); break; case ObjectConfigurationArgument::ARGUMENT_TYPES_STRAIGHTVALUE: $factoryMethodArguments[$index] = $argumentInformation['v']; break; case ObjectConfigurationArgument::ARGUMENT_TYPES_OBJECT: $factoryMethodArguments[$index] = $this->get($argumentInformation['v']); break; } } if (count($factoryMethodArguments) === 0) { return $factory->{$factoryMethodName}(); } else { return call_user_func_array([$factory, $factoryMethodName], $factoryMethodArguments); } }
/** * A method which runs the task implemented by the plugin for the given command * * @param string $controllerCommandName Name of the command in question, for example "repair" * @param ConsoleOutput $output An instance of ConsoleOutput which can be used for output or dialogues * @param NodeType $nodeType Only handle this node type (if specified) * @param string $workspaceName Only handle this workspace (if specified) * @param boolean $dryRun If TRUE, don't do any changes, just simulate what you would do * @param boolean $cleanup If FALSE, cleanup tasks are skipped * @param string $skip Skip the given check or checks (comma separated) * @param string $only Only execute the given check or checks (comma separated) * @return void */ public function invokeSubCommand($controllerCommandName, ConsoleOutput $output, NodeType $nodeType = null, $workspaceName = 'live', $dryRun = false, $cleanup = true, $skip = null, $only = null) { $this->output = $output; $commandMethods = ['generateUriPathSegments' => ['cleanup' => false], 'removeContentDimensionsFromRootAndSitesNode' => ['cleanup' => true]]; $skipCommandNames = Arrays::trimExplode(',', $skip === null ? '' : $skip); $onlyCommandNames = Arrays::trimExplode(',', $only === null ? '' : $only); switch ($controllerCommandName) { case 'repair': foreach ($commandMethods as $commandMethodName => $commandMethodConfiguration) { if (in_array($commandMethodName, $skipCommandNames)) { continue; } if ($onlyCommandNames !== [] && !in_array($commandMethodName, $onlyCommandNames)) { continue; } if (!$cleanup && $commandMethodConfiguration['cleanup']) { continue; } $this->{$commandMethodName}($workspaceName, $dryRun, $nodeType); } } }
/** * Sets labels for global NodeType elements like tabs and groups and the general label. * * @param string $nodeTypeLabelIdPrefix * @param array $configuration * @return void */ protected function setGlobalUiElementLabels($nodeTypeName, array &$configuration) { $nodeTypeLabelIdPrefix = $this->generateNodeTypeLabelIdPrefix($nodeTypeName); if ($this->shouldFetchTranslation($configuration['ui'])) { $configuration['ui']['label'] = $this->getInspectorElementTranslationId($nodeTypeLabelIdPrefix, 'ui', 'label'); } if (isset($configuration['ui']['help']['message']) && $this->shouldFetchTranslation($configuration['ui']['help'], 'message')) { $configuration['ui']['help']['message'] = $this->getInspectorElementTranslationId($nodeTypeLabelIdPrefix, 'ui', 'help.message'); } if (isset($configuration['ui']['help'])) { $configurationThumbnail = isset($configuration['ui']['help']['thumbnail']) ? $configuration['ui']['help']['thumbnail'] : null; $thumbnailUrl = $this->resolveHelpMessageThumbnail($nodeTypeName, $configurationThumbnail); if ($thumbnailUrl !== '') { $configuration['ui']['help']['thumbnail'] = $thumbnailUrl; } } $inspectorConfiguration = Arrays::getValueByPath($configuration, 'ui.inspector'); if (is_array($inspectorConfiguration)) { foreach ($inspectorConfiguration as $elementTypeName => $elementTypeItems) { foreach ($elementTypeItems as $elementName => $elementConfiguration) { if (!is_array($elementConfiguration) || !$this->shouldFetchTranslation($elementConfiguration)) { continue; } $translationLabelId = $this->getInspectorElementTranslationId($nodeTypeLabelIdPrefix, $elementTypeName, $elementName); $configuration['ui']['inspector'][$elementTypeName][$elementName]['label'] = $translationLabelId; } } } }
/** * Merges two policy configuration arrays. * * @param array $firstConfigurationArray * @param array $secondConfigurationArray * @return array */ protected function mergePolicyConfiguration(array $firstConfigurationArray, array $secondConfigurationArray) { $result = Arrays::arrayMergeRecursiveOverrule($firstConfigurationArray, $secondConfigurationArray); if (!isset($result['roles'])) { return $result; } foreach ($result['roles'] as $roleIdentifier => $roleConfiguration) { if (!isset($firstConfigurationArray['roles'][$roleIdentifier]['privileges']) || !isset($secondConfigurationArray['roles'][$roleIdentifier]['privileges'])) { continue; } $result['roles'][$roleIdentifier]['privileges'] = array_merge($firstConfigurationArray['roles'][$roleIdentifier]['privileges'], $secondConfigurationArray['roles'][$roleIdentifier]['privileges']); } return $result; }
/** * Move a settings path from "source" to "destination"; best to be used when package names change. * * @param string $sourcePath * @param string $destinationPath */ protected function moveSettingsPaths($sourcePath, $destinationPath) { $this->processConfiguration(ConfigurationManager::CONFIGURATION_TYPE_SETTINGS, function (array &$configuration) use($sourcePath, $destinationPath) { $sourceConfigurationValue = Arrays::getValueByPath($configuration, $sourcePath); $destinationConfigurationValue = Arrays::getValueByPath($configuration, $destinationPath); if ($sourceConfigurationValue !== null) { // source exists, so we need to move source to destination. if ($destinationConfigurationValue !== null) { // target exists as well; we need to MERGE source and target. $destinationConfigurationValue = Arrays::arrayMergeRecursiveOverrule($sourceConfigurationValue, $destinationConfigurationValue); } else { // target does NOT exist; we directly set target = source $destinationConfigurationValue = $sourceConfigurationValue; } // set the config on the new path $configuration = Arrays::setValueByPath($configuration, $destinationPath, $destinationConfigurationValue); // Unset the old configuration $configuration = Arrays::unsetValueByPath($configuration, $sourcePath); // remove empty keys before our removed key (if it exists) $sourcePathExploded = explode('.', $sourcePath); for ($length = count($sourcePathExploded) - 1; $length > 0; $length--) { $temporaryPath = array_slice($sourcePathExploded, 0, $length); $valueAtPath = Arrays::getValueByPath($configuration, $temporaryPath); if (empty($valueAtPath)) { $configuration = Arrays::unsetValueByPath($configuration, $temporaryPath); } else { break; } } } }, true); }
/** * @param NodeInterface $rootNode * @param array<\Neos\ContentRepository\Domain\Model\NodeData> $nodes * @return array */ public function collectParentNodeData(NodeInterface $rootNode, array $nodes) { $nodeCollection = array(); $addNode = function ($node, $matched) use($rootNode, &$nodeCollection) { /** @var NodeInterface $node */ $path = str_replace('/', '.children.', substr($node->getPath(), strlen($rootNode->getPath()) + 1)); if ($path !== '') { $nodeCollection = Arrays::setValueByPath($nodeCollection, $path . '.node', $node); if ($matched === true) { $nodeCollection = Arrays::setValueByPath($nodeCollection, $path . '.matched', true); } } }; $findParent = function ($node) use(&$findParent, &$addNode) { /** @var NodeInterface $node */ $parent = $node->getParent(); if ($parent !== null) { $addNode($parent, false); $findParent($parent); } }; foreach ($nodes as $node) { $addNode($node, true); $findParent($node); } $treeNodes = array(); $self = $this; $collectTreeNodeData = function (&$treeNodes, $node) use(&$collectTreeNodeData, $self) { $children = array(); if (isset($node['children'])) { foreach ($node['children'] as $childNode) { $collectTreeNodeData($children, $childNode); } } $treeNodes[] = $self->collectTreeNodeData($node['node'], true, $children, $children !== array(), isset($node['matched'])); }; foreach ($nodeCollection as $firstLevelNode) { $collectTreeNodeData($treeNodes, $firstLevelNode); } return $treeNodes; }
/** * Loads the specified configuration file and returns its content as an * array. If the file does not exist or could not be loaded, an empty * array is returned * * @param string $pathAndFilename Full path and filename of the file to load, excluding the file extension (ie. ".yaml") * @param boolean $allowSplitSource If TRUE, the type will be used as a prefix when looking for configuration files * @return array * @throws ParseErrorException */ public function load($pathAndFilename, $allowSplitSource = false) { $pathsAndFileNames = [$pathAndFilename . '.yaml']; if ($allowSplitSource === true) { $splitSourcePathsAndFileNames = glob($pathAndFilename . '.*.yaml'); if ($splitSourcePathsAndFileNames !== false) { sort($splitSourcePathsAndFileNames); $pathsAndFileNames = array_merge($pathsAndFileNames, $splitSourcePathsAndFileNames); } } $configuration = []; foreach ($pathsAndFileNames as $pathAndFilename) { if (is_file($pathAndFilename)) { try { if ($this->usePhpYamlExtension) { if (strpos($pathAndFilename, 'resource://') === 0) { $yaml = file_get_contents($pathAndFilename); $loadedConfiguration = @yaml_parse($yaml); unset($yaml); } else { $loadedConfiguration = @yaml_parse_file($pathAndFilename); } if ($loadedConfiguration === false) { throw new ParseErrorException('A parse error occurred while parsing file "' . $pathAndFilename . '".', 1391894094); } } else { $loadedConfiguration = Yaml::parse($pathAndFilename); } if (is_array($loadedConfiguration)) { $configuration = Arrays::arrayMergeRecursiveOverrule($configuration, $loadedConfiguration); } } catch (Exception $exception) { throw new ParseErrorException('A parse error occurred while parsing file "' . $pathAndFilename . '". Error message: ' . $exception->getMessage(), 1232014321); } } } return $configuration; }
/** * Get the preset configuration by $presetName, taking the preset hierarchy * (specified by *parentPreset*) into account. * * @param string $presetName name of the preset to get the configuration for * @return array the preset configuration * @throws \Neos\Form\Exception\PresetNotFoundException if preset with the name $presetName was not found * @api */ public function getPresetConfiguration($presetName) { if (!isset($this->formSettings['presets'][$presetName])) { throw new \Neos\Form\Exception\PresetNotFoundException(sprintf('The Preset "%s" was not found underneath TYPO3: Form: presets.', $presetName), 1332170104); } $preset = $this->formSettings['presets'][$presetName]; if (isset($preset['parentPreset'])) { $parentPreset = $this->getPresetConfiguration($preset['parentPreset']); unset($preset['parentPreset']); $preset = \Neos\Utility\Arrays::arrayMergeRecursiveOverrule($parentPreset, $preset); } return $preset; }