/** * @dataProvider voteProvider */ public function testVote(Attribute $attribute, $repositoryCanUser, $expectedResult) { $voter = new ValueObjectVoter($this->repository); $targets = isset($attribute->limitations['targets']) ? $attribute->limitations['targets'] : null; $this->repository->expects($this->once())->method('canUser')->with($attribute->module, $attribute->function, $attribute->limitations['valueObject'], $targets)->will($this->returnValue($repositoryCanUser)); $this->assertSame($expectedResult, $voter->vote($this->getMock('Symfony\\Component\\Security\\Core\\Authentication\\Token\\TokenInterface'), new \stdClass(), array($attribute))); }
protected function sudo(Closure $callback) { $resolver = new OptionsResolver(); $this->configureOptions($resolver); $this->params = $resolver->resolve($this->params); return $this->repository->sudo($callback); }
/** * Detects if there is a custom controller to use to render a Location/Content. * * @param FilterControllerEvent $event * * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException */ public function getController(FilterControllerEvent $event) { $request = $event->getRequest(); // Only taking content related controller (i.e. ez_content:viewLocation or ez_content:viewContent) if (strpos($request->attributes->get('_controller'), 'ez_content:') === false) { return; } try { if ($request->attributes->has('locationId')) { $valueObject = $this->repository->getLocationService()->loadLocation($request->attributes->get('locationId')); } elseif ($request->attributes->get('location') instanceof Location) { $valueObject = $request->attributes->get('location'); $request->attributes->set('locationId', $valueObject->id); } elseif ($request->attributes->has('contentId')) { $valueObject = $this->repository->sudo(function (Repository $repository) use($request) { return $repository->getContentService()->loadContentInfo($request->attributes->get('contentId')); }); } elseif ($request->attributes->get('contentInfo') instanceof ContentInfo) { $valueObject = $request->attributes->get('contentInfo'); $request->attributes->set('contentId', $valueObject->id); } } catch (UnauthorizedException $e) { throw new AccessDeniedException(); } if (!isset($valueObject)) { $this->logger->error('Could not resolver a view controller, invalid value object to match.'); return; } $controllerReference = $this->controllerManager->getControllerReference($valueObject, $request->attributes->get('viewType')); if (!$controllerReference instanceof ControllerReference) { return; } $request->attributes->set('_controller', $controllerReference->controller); $event->setController($this->controllerResolver->getController($request)); }
/** * @return \eZ\Publish\API\Repository\Values\Content\Content */ public function getContent() { if ($this->content == null) { $this->content = $this->repository->getContentService()->loadContent($this->location->contentId); } return $this->content; }
/** * If user is logged-in in legacy_mode (e.g. legacy admin interface), * will inject currently logged-in user in the repository. * * @param GetResponseEvent $event */ public function onKernelRequest(GetResponseEvent $event) { /** @var \eZ\Publish\Core\MVC\ConfigResolverInterface $configResolver */ $request = $event->getRequest(); $session = $request->getSession(); if ($event->getRequestType() !== HttpKernelInterface::MASTER_REQUEST || !$this->configResolver->getParameter('legacy_mode') || !($session->isStarted() && $session->has('eZUserLoggedInID'))) { return; } try { $apiUser = $this->repository->getUserService()->loadUser($session->get('eZUserLoggedInID')); $this->repository->setCurrentUser($apiUser); $token = $this->tokenStorage->getToken(); if ($token instanceof TokenInterface) { $token->setUser(new User($apiUser)); // Don't embed if we already have a LegacyToken, to avoid nested session storage. if (!$token instanceof LegacyToken) { $this->tokenStorage->setToken(new LegacyToken($token)); } } } catch (NotFoundException $e) { // Invalid user ID, the user may have been removed => invalidate the token and the session. $this->tokenStorage->setToken(null); $session->invalidate(); } }
/** * Refreshes the user for the account interface. * * It is up to the implementation to decide if the user data should be * totally reloaded (e.g. from the database), or if the UserInterface * object can just be merged into some internal array of users / identity * map. * * @param \Symfony\Component\Security\Core\User\UserInterface $user * * @throws \Symfony\Component\Security\Core\Exception\UnsupportedUserException * * @return \Symfony\Component\Security\Core\User\UserInterface */ public function refreshUser(CoreUserInterface $user) { if (!$user instanceof UserInterface) { throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user))); } $this->repository->setCurrentUser($user->getAPIUser()); return $user; }
public function handleAction(Request $request) { $user = $this->userService->loadUserByCredentials($request->username, $request->password); $this->repository->setCurrentUser($user); $contentCreateStruct = $this->contentProvider->newContentCreateStructFromRequest($request); $locationCreateStruct = $this->contentProvider->newLocationCreateStructFromRequest($request); $content = $this->contentService->createContent($contentCreateStruct, array($locationCreateStruct)); $this->contentService->publishVersion($content->versionInfo); }
/** * @inheritdoc */ public function load($data) { $this->doProgress('Creating database schema...'); $this->databaseSchemaCreator->createSchema(); $this->doProgress('Loading fixtures...'); // Always use repositoty sudo to get access for content creation $this->repository->sudo(function () use($data) { $this->loader->load($data); }); }
/** * Gets content type identifier of field corresponding with the given node * * @param TreeNodeInterface $node * @return string */ public function getContentTypeIdentifier(TreeNodeInterface $node) { $parent = $node->getParent(); $fieldName = $parent->getName(); $grandPa = $parent->getParent()->getParent(); $contentTypeNode = $grandPa->getChildByName('content_type'); $contentType = $this->repository->getContentTypeService()->loadContentTypeByIdentifier($contentTypeNode->getValue()); $fieldDefinition = $contentType->getFieldDefinition($fieldName); return $fieldDefinition->fieldTypeIdentifier; }
/** * @dataProvider voteProvider */ public function testVote(Attribute $attribute, $repositoryCanUser, $expectedResult) { $voter = new CoreVoter($this->repository); if ($repositoryCanUser !== null) { $this->repository->expects($this->once())->method('hasAccess')->with($attribute->module, $attribute->function)->will($this->returnValue($repositoryCanUser)); } else { $this->repository->expects($this->never())->method('hasAccess'); } $this->assertSame($expectedResult, $voter->vote($this->getMock('Symfony\\Component\\Security\\Core\\Authentication\\Token\\TokenInterface'), new \stdClass(), array($attribute))); }
/** * Converts eZ Publish legacy objects and nodes to content and locations * * @param mixed $object * * @return mixed */ public function convert($object) { if ($object instanceof eZContentObject) { return $this->repository->getContentService()->loadContent($object->attribute('id')); } else { if ($object instanceof eZContentObjectTreeNode) { return $this->repository->getLocationService()->loadLocation($object->attribute('node_id')); } } return $object; }
/** * Saves content draft corresponding to $data. * Depending on the nature of $data (create or update data), the draft will either be created or simply updated. * * @param ContentStruct|\EzSystems\RepositoryForms\Data\User\UserCreateData $data * @param $languageCode * * @return \eZ\Publish\API\Repository\Values\Content\Content */ private function saveDraft(UserCreateData $data, $languageCode) { foreach ($data->fieldsData as $fieldDefIdentifier => $fieldData) { if ($fieldData->getFieldTypeIdentifier() !== 'ezuser') { $data->setField($fieldDefIdentifier, $fieldData->value, $languageCode); } } return $this->repository->sudo(function () use($data) { return $this->userService->createUser($data, $data->getParentGroups()); }); }
/** * Returns the vote for the given parameters. * * This method must return one of the following constants: * ACCESS_GRANTED, ACCESS_DENIED, or ACCESS_ABSTAIN. * * @param TokenInterface $token A TokenInterface instance * @param object $object The object to secure * @param array $attributes An array of attributes associated with the method being invoked * * @return integer either ACCESS_GRANTED, ACCESS_ABSTAIN, or ACCESS_DENIED */ public function vote(TokenInterface $token, $object, array $attributes) { foreach ($attributes as $attribute) { if ($this->supportsAttribute($attribute)) { if ($this->repository->hasAccess($attribute->module, $attribute->function) === false) { return VoterInterface::ACCESS_DENIED; } return VoterInterface::ACCESS_GRANTED; } } return VoterInterface::ACCESS_ABSTAIN; }
/** * Performs actions related to security once the legacy kernel has been built. * * @param PostBuildKernelEvent $event */ public function onKernelBuilt(PostBuildKernelEvent $event) { // Ignore if not in web context, if legacy_mode is active or if user is not authenticated if ($this->enabled === false || !$event->getKernelHandler() instanceof ezpWebBasedKernelHandler || $this->configResolver->getParameter('legacy_mode') === true || !$this->isUserAuthenticated()) { return; } $currentUser = $this->repository->getCurrentUser(); $event->getLegacyKernel()->runCallback(function () use($currentUser) { $legacyUser = eZUser::fetch($currentUser->id); eZUser::setCurrentlyLoggedInUser($legacyUser, $legacyUser->attribute('contentobject_id'), eZUser::NO_SESSION_REGENERATE); }, false, false); }
public function testAuthenticate() { $anonymousUserId = 10; $this->configResolver->expects($this->once())->method('getParameter')->with('anonymous_user_id')->will($this->returnValue($anonymousUserId)); $this->repository->expects($this->once())->method('setCurrentUser')->with(new UserReference($anonymousUserId)); $key = 'some_key'; $authProvider = new AnonymousAuthenticationProvider($key); $authProvider->setRepository($this->repository); $authProvider->setConfigResolver($this->configResolver); $anonymousToken = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Authentication\\Token\\AnonymousToken')->setConstructorArgs(array($key, $this->getMock('Symfony\\Component\\Security\\Core\\User\\UserInterface')))->getMockForAbstractClass(); $this->assertSame($anonymousToken, $authProvider->authenticate($anonymousToken)); }
public function loadLocation(ContentInfo $contentInfo) { if (is_null($contentInfo->mainLocationId)) { throw new NotFoundException('main location of content', $contentInfo->id); } try { return $this->repository->sudo(function (Repository $repository) use($contentInfo) { return $repository->getLocationService()->loadLocation($contentInfo->mainLocationId); }); } catch (Exception $e) { throw new NotFoundException('main location of content', $contentInfo->id); } }
/** * @param $login * @param $email * @param $firstName * @param $lastName * @return User */ public function createNewUser($login, $email, $firstName, $lastName) { $userService = $this->repository->getUserService(); $userCreateStruct = $userService->newUserCreateStruct($login, $email, md5($email . $login . time() . rand(1, 10000)), 'eng-GB', $this->repository->getContentTypeService()->loadContentTypeByIdentifier('user')); $userCreateStruct->setField('first_name', $firstName); $userCreateStruct->setField('last_name', $lastName); $user = $this->repository->sudo(function () use($userService, $userCreateStruct) { $userGroup = $userService->loadUserGroup('11'); // guest accounts return $userService->createUser($userCreateStruct, array($userGroup)); }); return $user; }
/** * Returns the vote for the given parameters. * Checks if user has access to a given action on a given value object. * * $attributes->limitations is a hash that contains: * - 'valueObject' - The ValueObject to check access on (eZ\Publish\API\Repository\Values\ValueObject). e.g. Location or Content. * - 'targets' - The location, parent or "assignment" value object, or an array of the same. * * This method must return one of the following constants: * ACCESS_GRANTED, ACCESS_DENIED, or ACCESS_ABSTAIN. * * @see \eZ\Publish\API\Repository\Repository::canUser() * * @param TokenInterface $token A TokenInterface instance * @param object $object The object to secure * @param array $attributes An array of attributes associated with the method being invoked * * @return integer either ACCESS_GRANTED, ACCESS_ABSTAIN, or ACCESS_DENIED */ public function vote(TokenInterface $token, $object, array $attributes) { foreach ($attributes as $attribute) { if ($this->supportsAttribute($attribute)) { $targets = isset($attribute->limitations['targets']) ? $attribute->limitations['targets'] : null; if ($this->repository->canUser($attribute->module, $attribute->function, $attribute->limitations['valueObject'], $targets) === false) { return VoterInterface::ACCESS_DENIED; } return VoterInterface::ACCESS_GRANTED; } } return VoterInterface::ACCESS_ABSTAIN; }
/** * Returns latest published content that is located under $pathString and matching $contentTypeIdentifier. * The whole subtree will be passed through to find content. * * @param \eZ\Publish\API\Repository\Values\Content\Location $rootLocation Root location we want to start content search from. * @param string[] $includeContentTypeIdentifiers Array of ContentType identifiers we want content to match. * @param \eZ\Publish\API\Repository\Values\Content\Query\Criterion $criterion Additional criterion for filtering. * @param int|null $limit Max number of items to retrieve. If not provided, default limit will be used. * * @return \eZ\Publish\API\Repository\Values\Content\Content[] */ public function getLatestContent(Location $rootLocation, array $includeContentTypeIdentifiers = array(), Criterion $criterion = null, $limit = null) { $criteria = array(new Criterion\Subtree($rootLocation->pathString), new Criterion\Visibility(Criterion\Visibility::VISIBLE)); if ($includeContentTypeIdentifiers) { $criteria[] = new Criterion\ContentTypeIdentifier($includeContentTypeIdentifiers); } if (!empty($criterion)) { $criteria[] = $criterion; } $query = new Query(array('criterion' => new Criterion\LogicalAnd($criteria), 'sortClauses' => array(new SortClause\DatePublished(Query::SORT_DESC)))); $query->limit = $limit ?: $this->defaultMenuLimit; return $this->searchHelper->buildListFromSearchResult($this->repository->getSearchService()->findContent($query)); }
public function getView(Location $location, $viewType) { if ($viewType !== 'full') { return null; } if ($location->getContentInfo()->sectionId !== $this->premiumSectionId) { return null; } if ($this->subscriptionChecker->userIsSubscriber($this->repository->getCurrentUser())) { return null; } return new ContentView("eZDemoBundle:{$viewType}:premium_content.html.twig"); }
public function userIsSubscriber(User $user) { $roleService = $this->repository->getRoleService(); return $this->repository->sudo(function (Repository $repository) use($user, $roleService) { foreach ($repository->getUserService()->loadUserGroupsOfUser($user) as $group) { foreach ($roleService->getRoleAssignmentsForUserGroup($group) as $role) { if ($this->isSubscriberRole($role->role)) { return true; } } } return false; }); }
/** * Refreshes the user for the account interface. * * It is up to the implementation to decide if the user data should be * totally reloaded (e.g. from the database), or if the UserInterface * object can just be merged into some internal array of users / identity * map. * * @param \Symfony\Component\Security\Core\User\UserInterface $user * * @throws \Symfony\Component\Security\Core\Exception\UnsupportedUserException * * @return \Symfony\Component\Security\Core\User\UserInterface */ public function refreshUser(CoreUserInterface $user) { if (!$user instanceof UserInterface) { throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user))); } try { $refreshedAPIUser = $this->repository->getUserService()->loadUser($user->getAPIUser()->id); $user->setAPIUser($refreshedAPIUser); $this->repository->setCurrentUser($refreshedAPIUser); return $user; } catch (NotFoundException $e) { throw new UsernameNotFoundException($e->getMessage(), 0, $e); } }
/** * If user is logged-in in legacy_mode (e.g. legacy admin interface), * will inject currently logged-in user in the repository. * * @param GetResponseEvent $event */ public function onKernelRequest(GetResponseEvent $event) { /** @var \eZ\Publish\Core\MVC\ConfigResolverInterface $configResolver */ $request = $event->getRequest(); if ($event->getRequestType() !== HttpKernelInterface::MASTER_REQUEST || !$this->configResolver->getParameter('legacy_mode') || !$request->getSession()->has('eZUserLoggedInID')) { return; } $apiUser = $this->repository->getUserService()->loadUser($request->getSession()->get('eZUserLoggedInID')); $this->repository->setCurrentUser($apiUser); $token = $this->securityContext->getToken(); if ($token instanceof TokenInterface) { $token->setUser(new User($apiUser)); $token->setAuthenticated(true); } }
/** * Tries to retrieve a valid eZ user if authenticated user doesn't come from the repository (foreign user provider). * Will dispatch an event allowing listeners to return a valid eZ user for current authenticated user. * Will by default let the repository load the anonymous user. * * @param \Symfony\Component\Security\Http\Event\InteractiveLoginEvent $event */ public function onInteractiveLogin(BaseInteractiveLoginEvent $event) { $token = $event->getAuthenticationToken(); $originalUser = $token->getUser(); if ($originalUser instanceof eZUser || !$originalUser instanceof UserInterface) { return; } /* * 1. Send the event. * 2. If no eZ user is returned, load Anonymous user. * 3. Inject eZ user in repository. * 4. Create the UserWrapped user object (implementing eZ UserInterface) with loaded eZ user. * 5. Create new token with UserWrapped user * 6. Inject the new token in security context */ $subLoginEvent = new InteractiveLoginEvent($event->getRequest(), $token); $this->eventDispatcher->dispatch(MVCEvents::INTERACTIVE_LOGIN, $subLoginEvent); if ($subLoginEvent->hasAPIUser()) { $apiUser = $subLoginEvent->getAPIUser(); } else { $apiUser = $this->repository->getUserService()->loadUser($this->configResolver->getParameter("anonymous_user_id")); } $this->repository->setCurrentUser($apiUser); $providerKey = method_exists($token, 'getProviderKey') ? $token->getProviderKey() : __CLASS__; $interactiveToken = new InteractiveLoginToken($this->getUser($originalUser, $apiUser), get_class($token), $token->getCredentials(), $providerKey, $token->getRoles()); $interactiveToken->setAttributes($token->getAttributes()); $this->securityContext->setToken($interactiveToken); }
private function mapContentCreateToUserCreate(RestContentCreateStruct $restContentCreateStruct) { $contentCreateStruct = $restContentCreateStruct->contentCreateStruct; $userCreateStruct = new UserCreateStruct(); $fields = array(); foreach ($contentCreateStruct->fields as $field) { // @todo fix hardcode user_account if ($field->value instanceof UserFieldValue) { $userCreateStruct->login = $field->value->login; $userCreateStruct->email = $field->value->email; $userCreateStruct->password = $field->value->passwordHash; $field->value->passwordHash = null; $foundUserField = true; } $userCreateStruct->fields[] = $field; } if (!isset($foundUserField)) { return false; } $properties = ['contentType', 'sectionId', 'ownerId', 'alwaysAvailable', 'remoteId', 'mainLanguageCode', 'modificationDate']; foreach ($properties as $property) { if (isset($contentCreateStruct->{$property})) { $userCreateStruct->{$property} = $contentCreateStruct->{$property}; } } $userGroup = $this->repository->getUserService()->loadUserGroup($restContentCreateStruct->locationCreateStruct->parentLocationId); return [$userCreateStruct, $userGroup]; }
/** * Creates an array of SPI location create structs from given array of API location create structs * * @throws \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException * * @param \eZ\Publish\API\Repository\Values\Content\LocationCreateStruct $locationCreateStruct * @param \eZ\Publish\API\Repository\Values\Content\Location $parentLocation * @param mixed $mainLocation * @param mixed $contentId * @param mixed $contentVersionNo * * @return \eZ\Publish\SPI\Persistence\Content\Location\CreateStruct */ public function buildSPILocationCreateStruct($locationCreateStruct, APILocation $parentLocation, $mainLocation, $contentId, $contentVersionNo) { if ($locationCreateStruct->priority !== null && !is_int($locationCreateStruct->priority)) { throw new InvalidArgumentValue("priority", $locationCreateStruct->priority, "LocationCreateStruct"); } if (!is_bool($locationCreateStruct->hidden)) { throw new InvalidArgumentValue("hidden", $locationCreateStruct->hidden, "LocationCreateStruct"); } if ($locationCreateStruct->remoteId !== null && (!is_string($locationCreateStruct->remoteId) || empty($locationCreateStruct->remoteId))) { throw new InvalidArgumentValue("remoteId", $locationCreateStruct->remoteId, "LocationCreateStruct"); } if ($locationCreateStruct->sortField !== null && !$this->isValidLocationSortField($locationCreateStruct->sortField)) { throw new InvalidArgumentValue("sortField", $locationCreateStruct->sortField, "LocationCreateStruct"); } if ($locationCreateStruct->sortOrder !== null && !$this->isValidLocationSortOrder($locationCreateStruct->sortOrder)) { throw new InvalidArgumentValue("sortOrder", $locationCreateStruct->sortOrder, "LocationCreateStruct"); } $remoteId = $locationCreateStruct->remoteId; if (null === $remoteId) { $remoteId = $this->getUniqueHash($locationCreateStruct); } else { try { $this->repository->getLocationService()->loadLocationByRemoteId($remoteId); throw new InvalidArgumentException("\$locationCreateStructs", "Another Location with remoteId '{$remoteId}' exists"); } catch (NotFoundException $e) { // Do nothing } } return new SPILocationCreateStruct(array("priority" => $locationCreateStruct->priority, "hidden" => $locationCreateStruct->hidden, "invisible" => $locationCreateStruct->hidden === true || $parentLocation->invisible, "remoteId" => $remoteId, "contentId" => $contentId, "contentVersion" => $contentVersionNo, "pathIdentificationString" => null, "mainLocationId" => $mainLocation, "sortField" => $locationCreateStruct->sortField !== null ? $locationCreateStruct->sortField : Location::SORT_FIELD_NAME, "sortOrder" => $locationCreateStruct->sortOrder !== null ? $locationCreateStruct->sortOrder : Location::SORT_ORDER_ASC, "parentId" => $locationCreateStruct->parentLocationId)); }
/** * Appends destination Content ids of given $fieldValue to the $relation array. * * If $fieldValue contains Location ids, the will be converted to the Content id that Location encapsulates. * * @param array $relations * @param array $locationIdToContentIdMapping An array with Location Ids as keys and corresponding Content Id as values * @param \eZ\Publish\SPI\FieldType\FieldType $fieldType * @param \eZ\Publish\Core\FieldType\Value $fieldValue Accepted field value. * @param string $fieldDefinitionId * * @return void */ public function appendFieldRelations(array &$relations, array &$locationIdToContentIdMapping, SPIFieldType $fieldType, BaseValue $fieldValue, $fieldDefinitionId) { foreach ($fieldType->getRelations($fieldValue) as $relationType => $destinationIds) { if ($relationType === Relation::FIELD) { if (!isset($relations[$relationType][$fieldDefinitionId])) { $relations[$relationType][$fieldDefinitionId] = array(); } $relations[$relationType][$fieldDefinitionId] += array_flip($destinationIds); } else { if ($relationType & (Relation::LINK | Relation::EMBED)) { if (!isset($relations[$relationType])) { $relations[$relationType] = array(); } if (isset($destinationIds["locationIds"])) { foreach ($destinationIds["locationIds"] as $locationId) { if (!isset($locationIdToContentIdMapping[$locationId])) { $location = $this->repository->getLocationService()->loadLocation($locationId); $locationIdToContentIdMapping[$locationId] = $location->contentId; } $relations[$relationType][$locationIdToContentIdMapping[$locationId]] = true; } } if (isset($destinationIds["contentIds"])) { $relations[$relationType] += array_flip($destinationIds["contentIds"]); } } } } }
/** * Builds the domain user object from provided persistence user object * * @param \eZ\Publish\SPI\Persistence\User $spiUser * @param \eZ\Publish\API\Repository\Values\Content\Content|null $content * * @return \eZ\Publish\API\Repository\Values\User\User */ protected function buildDomainUserObject(SPIUser $spiUser, APIContent $content = null) { if ($content === null) { $content = $this->repository->getContentService()->internalLoadContent($spiUser->id); } return new User(array('content' => $content, 'login' => $spiUser->login, 'email' => $spiUser->email, 'passwordHash' => $spiUser->passwordHash, 'hashAlgorithm' => (int) $spiUser->hashAlgorithm, 'enabled' => $spiUser->isEnabled, 'maxLogin' => (int) $spiUser->maxLogin)); }
/** * Publish the content type and update content objects. * * This method updates content objects, depending on the changed field definitions. * * @throws \eZ\Publish\API\Repository\Exceptions\BadStateException If the content type has no draft * @throws \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException If the content type has no field definitions * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the user is not allowed to publish a content type * * @param \eZ\Publish\API\Repository\Values\ContentType\ContentTypeDraft $contentTypeDraft */ public function publishContentTypeDraft(APIContentTypeDraft $contentTypeDraft) { if ($this->repository->hasAccess('class', 'update') !== true) { throw new UnauthorizedException('ContentType', 'update'); } try { $loadedContentTypeDraft = $this->loadContentTypeDraft($contentTypeDraft->id); } catch (APINotFoundException $e) { throw new BadStateException("\$contentTypeDraft", "The content type does not have a draft.", $e); } if (count($loadedContentTypeDraft->getFieldDefinitions()) === 0) { throw new InvalidArgumentException("\$contentTypeDraft", "The content type draft should have at least one field definition."); } $this->repository->beginTransaction(); try { if (empty($loadedContentTypeDraft->nameSchema)) { $fieldDefinitions = $loadedContentTypeDraft->getFieldDefinitions(); $this->contentTypeHandler->update($contentTypeDraft->id, $contentTypeDraft->status, $this->buildSPIContentTypeUpdateStruct($loadedContentTypeDraft, new ContentTypeUpdateStruct(array("nameSchema" => "<" . $fieldDefinitions[0]->identifier . ">")))); } $this->contentTypeHandler->publish($loadedContentTypeDraft->id); $this->repository->commit(); } catch (Exception $e) { $this->repository->rollback(); throw $e; } }
/** * Get ContentType by Content/ContentInfo. * * @param \eZ\Publish\API\Repository\Values\Content\Content|\eZ\Publish\API\Repository\Values\Content\ContentInfo $content * * @return \eZ\Publish\API\Repository\Values\ContentType\ContentType|null */ private function getContentType(ValueObject $content) { if ($content instanceof Content) { return $this->repository->getContentTypeService()->loadContentType($content->getVersionInfo()->getContentInfo()->contentTypeId); } elseif ($content instanceof ContentInfo) { return $this->repository->getContentTypeService()->loadContentType($content->contentTypeId); } }