/**
  * Change the property on the given node.
  *
  * @param NodeData $node
  * @return void
  */
 public function execute(NodeData $node)
 {
     foreach ($node->getNodeType()->getProperties() as $propertyName => $propertyConfiguration) {
         if (isset($propertyConfiguration['type']) && in_array(trim($propertyConfiguration['type']), $this->getHandledObjectTypes())) {
             if (!isset($nodeProperties)) {
                 $nodeRecordQuery = $this->entityManager->getConnection()->prepare('SELECT properties FROM typo3_typo3cr_domain_model_nodedata WHERE persistence_object_identifier=?');
                 $nodeRecordQuery->execute([$this->persistenceManager->getIdentifierByObject($node)]);
                 $nodeRecord = $nodeRecordQuery->fetch(\PDO::FETCH_ASSOC);
                 $nodeProperties = unserialize($nodeRecord['properties']);
             }
             if (!isset($nodeProperties[$propertyName]) || !is_object($nodeProperties[$propertyName])) {
                 continue;
             }
             /** @var Asset $assetObject */
             $assetObject = $nodeProperties[$propertyName];
             $nodeProperties[$propertyName] = null;
             $stream = $assetObject->getResource()->getStream();
             if ($stream === false) {
                 continue;
             }
             fclose($stream);
             $objectType = TypeHandling::getTypeForValue($assetObject);
             $objectIdentifier = ObjectAccess::getProperty($assetObject, 'Persistence_Object_Identifier', true);
             $nodeProperties[$propertyName] = array('__flow_object_type' => $objectType, '__identifier' => $objectIdentifier);
         }
     }
     if (isset($nodeProperties)) {
         $nodeUpdateQuery = $this->entityManager->getConnection()->prepare('UPDATE typo3_typo3cr_domain_model_nodedata SET properties=? WHERE persistence_object_identifier=?');
         $nodeUpdateQuery->execute([serialize($nodeProperties), $this->persistenceManager->getIdentifierByObject($node)]);
     }
 }
 /**
  * @test
  */
 public function renderWithoutValueInvokesRenderChildren()
 {
     $object = new \stdClass();
     $this->viewHelper->expects($this->once())->method('renderChildren')->will($this->returnValue($object));
     $this->mockPersistenceManager->expects($this->once())->method('getIdentifierByObject')->with($object)->will($this->returnValue('b59292c5-1a28-4b36-8615-10d3c5b3a4d8'));
     $this->assertEquals('b59292c5-1a28-4b36-8615-10d3c5b3a4d8', $this->viewHelper->render());
 }
Esempio n. 3
0
 /**
  * Gets the Party having an Account assigned
  *
  * @param Account $account
  * @return AbstractParty
  */
 public function getAssignedPartyOfAccount(Account $account)
 {
     $accountIdentifier = $this->persistenceManager->getIdentifierByObject($account);
     if (!isset($this->accountsInPartyRuntimeCache[$accountIdentifier])) {
         $party = $this->partyRepository->findOneHavingAccount($account);
         $this->accountsInPartyRuntimeCache[$accountIdentifier] = $party;
     }
     return $this->accountsInPartyRuntimeCache[$accountIdentifier];
 }
 /**
  * @test
  * @return void
  */
 public function generateUuidGeneratesUuidAndRegistersProxyAsNewObject()
 {
     $className = 'Class' . md5(uniqid(mt_rand(), true));
     eval('class ' . $className . ' implements \\Neos\\Flow\\Persistence\\Aspect\\PersistenceMagicInterface { public $Persistence_Object_Identifier = NULL; }');
     $object = new $className();
     $this->mockJoinPoint->expects($this->atLeastOnce())->method('getProxy')->will($this->returnValue($object));
     $this->mockPersistenceManager->expects($this->atLeastOnce())->method('registerNewObject')->with($object);
     $this->persistenceMagicAspect->generateUuid($this->mockJoinPoint);
     $this->assertEquals(36, strlen($object->Persistence_Object_Identifier));
 }
Esempio n. 5
0
 /**
  * @test
  */
 public function getAssignedPartyOfAccountCachesParty()
 {
     $this->mockPersistenceManager->expects($this->any())->method('getIdentifierByObject')->will($this->returnValue('723e3913-f803-42c8-a44c-fd7115f555c3'));
     $this->mockPartyRepository->expects($this->once())->method('findOneHavingAccount')->with($this->account)->will($this->returnValue($this->party));
     $this->party->addAccount($this->account);
     $assignedParty = $this->partyService->getAssignedPartyOfAccount($this->account);
     $this->assertSame($this->party, $assignedParty);
     $assignedParty = $this->partyService->getAssignedPartyOfAccount($this->account);
     $this->assertSame($this->party, $assignedParty);
 }
 /**
  * Sets up this test case
  *
  */
 public function setUp()
 {
     $this->mockObjectManager = $this->createMock(ObjectManagerInterface::class);
     $this->route = $this->getAccessibleMock(Routing\Route::class, ['dummy']);
     $this->route->_set('objectManager', $this->mockObjectManager);
     $this->mockPersistenceManager = $this->createMock(PersistenceManagerInterface::class);
     $this->mockPersistenceManager->expects($this->any())->method('convertObjectsToIdentityArrays')->will($this->returnCallback(function ($array) {
         return $array;
     }));
     $this->inject($this->route, 'persistenceManager', $this->mockPersistenceManager);
 }
 /**
  * Loads the objects this LazySplObjectStorage is supposed to hold.
  *
  * @return void
  */
 protected function initialize()
 {
     if (is_array($this->objectIdentifiers)) {
         foreach ($this->objectIdentifiers as $identifier) {
             try {
                 parent::attach($this->persistenceManager->getObjectByIdentifier($identifier));
             } catch (Exception\InvalidObjectDataException $exception) {
                 // when security query rewriting holds back an object here, we skip it...
             }
         }
         $this->objectIdentifiers = null;
     }
 }
 /**
  * Renders a hidden form field containing the technical identity of the given object.
  *
  * @param object $object Object to create the identity field for
  * @param string $name Name
  * @return string A hidden field containing the Identity (UUID in Flow) of the given object or NULL if the object is unknown to the persistence framework
  * @see \Neos\Flow\Mvc\Controller\Argument::setValue()
  */
 protected function renderHiddenIdentityField($object, $name)
 {
     if (!is_object($object) || $this->persistenceManager->isNewObject($object)) {
         return '';
     }
     $identifier = $this->persistenceManager->getIdentifierByObject($object);
     if ($identifier === null) {
         return chr(10) . '<!-- Object of type ' . get_class($object) . ' is without identity -->' . chr(10);
     }
     $name = $this->prefixFieldName($name) . '[__identity]';
     $this->registerFieldNameForFormTokenGeneration($name);
     return chr(10) . '<input type="hidden" name="' . $name . '" value="' . $identifier . '" />' . chr(10);
 }
 /**
  * Outputs the identifier of the specified object
  *
  * @param object $value the object to render the identifier for, or NULL if VH children should be used
  * @return mixed the identifier of $value, usually the UUID
  * @throws ViewHelper\Exception if the given value is no object
  * @api
  */
 public function render($value = null)
 {
     if ($value === null) {
         $value = $this->renderChildren();
     }
     if ($value === null) {
         return null;
     }
     if (!is_object($value)) {
         throw new ViewHelper\Exception('f:format.identifier expects an object, ' . gettype($value) . ' given.', 1337700024);
     }
     return $this->persistenceManager->getIdentifierByObject($value);
 }
 /**
  * Add a redirect
  *
  * Creates a new custom redirect. The optional argument ``host`` is used to define a specific redirect only valid
  * for a certain domain If no ``host`` argument is supplied, the redirect will act as a fallback redirect for all
  * domains in use. If any redirect exists with the same ``source`` property, it will be replaced if the ``force``
  * property has been set.
  *
  * @param string $source The relative URI path that should trigger the redirect
  * @param string $target The relative URI path that the redirect should point to
  * @param integer $statusCode The status code of the redirect header
  * @param string $host (optional) The host the redirect is valid for. If none is set, the redirect is valid for all
  * @param boolean $force Replace existing redirect (based on the source URI)
  * @return void
  */
 public function addCommand($source, $target, $statusCode, $host = null, $force = false)
 {
     $this->outputLine();
     $this->outputLine('<b>Create a redirect ...</b>');
     $this->outputLine();
     $redirect = $this->redirectStorage->getOneBySourceUriPathAndHost($source, $host, false);
     $isSame = $this->isSame($source, $target, $host, $statusCode, $redirect);
     if ($redirect !== null && $isSame === false && $force === false) {
         $this->outputLine('A redirect with the same source URI exist, see below:');
         $this->outputLine();
         $this->outputRedirectLine('<error>!!</error>', $redirect);
         $this->outputLine();
         $this->outputLine('Use --force to replace it');
         $this->outputLine();
         $this->sendAndExit(1);
     } elseif ($redirect !== null && $isSame === false && $force === true) {
         $this->redirectStorage->removeOneBySourceUriPathAndHost($source, $host);
         $this->outputRedirectLine('<info>--</info>', $redirect);
         $this->persistenceManager->persistAll();
     } elseif ($redirect !== null && $isSame === true) {
         $this->outputRedirectLine('<comment>~~</comment>', $redirect);
         $this->outputLine();
         $this->outputLegend();
         $this->sendAndExit();
     }
     $redirects = $this->redirectStorage->addRedirect($source, $target, $statusCode, [$host]);
     $redirect = reset($redirects);
     $this->outputRedirectLine('<info>++</info>', $redirect);
     $this->outputLine();
     $this->outputLegend();
 }
 /**
  * Schedules a modified object for persistence.
  *
  * @param object $object The modified object
  * @return void
  * @throws IllegalObjectTypeException
  * @api
  */
 public function update($object)
 {
     if (!$object instanceof $this->objectType) {
         throw new IllegalObjectTypeException('The modified object given to update() was not of the type (' . $this->objectType . ') this repository manages.', 1249479625);
     }
     $this->persistenceManager->update($object);
 }
 /**
  * @param FinisherContext $finisherContext
  * @return void
  * @throws Exception
  */
 public function importSite(FinisherContext $finisherContext)
 {
     $formValues = $finisherContext->getFormRuntime()->getFormState()->getFormValues();
     if (isset($formValues['prune']) && intval($formValues['prune']) === 1) {
         $this->nodeDataRepository->removeAll();
         $this->workspaceRepository->removeAll();
         $this->domainRepository->removeAll();
         $this->siteRepository->removeAll();
         $this->persistenceManager->persistAll();
     }
     if (!empty($formValues['packageKey'])) {
         if ($this->packageManager->isPackageAvailable($formValues['packageKey'])) {
             throw new Exception(sprintf('The package key "%s" already exists.', $formValues['packageKey']), 1346759486);
         }
         $packageKey = $formValues['packageKey'];
         $siteName = $formValues['siteName'];
         $generatorService = $this->objectManager->get(\Neos\SiteKickstarter\Service\GeneratorService::class);
         $generatorService->generateSitePackage($packageKey, $siteName);
     } elseif (!empty($formValues['site'])) {
         $packageKey = $formValues['site'];
     }
     $this->deactivateOtherSitePackages($packageKey);
     $this->packageManager->activatePackage($packageKey);
     if (!empty($packageKey)) {
         try {
             $contentContext = $this->contextFactory->create(array('workspaceName' => 'live'));
             $this->siteImportService->importFromPackage($packageKey, $contentContext);
         } catch (\Exception $exception) {
             $finisherContext->cancel();
             $this->systemLogger->logException($exception);
             throw new SetupException(sprintf('Error: During the import of the "Sites.xml" from the package "%s" an exception occurred: %s', $packageKey, $exception->getMessage()), 1351000864);
         }
     }
 }
 /**
  * Generates a unique string for the given identifier according to $this->uriPattern.
  * If no UriPattern is set, the path segment is equal to the (URL-encoded) $identifier - otherwise a matching
  * ObjectPathMapping is fetched from persistence.
  * If no ObjectPathMapping exists for the given identifier, a new ObjectPathMapping is created.
  *
  * @param string $identifier the technical identifier of the object
  * @return string|integer the resolved path segment(s)
  * @throws InfiniteLoopException if no unique path segment could be found after 100 iterations
  */
 protected function getPathSegmentByIdentifier($identifier)
 {
     if ($this->getUriPattern() === '') {
         return rawurlencode($identifier);
     }
     $objectPathMapping = $this->objectPathMappingRepository->findOneByObjectTypeUriPatternAndIdentifier($this->objectType, $this->getUriPattern(), $identifier);
     if ($objectPathMapping !== null) {
         return $this->lowerCase ? strtolower($objectPathMapping->getPathSegment()) : $objectPathMapping->getPathSegment();
     }
     $object = $this->persistenceManager->getObjectByIdentifier($identifier, $this->objectType);
     $pathSegment = $uniquePathSegment = $this->createPathSegmentForObject($object);
     $pathSegmentLoopCount = 0;
     do {
         if ($pathSegmentLoopCount++ > 99) {
             throw new InfiniteLoopException('No unique path segment could be found after ' . ($pathSegmentLoopCount - 1) . ' iterations.', 1316441798);
         }
         if ($uniquePathSegment !== '') {
             $objectPathMapping = $this->objectPathMappingRepository->findOneByObjectTypeUriPatternAndPathSegment($this->objectType, $this->getUriPattern(), $uniquePathSegment, !$this->lowerCase);
             if ($objectPathMapping === null) {
                 $this->storeObjectPathMapping($uniquePathSegment, $identifier);
                 break;
             }
         }
         $uniquePathSegment = sprintf('%s-%d', $pathSegment, $pathSegmentLoopCount);
     } while (true);
     return $this->lowerCase ? strtolower($uniquePathSegment) : $uniquePathSegment;
 }
 /**
  * @param array $elements
  * @return FlowQuery
  */
 protected function createFlowQuery(array $elements)
 {
     $flowQuery = $this->getAccessibleMock(FlowQuery::class, ['dummy'], [$elements]);
     // Set up mock persistence manager to return dummy object identifiers
     $this->mockPersistenceManager = $this->createMock(PersistenceManagerInterface::class);
     $this->mockPersistenceManager->expects($this->any())->method('getIdentifierByObject')->will($this->returnCallback(function ($object) {
         if (isset($object->__identity)) {
             return $object->__identity;
         }
     }));
     $mockPersistenceManager = $this->mockPersistenceManager;
     $objectManager = $this->createMock(ObjectManagerInterface::class);
     $objectManager->expects($this->any())->method('get')->will($this->returnCallback(function ($className) use($mockPersistenceManager) {
         $instance = new $className();
         // Special case to inject the mock persistence manager into the filter operation
         if ($className === Operations\Object\FilterOperation::class) {
             ObjectAccess::setProperty($instance, 'persistenceManager', $mockPersistenceManager, true);
         }
         return $instance;
     }));
     $operationResolver = $this->getAccessibleMock(OperationResolver::class, ['dummy']);
     $operationResolver->_set('objectManager', $objectManager);
     $operationResolver->_set('finalOperationNames', ['count' => 'count', 'get' => 'get', 'is' => 'is', 'property' => 'property']);
     $operationResolver->_set('operations', ['count' => [300 => Operations\CountOperation::class], 'first' => [300 => Operations\FirstOperation::class], 'last' => [300 => Operations\LastOperation::class], 'slice' => [300 => Operations\SliceOperation::class], 'get' => [300 => Operations\GetOperation::class], 'is' => [300 => Operations\IsOperation::class], 'filter' => [300 => Operations\Object\FilterOperation::class], 'children' => [300 => Operations\Object\ChildrenOperation::class], 'property' => [300 => Operations\Object\PropertyOperation::class]]);
     $flowQuery->_set('operationResolver', $operationResolver);
     return $flowQuery;
 }
 /**
  * Checks the given token for validity and sets the token authentication status
  * accordingly (success, wrong credentials or no credentials given).
  *
  * @param TokenInterface $authenticationToken The token to be authenticated
  * @return void
  * @throws UnsupportedAuthenticationTokenException
  */
 public function authenticate(TokenInterface $authenticationToken)
 {
     if (!$authenticationToken instanceof UsernamePassword) {
         throw new UnsupportedAuthenticationTokenException('This provider cannot authenticate the given token.', 1217339840);
     }
     /** @var $account Account */
     $account = null;
     $credentials = $authenticationToken->getCredentials();
     if ($authenticationToken->getAuthenticationStatus() !== TokenInterface::AUTHENTICATION_SUCCESSFUL) {
         $authenticationToken->setAuthenticationStatus(TokenInterface::NO_CREDENTIALS_GIVEN);
     }
     if (!is_array($credentials) || !isset($credentials['username']) || !isset($credentials['password'])) {
         return;
     }
     $providerName = $this->name;
     $accountRepository = $this->accountRepository;
     $this->securityContext->withoutAuthorizationChecks(function () use($credentials, $providerName, $accountRepository, &$account) {
         $account = $accountRepository->findActiveByAccountIdentifierAndAuthenticationProviderName($credentials['username'], $providerName);
     });
     $authenticationToken->setAuthenticationStatus(TokenInterface::WRONG_CREDENTIALS);
     if ($account === null) {
         $this->hashService->validatePassword($credentials['password'], 'bcrypt=>$2a$14$DummySaltToPreventTim,.ingAttacksOnThisProvider');
         return;
     }
     if ($this->hashService->validatePassword($credentials['password'], $account->getCredentialsSource())) {
         $account->authenticationAttempted(TokenInterface::AUTHENTICATION_SUCCESSFUL);
         $authenticationToken->setAuthenticationStatus(TokenInterface::AUTHENTICATION_SUCCESSFUL);
         $authenticationToken->setAccount($account);
     } else {
         $account->authenticationAttempted(TokenInterface::WRONG_CREDENTIALS);
     }
     $this->accountRepository->update($account);
     $this->persistenceManager->whitelistObject($account);
 }
 /**
  * Returns the real object this proxy stands for
  *
  * @return object The "content object" as it was originally passed to the constructor
  */
 public function getObject()
 {
     if ($this->contentObject === null) {
         $this->contentObject = $this->persistenceManager->getObjectByIdentifier($this->targetId, $this->targetType);
     }
     return $this->contentObject;
 }
 /**
  * Finds an object from the repository by searching for its identity properties.
  *
  * @param array $identityProperties Property names and values to search for
  * @param string $type The object type to look for
  * @return object Either the object matching the identity or NULL if no object was found
  * @throws DuplicateObjectException if more than one object was found
  */
 protected function findObjectByIdentityProperties(array $identityProperties, $type)
 {
     $query = $this->persistenceManager->createQueryForType($type);
     $classSchema = $this->reflectionService->getClassSchema($type);
     $equals = [];
     foreach ($classSchema->getIdentityProperties() as $propertyName => $propertyType) {
         if (isset($identityProperties[$propertyName])) {
             if ($propertyType === 'string') {
                 $equals[] = $query->equals($propertyName, $identityProperties[$propertyName], false);
             } else {
                 $equals[] = $query->equals($propertyName, $identityProperties[$propertyName]);
             }
         }
     }
     if (count($equals) === 1) {
         $constraint = current($equals);
     } else {
         $constraint = $query->logicalAnd(current($equals), next($equals));
         while (($equal = next($equals)) !== false) {
             $constraint = $query->logicalAnd($constraint, $equal);
         }
     }
     $objects = $query->matching($constraint)->execute();
     $numberOfResults = $objects->count();
     if ($numberOfResults === 1) {
         return $objects->getFirst();
     } elseif ($numberOfResults === 0) {
         return null;
     } else {
         throw new DuplicateObjectException('More than one object was returned for the given identity, this is a constraint violation.', 1259612399);
     }
 }
 /**
  * Generate missing URI path segments
  *
  * This generates URI path segment properties for all document nodes which don't have
  * a path segment set yet.
  *
  * @param string $workspaceName
  * @param boolean $dryRun
  * @return void
  */
 public function generateUriPathSegments($workspaceName, $dryRun)
 {
     $baseContext = $this->createContext($workspaceName, []);
     $baseContextSitesNode = $baseContext->getNode(SiteService::SITES_ROOT_PATH);
     if (!$baseContextSitesNode) {
         $this->output->outputLine('<error>Could not find "' . SiteService::SITES_ROOT_PATH . '" root node</error>');
         return;
     }
     $baseContextSiteNodes = $baseContextSitesNode->getChildNodes();
     if ($baseContextSiteNodes === []) {
         $this->output->outputLine('<error>Could not find any site nodes in "' . SiteService::SITES_ROOT_PATH . '" root node</error>');
         return;
     }
     foreach ($this->dimensionCombinator->getAllAllowedCombinations() as $dimensionCombination) {
         $flowQuery = new FlowQuery($baseContextSiteNodes);
         $siteNodes = $flowQuery->context(['dimensions' => $dimensionCombination, 'targetDimensions' => []])->get();
         if (count($siteNodes) > 0) {
             $this->output->outputLine('Checking for nodes with missing URI path segment in dimension "%s"', array(trim(NodePaths::generateContextPath('', '', $dimensionCombination), '@;')));
             foreach ($siteNodes as $siteNode) {
                 $this->generateUriPathSegmentsForNode($siteNode, $dryRun);
             }
         }
     }
     $this->persistenceManager->persistAll();
 }
 /**
  * Forwards the request to another action and / or controller.
  *
  * Request is directly transferred to the other action / controller
  *
  * @param string $actionName Name of the action to forward to
  * @param string $controllerName Unqualified object name of the controller to forward to. If not specified, the current controller is used.
  * @param string $packageKey Key of the package containing the controller to forward to. May also contain the sub package, concatenated with backslash (Vendor.Foo\Bar\Baz). If not specified, the current package is assumed.
  * @param array $arguments Arguments to pass to the target action
  * @return void
  * @throws ForwardException
  * @see redirect()
  * @api
  */
 protected function forward($actionName, $controllerName = null, $packageKey = null, array $arguments = [])
 {
     $nextRequest = clone $this->request;
     $nextRequest->setControllerActionName($actionName);
     if ($controllerName !== null) {
         $nextRequest->setControllerName($controllerName);
     }
     if ($packageKey !== null && strpos($packageKey, '\\') !== false) {
         list($packageKey, $subpackageKey) = explode('\\', $packageKey, 2);
     } else {
         $subpackageKey = null;
     }
     if ($packageKey !== null) {
         $nextRequest->setControllerPackageKey($packageKey);
         $nextRequest->setControllerSubpackageKey($subpackageKey);
     }
     $regularArguments = [];
     foreach ($arguments as $argumentName => $argumentValue) {
         if (substr($argumentName, 0, 2) === '__') {
             $nextRequest->setArgument($argumentName, $argumentValue);
         } else {
             $regularArguments[$argumentName] = $argumentValue;
         }
     }
     $nextRequest->setArguments($this->persistenceManager->convertObjectsToIdentityArrays($regularArguments));
     $this->arguments->removeAll();
     $forwardException = new ForwardException();
     $forwardException->setNextRequest($nextRequest);
     throw $forwardException;
 }
 /**
  * After returning advice, generates the value hash for the object
  *
  * @param JoinPointInterface $joinPoint The current join point
  * @return void
  * @Flow\After("Neos\Flow\Persistence\Aspect\PersistenceMagicAspect->isNonEmbeddedValueObject && method(.*->__construct()) && filter(Neos\Flow\Persistence\Doctrine\Mapping\Driver\FlowAnnotationDriver)")
  */
 public function generateValueHash(JoinPointInterface $joinPoint)
 {
     $proxy = $joinPoint->getProxy();
     $proxyClassName = get_class($proxy);
     $hashSourceParts = [];
     $classSchema = $this->reflectionService->getClassSchema($proxyClassName);
     foreach ($classSchema->getProperties() as $property => $propertySchema) {
         // Currently, private properties are transient. Should this behaviour change, they need to be included
         // in the value hash generation
         if ($classSchema->isPropertyTransient($property) || $this->reflectionService->isPropertyPrivate($proxyClassName, $property)) {
             continue;
         }
         $propertyValue = ObjectAccess::getProperty($proxy, $property, true);
         if (is_object($propertyValue) === true) {
             // The persistence manager will return NULL if the given object is unknown to persistence
             $propertyValue = $this->persistenceManager->getIdentifierByObject($propertyValue) ?: $propertyValue;
         }
         $hashSourceParts[$property] = $propertyValue;
     }
     ksort($hashSourceParts);
     $hashSourceParts['__class_name__'] = $proxyClassName;
     $serializedSource = $this->useIgBinary === true ? igbinary_serialize($hashSourceParts) : serialize($hashSourceParts);
     $proxy = $joinPoint->getProxy();
     ObjectAccess::setProperty($proxy, 'Persistence_Object_Identifier', sha1($serializedSource), true);
 }
 /**
  * Sends the given HTTP request
  *
  * @param Http\Request $httpRequest
  * @return Http\Response
  * @throws Http\Exception
  * @api
  */
 public function sendRequest(Http\Request $httpRequest)
 {
     $requestHandler = $this->bootstrap->getActiveRequestHandler();
     if (!$requestHandler instanceof FunctionalTestRequestHandler) {
         throw new Http\Exception('The browser\'s internal request engine has only been designed for use within functional tests.', 1335523749);
     }
     $this->securityContext->clearContext();
     $this->validatorResolver->reset();
     $response = new Http\Response();
     $componentContext = new ComponentContext($httpRequest, $response);
     $requestHandler->setComponentContext($componentContext);
     $objectManager = $this->bootstrap->getObjectManager();
     $baseComponentChain = $objectManager->get(\Neos\Flow\Http\Component\ComponentChain::class);
     $componentContext = new ComponentContext($httpRequest, $response);
     try {
         $baseComponentChain->handle($componentContext);
     } catch (\Throwable $throwable) {
         $this->prepareErrorResponse($throwable, $componentContext->getHttpResponse());
     } catch (\Exception $exception) {
         $this->prepareErrorResponse($exception, $componentContext->getHttpResponse());
     }
     $session = $this->bootstrap->getObjectManager()->get(SessionInterface::class);
     if ($session->isStarted()) {
         $session->close();
     }
     $this->persistenceManager->clearState();
     return $componentContext->getHttpResponse();
 }
 /**
  * Convert an object from \Neos\Media\Domain\Model\ImageInterface to a json representation
  *
  * @param ImageInterface $source
  * @param string $targetType must be 'string'
  * @param array $convertedChildProperties
  * @param PropertyMappingConfigurationInterface $configuration
  * @return string|Error The converted Image, a Validation Error or NULL
  */
 public function convertFrom($source, $targetType, array $convertedChildProperties = array(), PropertyMappingConfigurationInterface $configuration = null)
 {
     $data = array('__identity' => $this->persistenceManager->getIdentifierByObject($source), '__type' => TypeHandling::getTypeForValue($source));
     if ($source instanceof ImageVariant) {
         $data['originalAsset'] = ['__identity' => $this->persistenceManager->getIdentifierByObject($source->getOriginalAsset())];
         $adjustments = array();
         foreach ($source->getAdjustments() as $adjustment) {
             $index = TypeHandling::getTypeForValue($adjustment);
             $adjustments[$index] = array();
             foreach (ObjectAccess::getGettableProperties($adjustment) as $propertyName => $propertyValue) {
                 $adjustments[$index][$propertyName] = $propertyValue;
             }
         }
         $data['adjustments'] = $adjustments;
     }
     return $data;
 }
 /**
  * @param object $object
  * @param string $parentIdentifier
  * @return array
  */
 protected function processObject($object, $parentIdentifier)
 {
     if (isset($this->classSchemata[get_class($object)]) && $this->classSchemata[get_class($object)]->isAggregateRoot() && !$this->persistenceManager->isNewObject($object)) {
         return ['identifier' => $this->persistenceSession->getIdentifierByObject($object)];
     } else {
         return ['identifier' => $this->persistObject($object, $parentIdentifier)];
     }
 }
 /**
  * Removes unused ImageVariants after a Node property changes to a different ImageVariant.
  * This is triggered via the nodePropertyChanged event.
  *
  * Note: This method it triggered by the "nodePropertyChanged" signal, @see \Neos\ContentRepository\Domain\Model\Node::emitNodePropertyChanged()
  *
  * @param NodeInterface $node the affected node
  * @param string $propertyName name of the property that has been changed/added
  * @param mixed $oldValue the property value before it was changed or NULL if the property is new
  * @param mixed $value the new property value
  * @return void
  */
 public function removeUnusedImageVariant(NodeInterface $node, $propertyName, $oldValue, $value)
 {
     if ($oldValue === $value || !$oldValue instanceof ImageVariant) {
         return;
     }
     $identifier = $this->persistenceManager->getIdentifierByObject($oldValue);
     $results = $this->nodeDataRepository->findNodesByRelatedEntities(array(ImageVariant::class => [$identifier]));
     // This case shouldn't happen as the query will usually find at least the node that triggered this call, still if there is no relation we can remove the ImageVariant.
     if ($results === []) {
         $this->assetRepository->remove($oldValue);
         return;
     }
     // If the result contains exactly the node that got a new ImageVariant assigned then we are safe to remove the asset here.
     if ($results === [$node->getNodeData()]) {
         $this->assetRepository->remove($oldValue);
     }
 }
 /**
  * @test
  */
 public function convertFromReturnsNullIfSpecifiedResourceCantBeFound()
 {
     $source = ['error' => \UPLOAD_ERR_NO_FILE, 'originallySubmittedResource' => ['__identity' => '79ecda60-1a27-69ca-17bf-a5d9e80e6c39']];
     $this->inject($this->resourceTypeConverter, 'persistenceManager', $this->mockPersistenceManager);
     $this->mockPersistenceManager->expects($this->once())->method('getObjectByIdentifier')->with('79ecda60-1a27-69ca-17bf-a5d9e80e6c39', PersistentResource::class)->will($this->returnValue(null));
     $actualResource = $this->resourceTypeConverter->convertFrom($source, PersistentResource::class);
     $this->assertNull($actualResource);
 }
 /**
  * Schedules a modified object for persistence.
  *
  * @param object $object The modified object
  * @throws IllegalObjectTypeException
  * @api
  */
 public function update($object)
 {
     if (!is_object($object) || !$object instanceof $this->entityClassName) {
         $type = is_object($object) ? get_class($object) : gettype($object);
         throw new IllegalObjectTypeException('The value given to update() was ' . $type . ' , however the ' . get_class($this) . ' can only store ' . $this->entityClassName . ' instances.', 1249479625);
     }
     $this->persistenceManager->update($object);
 }
 /**
  * Removes all routing cache entries for the given $nodeData
  *
  * @param NodeInterface $node
  * @return void
  */
 protected function flushRoutingCacheForNode(NodeInterface $node)
 {
     $nodeData = $node->getNodeData();
     $nodeDataIdentifier = $this->persistenceManager->getIdentifierByObject($nodeData);
     if ($nodeDataIdentifier === null) {
         return;
     }
     $this->routerCachingService->flushCachesByTag($nodeDataIdentifier);
 }
 /**
  * Remove given site all nodes for that site and all domains associated.
  *
  * @param Site $site
  * @return void
  */
 public function pruneSite(Site $site)
 {
     $siteNodePath = NodePaths::addNodePathSegment(static::SITES_ROOT_PATH, $site->getNodeName());
     $this->nodeDataRepository->removeAllInPath($siteNodePath);
     $siteNodes = $this->nodeDataRepository->findByPath($siteNodePath);
     foreach ($siteNodes as $siteNode) {
         $this->nodeDataRepository->remove($siteNode);
     }
     $site->setPrimaryDomain(null);
     $this->siteRepository->update($site);
     $domainsForSite = $this->domainRepository->findBySite($site);
     foreach ($domainsForSite as $domain) {
         $this->domainRepository->remove($domain);
     }
     $this->persistenceManager->persistAll();
     $this->siteRepository->remove($site);
     $this->emitSitePruned($site);
 }
 /**
  * @test
  */
 public function getCachedResolvedUriPathSkipsCacheIfRouteValuesContainObjectsThatCantBeConvertedToHashes()
 {
     $mockObject = new \stdClass();
     $routeValues = ['b' => 'route values', 'someObject' => $mockObject];
     $this->mockPersistenceManager->expects($this->once())->method('getIdentifierByObject')->with($mockObject)->will($this->returnValue(null));
     $this->mockResolveCache->expects($this->never())->method('has');
     $this->mockResolveCache->expects($this->never())->method('set');
     $this->routerCachingService->getCachedResolvedUriPath($routeValues);
 }
 /**
  * Checks if recently imported resources really have been persisted - and if not, removes its data from the
  * respective storage.
  *
  * @return void
  */
 public function shutdownObject()
 {
     /** @var PersistentResource $resource */
     foreach ($this->resourceRepository->getAddedResources() as $resource) {
         if ($this->persistenceManager->isNewObject($resource)) {
             $this->deleteResource($resource, false);
         }
     }
 }