code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
private function hasUncommittedEvents() { $reflector = new \ReflectionClass(EventSourcedAggregateRoot::class); $property = $reflector->getProperty('uncommittedEvents'); $property->setAccessible(true); $uncommittedEvents = $property->getValue($this); return !empty($uncommittedEvents); }
Use reflection to get check if the aggregate has uncommitted events. @return bool
public static function importFromUDB2( $actorId, $cdbXml, $cdbXmlNamespaceUri ) { $organizer = new static(); $organizer->apply( new OrganizerImportedFromUDB2( $actorId, $cdbXml, $cdbXmlNamespaceUri ) ); return $organizer; }
Import from UDB2. @param string $actorId The actor id. @param string $cdbXml The cdb xml. @param string $cdbXmlNamespaceUri The cdb xml namespace uri. @return Organizer The actor.
public static function create( $id, Language $mainLanguage, Url $website, Title $title ) { $organizer = new self(); $organizer->apply( new OrganizerCreatedWithUniqueWebsite($id, $mainLanguage, $website, $title) ); return $organizer; }
Factory method to create a new Organizer. @param string $id @param Language $mainLanguage @param Url $website @param Title $title @return Organizer
protected function applyOrganizerCreated(OrganizerCreated $organizerCreated) { $this->actorId = $organizerCreated->getOrganizerId(); $this->mainLanguage = new Language('nl'); $this->setTitle($organizerCreated->getTitle(), $this->mainLanguage); }
Apply the organizer created event. @param OrganizerCreated $organizerCreated
protected function applyOrganizerCreatedWithUniqueWebsite(OrganizerCreatedWithUniqueWebsite $organizerCreated) { $this->actorId = $organizerCreated->getOrganizerId(); $this->mainLanguage = $organizerCreated->getMainLanguage(); $this->website = $organizerCreated->getWebsite(); $this->setTitle($organizerCreated->getTitle(), $this->mainLanguage); }
Apply the organizer created event. @param OrganizerCreatedWithUniqueWebsite $organizerCreated
public function handle($command) { $method = $this->getHandleMethod($command); if (! method_exists($this, $method)) { return; } $parameter = new \ReflectionParameter(array($this, $method), 0); $expectedClass = $parameter->getClass(); if ($expectedClass->getName() == get_class($command)) { $this->$method($command); } }
{@inheritDoc}
public static function fromJSONLDEvent($eventString) { $event = json_decode($eventString); foreach ($event->terms as $term) { if ($term->domain == self::DOMAIN) { return new self($term->id, $term->label); } } return null; }
Creates a new EventType object from a JSON-LD encoded event. @param string $eventString The cultural event encoded as JSON-LD @return self|null
public static function deserialize(array $data) { return new static( new UUID($data[self::UUID]), new UUID($data[self::LABEL_ID]) ); }
{@inheritdoc}
protected function applyPlaceImportedFromUDB2(PlaceImportedFromUDB2 $place) { // No relation exists in UDB2. $placeId = $place->getActorId(); $this->storeRelations($placeId, null); }
Store the relation for places imported from UDB2.
protected function applyPlaceDeleted(PlaceDeleted $place) { $placeId = $place->getItemId(); $this->repository->removeRelations($placeId); }
Delete the relations.
public static function create( UUID $id, MIMEType $mimeType, StringLiteral $description, StringLiteral $copyrightHolder, Url $sourceLocation, Language $language ) { $mediaObject = new self(); $mediaObject->apply( new MediaObjectCreated( $id, $mimeType, $description, $copyrightHolder, $sourceLocation, $language ) ); return $mediaObject; }
@param UUID $id @param MIMEType $mimeType @param StringLiteral $description @param StringLiteral $copyrightHolder @param Url $sourceLocation @param Language $language @return MediaObject
public function search(array $params) { foreach ($this->filters as $filter) { $params = $filter->apply($params); } return $this->filteredSearchService->search($params); }
{@inheritdoc}
public static function deserialize(array $data) { $labels = new Labels(); foreach ($data['labels'] as $label) { $labels = $labels->with(new Label( new LabelName($label['label']), $label['visibility'] )); } return new static( $data['organizer_id'], $labels ); }
{@inheritdoc}
public function serialize() { $labels = []; foreach ($this->getLabels() as $label) { /** @var Label $label */ $labels[] = [ 'label' => $label->getName()->toString(), 'visibility' => $label->isVisible(), ]; } return parent::serialize() + [ 'labels' => $labels, ]; }
{@inheritdoc}
public static function map() { return [ OrganizerCreated::class => 'application/vnd.cultuurnet.udb3-events.organizer-created+json', OrganizerCreatedWithUniqueWebsite::class => 'application/vnd.cultuurnet.udb3-events.organizer-created-with-unique-website+json', OrganizerDeleted::class => 'application/vnd.cultuurnet.udb3-events.organizer-deleted+json', OrganizerImportedFromUDB2::class => 'application/vnd.cultuurnet.udb3-events.organizer-imported-from-udb2+json', OrganizerUpdatedFromUDB2::class => 'application/vnd.cultuurnet.udb3-events.organizer-updated-from-udb2+json', OrganizerProjectedToJSONLD::class => 'application/vnd.cultuurnet.udb3-events.organizer-projected-to-jsonld+json', WebsiteUpdated::class => 'application/vnd.cultuurnet.udb3-events.organizer-website-updated+json', TitleUpdated::class => 'application/vnd.cultuurnet.udb3-events.organizer-title-updated+json', TitleTranslated::class => 'application/vnd.cultuurnet.udb3-events.organizer-title-translated+json', LabelAdded::class => 'application/vnd.cultuurnet.udb3-events.organizer-label-added+json', LabelRemoved::class => 'application/vnd.cultuurnet.udb3-events.organizer-label-removed+json', AddressUpdated::class => 'application/vnd.cultuurnet.udb3-events.organizer-address-updated+json', AddressTranslated::class => 'application/vnd.cultuurnet.udb3-events.organizer-address-translated+json', ContactPointUpdated::class => 'application/vnd.cultuurnet.udb3-events.organizer-contact-point-updated+json', ]; }
@return array @todo once we upgrade to PHP 5.6+ this can be moved to a constant.
public function handle($command) { $commandName = get_class($command); $commandHandlers = $this->getCommandHandlers(); if (isset($commandHandlers[$commandName])) { $handler = $commandHandlers[$commandName]; call_user_func(array($this, $handler), $command); } else { parent::handle($command); } }
{@inheritdoc}
public function handleAddImage(AbstractAddImage $addImage) { $offer = $this->load($addImage->getItemId()); $image = $this->mediaManager->getImage($addImage->getImageId()); $offer->addImage($image); $this->offerRepository->save($offer); }
Handle an add image command. @param AbstractAddImage $addImage
public function handleUpdateDescription(AbstractUpdateDescription $updateDescription) { $offer = $this->load($updateDescription->getItemId()); $offer->updateDescription( $updateDescription->getDescription(), $updateDescription->getLanguage() ); $this->offerRepository->save($offer); }
Handle the update of description on a place. @param AbstractUpdateDescription $updateDescription
public function handleUpdateTypicalAgeRange(AbstractUpdateTypicalAgeRange $updateTypicalAgeRange) { $offer = $this->load($updateTypicalAgeRange->getItemId()); $offer->updateTypicalAgeRange( $updateTypicalAgeRange->getTypicalAgeRange() ); $this->offerRepository->save($offer); }
Handle the update of typical age range on a place. @param AbstractUpdateTypicalAgeRange $updateTypicalAgeRange
public function handleDeleteTypicalAgeRange(AbstractDeleteTypicalAgeRange $deleteTypicalAgeRange) { $offer = $this->load($deleteTypicalAgeRange->getItemId()); $offer->deleteTypicalAgeRange(); $this->offerRepository->save($offer); }
Handle the deletion of typical age range on a place. @param AbstractDeleteTypicalAgeRange $deleteTypicalAgeRange
public function handleUpdateOrganizer(AbstractUpdateOrganizer $updateOrganizer) { $offer = $this->load($updateOrganizer->getItemId()); $this->loadOrganizer($updateOrganizer->getOrganizerId()); $offer->updateOrganizer( $updateOrganizer->getOrganizerId() ); $this->offerRepository->save($offer); }
Handle an update command to update organizer of a place. @param AbstractUpdateOrganizer $updateOrganizer
public function handleDeleteOrganizer(AbstractDeleteOrganizer $deleteOrganizer) { $offer = $this->load($deleteOrganizer->getItemId()); $offer->deleteOrganizer( $deleteOrganizer->getOrganizerId() ); $this->offerRepository->save($offer); }
Handle an update command to delete the organizer. @param AbstractDeleteOrganizer $deleteOrganizer
public function handleUpdateContactPoint(AbstractUpdateContactPoint $updateContactPoint) { $offer = $this->load($updateContactPoint->getItemId()); $offer->updateContactPoint( $updateContactPoint->getContactPoint() ); $this->offerRepository->save($offer); }
Handle an update command to updated the contact point. @param AbstractUpdateContactPoint $updateContactPoint
public function handleUpdateBookingInfo(AbstractUpdateBookingInfo $updateBookingInfo) { $offer = $this->load($updateBookingInfo->getItemId()); $offer->updateBookingInfo( $updateBookingInfo->getBookingInfo() ); $this->offerRepository->save($offer); }
Handle an update command to updated the booking info. @param AbstractUpdateBookingInfo $updateBookingInfo
private function polyFillMultilingualFields(JsonDocument $jsonDocument) { $body = $jsonDocument->getBody(); $mainLanguage = isset($body->mainLanguage) ? $body->mainLanguage : 'nl'; if (isset($body->address->streetAddress)) { $body->address = (object) [ $mainLanguage => $body->address, ]; } if (isset($body->bookingInfo->urlLabel) && is_string($body->bookingInfo->urlLabel)) { $body->bookingInfo->urlLabel = (object) [ $mainLanguage => $body->bookingInfo->urlLabel, ]; } if (isset($body->priceInfo) && is_array($body->priceInfo) && is_string($body->priceInfo[0]->name)) { foreach ($body->priceInfo as $priceInfo) { $priceInfo->name = (object) [ $mainLanguage => $priceInfo->name, ]; } } return $jsonDocument->withBody($body); }
@todo Remove when full replay is done. @replay_i18n @see https://jira.uitdatabank.be/browse/III-2201 @param JsonDocument $jsonDocument @return JsonDocument
public function serialize() { $facilities = array(); foreach ($this->facilities as $facility) { $facilities[] = $facility->serialize(); } return parent::serialize() + array( 'facilities' => $facilities, ); }
{@inheritdoc}
public function remove($uuid) { $q = $this->connection->createQueryBuilder(); $expr = $this->connection->getExpressionBuilder(); $q ->delete($this->tableName->toNative()) ->where($expr->eq(SchemaConfigurator::UUID_COLUMN, ':role_id')) ->setParameter('role_id', $uuid); $q->execute(); }
{@inheritdoc}
public function save($uuid, $name, $constraint = null) { $q = $this->connection->createQueryBuilder(); $q ->insert($this->tableName->toNative()) ->values( [ SchemaConfigurator::UUID_COLUMN => ':role_id', SchemaConfigurator::NAME_COLUMN => ':role_name', SchemaConfigurator::CONSTRAINT_COLUMN => ':constraint', ] ) ->setParameter('role_id', $uuid) ->setParameter('role_name', $name) ->setParameter('constraint', $constraint); $q->execute(); }
{@inheritdoc}
public function search($query = '', $limit = 10, $start = 0) { $q = $this->connection->createQueryBuilder(); $expr = $this->connection->getExpressionBuilder(); // Results. $q ->select('uuid', 'name') ->from($this->tableName->toNative()) ->orderBy('name', 'ASC') ->setMaxResults($limit) ->setFirstResult($start); if (!empty($query)) { $q->where($expr->like('name', ':role_name')); $q->setParameter('role_name', '%' . $query . '%'); } $results = $q->execute()->fetchAll(\PDO::FETCH_ASSOC); //Total. $q = $this->connection->createQueryBuilder(); $q ->resetQueryParts() ->select('COUNT(*) AS total') ->from($this->tableName->toNative()); if (!empty($query)) { $q->where($expr->like('name', ':role_name')); $q->setParameter('role_name', '%' . $query . '%'); } $total = $q->execute()->fetchColumn(); return new Results($limit, $results, $total); }
{@inheritdoc}
public function updateName($uuid, $name) { $q = $this->connection->createQueryBuilder(); $expr = $this->connection->getExpressionBuilder(); $q ->update($this->tableName->toNative()) ->where($expr->eq(SchemaConfigurator::UUID_COLUMN, ':role_id')) ->set(SchemaConfigurator::UUID_COLUMN, ':role_id') ->set(SchemaConfigurator::NAME_COLUMN, ':role_name') ->setParameter('role_id', $uuid) ->setParameter('role_name', $name); $q->execute(); }
{@inheritdoc}
public function updateConstraint($uuid, $constraint = null) { $q = $this->connection->createQueryBuilder(); $expr = $this->connection->getExpressionBuilder(); $q ->update($this->tableName->toNative()) ->where($expr->eq(SchemaConfigurator::UUID_COLUMN, ':role_id')) ->set(SchemaConfigurator::UUID_COLUMN, ':role_id') ->set(SchemaConfigurator::CONSTRAINT_COLUMN, ':constraint') ->setParameter('role_id', $uuid) ->setParameter('constraint', $constraint); $q->execute(); }
{@inheritdoc}
protected function prepareLoadStatement() { $queryBuilder = $this->connection->createQueryBuilder(); $queryBuilder->select('id', 'uuid', 'playhead', 'metadata', 'payload', 'recorded_on') ->from($this->tableName) ->where('id >= :startid') ->setParameter('startid', $this->startId) ->orderBy('id', 'ASC') ->setMaxResults(1); if ($this->cdbids) { $queryBuilder->andWhere('uuid IN (:uuids)') ->setParameter('uuids', $this->cdbids, Connection::PARAM_STR_ARRAY); } if (!empty($this->aggregateType)) { $queryBuilder->andWhere('aggregate_type = :aggregate_type'); $queryBuilder->setParameter('aggregate_type', $this->aggregateType); } return $queryBuilder->execute(); }
The load statement can no longer be 'cached' because of using the query builder. The query builder requires all parameters to be set before using the execute command. The previous solution used the prepare statement on the connection, this did not require all parameters to be set up front. @return Statement @throws DBALException
public static function createPlace( $id, Language $mainLanguage, Title $title, EventType $eventType, Address $address, CalendarInterface $calendar, Theme $theme = null, DateTimeImmutable $publicationDate = null ) { $place = new self(); $place->apply(new PlaceCreated( $id, $mainLanguage, $title, $eventType, $address, $calendar, $theme, $publicationDate )); return $place; }
Factory method to create a new Place. @todo Refactor this method so it can be called create. Currently the normal behavior for create is taken by the legacy udb2 logic. The PlaceImportedFromUDB2 could be a superclass of Place. @param string $id @param Language $mainLanguage @param Title $title @param EventType $eventType @param Address $address @param CalendarInterface $calendar @param Theme|null $theme @param DateTimeImmutable|null $publicationDate @return self
protected function applyPlaceCreated(PlaceCreated $placeCreated) { $this->mainLanguage = $placeCreated->getMainLanguage(); $this->titles[$this->mainLanguage->getCode()] = $placeCreated->getTitle(); $this->calendar = $placeCreated->getCalendar(); $this->contactPoint = new ContactPoint(); $this->bookingInfo = new BookingInfo(); $this->typeId = $placeCreated->getEventType()->getId(); $this->themeId = $placeCreated->getTheme() ? $placeCreated->getTheme()->getId() : null; $this->addresses[$this->mainLanguage->getCode()] = $placeCreated->getAddress(); $this->placeId = $placeCreated->getPlaceId(); $this->workflowStatus = WorkflowStatus::DRAFT(); }
Apply the place created event. @param PlaceCreated $placeCreated
public function updateMajorInfo( Title $title, EventType $eventType, Address $address, CalendarInterface $calendar, Theme $theme = null ) { $this->apply( new MajorInfoUpdated( $this->placeId, $title, $eventType, $address, $calendar, $theme ) ); }
Update the major info. @param Title $title @param EventType $eventType @param Address $address @param CalendarInterface $calendar @param Theme $theme
public static function importFromUDB2Actor( $actorId, $cdbXml, $cdbXmlNamespaceUri ) { $place = new static(); $place->apply( new PlaceImportedFromUDB2( $actorId, $cdbXml, $cdbXmlNamespaceUri ) ); return $place; }
Import from UDB2. @param string $actorId The actor id. @param string $cdbXml The cdb xml. @param string $cdbXmlNamespaceUri The cdb xml namespace uri. @return Place
public function filter($string) { // Add one newline after each break tag. $string = $this->setNewlinesAfterClosingTags($string, 'br', 1, true); // Add two newlines after each closing paragraph tag. $string = $this->setNewlinesAfterClosingTags($string, 'p', 2); // Decode all HTML entities, like &, so they are human-readable. $string = html_entity_decode($string); // Strip all HTML tags. $string = strip_tags($string); // Remove any excessive consecutive newlines. $string = $this->limitConsecutiveNewlines($string, 2); // Trim any whitespace or newlines from the start and/or end of the string. $string = trim($string); return $string; }
{@inheritdoc}
protected function limitConsecutiveNewlines($string, $limit = 2) { // Pattern that finds any consecutive newlines that exceed the allowed limit. $exceeded = $limit + 1; $pattern = '/((\\n){' . $exceeded . ',})/'; // Create a string with the maximum number of allowed newlines. $newlines = ''; for ($i = 0; $i < $limit; $i++) { $newlines .= PHP_EOL; } // Find each match and replace it with the maximum number of newlines. return preg_replace($pattern, $newlines, $string); }
Restricts the number of consecutive newlines in a specific string. @param string $string String to limit consecutive newlines in. @param int $limit Limit of consecutive newlines. (Defaults to 2.) @return string Processed string.
public static function fromSubtype($subtypeString) { if (false === \is_string($subtypeString)) { throw new InvalidNativeArgumentException($subtypeString, array('string')); } $typeSupported = array_key_exists($subtypeString, self::$supportedSubtypes); if (!$typeSupported) { throw new UnsupportedMIMETypeException('MIME type "' . $subtypeString . '" is not supported!'); } $type = self::$supportedSubtypes[$subtypeString]; return new static($type . '/' . $subtypeString); }
@param string $subtypeString @throws UnsupportedMIMETypeException @return MIMEType
public function enrich(Metadata $metadata) { if ($this->metadata) { return $metadata->merge($this->metadata); } else { return $metadata; } }
{@inheritdoc}
public function getEntity($id) { /** @var JsonDocument $document */ $document = $this->documentRepository->get($id); if (!$document) { // If the read model is not initialized yet, try to load // the entity, which will initialize the read model. try { $this->entityRepository->load($id); } catch (AggregateNotFoundException $e) { throw new EntityNotFoundException( sprintf('Entity with id: %s not found.', $id) ); } /** @var JsonDocument $document */ $document = $this->documentRepository->get($id); if (!$document) { throw new EntityNotFoundException( sprintf('Entity with id: %s not found.', $id) ); } } return $document->getRawBody(); }
{@inheritdoc}
protected function applyMajorInfoUpdated(MajorInfoUpdated $majorInfoUpdated) { $document = $this ->loadPlaceDocumentFromRepositoryById($majorInfoUpdated->getPlaceId()) ->apply(OfferUpdate::calendar($majorInfoUpdated->getCalendar())); $jsonLD = $document->getBody(); $jsonLD->name->{$this->getMainLanguage($jsonLD)->getCode()} = $majorInfoUpdated->getTitle(); $this->setAddress( $jsonLD, $majorInfoUpdated->getAddress(), $this->getMainLanguage($jsonLD) ); $availableTo = AvailableTo::createFromCalendar($majorInfoUpdated->getCalendar()); $jsonLD->availableTo = (string)$availableTo; // Remove old theme and event type. $jsonLD->terms = array_filter($jsonLD->terms, function ($term) { return $term->domain !== EventType::DOMAIN && $term->domain !== Theme::DOMAIN; }); $eventType = $majorInfoUpdated->getEventType(); $jsonLD->terms = [ $eventType->toJsonLd(), ]; $theme = $majorInfoUpdated->getTheme(); if (!empty($theme)) { $jsonLD->terms[] = $theme->toJsonLd(); } // Remove geocoordinates, because the address might have been // updated and we might get inconsistent data if it takes a while // before the new geocoordinates are added. // In case geocoding fails, it's also easier to look for places that // have no geocoordinates instead of places that have incorrect // geocoordinates. unset($jsonLD->geo); return $document->withBody($jsonLD); }
Apply the major info updated command to the projector. @param MajorInfoUpdated $majorInfoUpdated @return JsonDocument
public function create( UUID $id, MIMEType $fileType, StringLiteral $description, StringLiteral $copyrightHolder, Url $sourceLocation, Language $language ) { try { $existingMediaObject = $this->repository->load($id); $this->logger->info('Trying to create media with id: ' .$id . ' but it already exists. Using existing Media Object!'); return $existingMediaObject; } catch (AggregateNotFoundException $exception) { $this->logger->info('No existing media with id: ' .$id . ' found. Creating a new Media Object!'); } $mediaObject = MediaObject::create( $id, $fileType, $description, $copyrightHolder, $sourceLocation, $language ); $this->repository->save($mediaObject); return $mediaObject; }
{@inheritdoc}
public function handleUploadImage(UploadImage $uploadImage) { $pathParts = explode('/', $uploadImage->getFilePath()); $fileName = array_pop($pathParts); $fileNameParts = explode('.', $fileName); $extension = StringLiteral::fromNative(array_pop($fileNameParts)); $destinationPath = $this->pathGenerator->path( $uploadImage->getFileId(), $extension ); $destinationIri = $this->iriGenerator->iri($destinationPath); $this->filesystem->rename( $uploadImage->getFilePath(), $this->mediaDirectory . '/' . $destinationPath ); $this->create( $uploadImage->getFileId(), $uploadImage->getMimeType(), $uploadImage->getDescription(), $uploadImage->getCopyrightHolder(), Url::fromNative($destinationIri), $uploadImage->getLanguage() ); $jobInfo = ['file_id' => (string) $uploadImage->getFileId()]; $this->logger->info('job_info', $jobInfo); }
{@inheritdoc}
public function get(UUID $fileId) { try { $mediaObject = $this->repository->load((string) $fileId); } catch (AggregateNotFoundException $e) { throw new MediaObjectNotFoundException( sprintf("Media object with id '%s' not found", $fileId), 0, $e ); } return $mediaObject; }
{@inheritdoc}
private function getUiTIDSavedSearchRepository() { $metadata = $this->metadata->serialize(); $tokenCredentials = $metadata['uitid_token_credentials']; $savedSearchesService = $this->savedSearchesServiceFactory->withTokenCredentials($tokenCredentials); $repository = new UiTIDSavedSearchRepository($savedSearchesService); if ($this->logger) { $repository->setLogger($this->logger); } return $repository; }
Should be called inside the handle methods and not inside the constructor, because the metadata property is set or overwritten right before a handle method is called. @return UiTIDSavedSearchRepository
private function guardValidnessWithJSONSchema($json) { // @todo JSON-SCHEMA inside swagger.json should be reused here $schema = json_decode('{ "type": "object", "properties": { "description": { "type": "string" } }, "required": [ "description" ], "additionalProperties": false }'); $validator = new Validator(); $validator->check($json, $schema); if (!$validator->isValid()) { $errors = $validator->getErrors(); $errorMessages = $this->getErrorMessages($errors); throw new ValidationException($errorMessages); } }
@param mixed $json @throws ValidationException
private function createChronologicalTimestamp(DateTimeInterface $start, DateTimeInterface $end) { $startDate = Chronos::instance($start); $endDate = Chronos::instance($end); if ($startDate->isSameDay($endDate) && $endDate->lt($startDate)) { $endDate = $endDate->addDay(); } if ($endDate->lt($startDate)) { $endDate = $startDate; } return new Timestamp($startDate, $endDate); }
End date might be before start date in cdbxml when event takes place between e.g. 9 PM and 3 AM (the next day). To keep the dates chronological we push the end to the next day. If the end dates does not make any sense at all, it is forced to the start date. @param DateTimeInterface $start @param DateTimeInterface $end @return Timestamp
protected function applyOrganizerProjectedToJSONLD( OrganizerProjectedToJSONLD $organizerProjectedToJSONLD ) { $placeIds = $this->placeRelations->getPlacesOrganizedByOrganizer( $organizerProjectedToJSONLD->getId() ); $organizer = $this->organizerService->getEntity( $organizerProjectedToJSONLD->getId() ); $organizerJSONLD = json_decode($organizer); foreach ($placeIds as $placeId) { $this->updateEmbeddedOrganizer($placeId, $organizerJSONLD); } }
@param OrganizerProjectedToJSONLD $organizerProjectedToJSONLD @throws \CultuurNet\UDB3\EntityNotFoundException
public function createEvent( Language $mainLanguage, Title $title, EventType $eventType, Location $location, CalendarInterface $calendar, $theme = null ) { $eventId = $this->uuidGenerator->generate(); $event = Event::create( $eventId, $mainLanguage, $title, $eventType, $location, $calendar, $theme, $this->publicationDate ); $this->writeRepository->save($event); return $eventId; }
{@inheritdoc}
public function updateMajorInfo($eventId, Title $title, EventType $eventType, Location $location, CalendarInterface $calendar, $theme = null) { $this->guardId($eventId); return $this->commandBus->dispatch( new UpdateMajorInfo($eventId, $title, $eventType, $location, $calendar, $theme) ); }
{@inheritdoc}
public function search(string $query, $limit = 30, $start = 0, $sort = null) { if ($query == '*.*' && $limit == 30 && $start == 0 && $sort == 'lastupdated desc') { $result = $this->fetchFromCache(); if (null === $result) { $result = $this->search->search($query, $limit, $start, $sort); $this->saveToCache($result); } return $result; } else { return $this->search->search($query, $limit, $start, $sort); } }
Find UDB3 data based on an arbitrary query. @param string $query An arbitrary query. @param int $limit How many items to retrieve. @param int $start Offset to start from. @return array|\JsonSerializable A JSON-LD array or JSON serializable object.
public function handle(DomainMessage $domainMessage) { $event = $domainMessage->getPayload(); $eventName = get_class($event); $eventHandlers = $this->getEventHandlers(); if (isset($eventHandlers[$eventName])) { $handler = $eventHandlers[$eventName]; call_user_func(array($this, $handler), $event, $domainMessage); } else { $this->handleUnknownEvents($domainMessage); } }
{@inheritdoc}
public function editDescription(Description $description) { $this->guardNotDeleted(); if ($description !== $this->description) { $this->apply(new DescriptionEdited($this->id, $description)); } }
@param Description $description @throws AggregateDeletedException
private function identifyParent(DomainMessage $message) { /** @var AggregateCopiedEventInterface $domainEvent */ $domainEvent = $message->getPayload(); if (!$domainEvent instanceof AggregateCopiedEventInterface) { throw new UnknownParentAggregateException(); } return $domainEvent->getParentAggregateId(); }
@param DomainMessage $message @return string @throws UnknownParentAggregateException
private function limitEventStreamToPlayhead(DomainEventStreamInterface $eventStream, $playhead) { return array_filter( iterator_to_array($eventStream), function (DomainMessage $message) use ($playhead) { return intval($message->getPlayhead()) < $playhead; } ); }
@param DomainEventStreamInterface $eventStream @param int $playhead @return DomainMessage[]
public function deserialize(StringLiteral $data) { $data = parent::deserialize($data); if (empty($data->label)) { throw new MissingValueException('Missing value "label".'); } if (empty($data->offers)) { throw new MissingValueException('Missing value "offers".'); } $label = new Label($data->label); $offers = new OfferIdentifierCollection(); foreach ($data->offers as $offer) { $offers = $offers->with( $this->offerIdentifierDeserializer->deserialize( new StringLiteral( json_encode($offer) ) ) ); } return new AddLabelToMultiple($offers, $label); }
@param StringLiteral $data @return AddLabelToMultiple @throws NotWellFormedException
protected function getMainImageId() { $mainImage = $this->images->getMain(); return isset($mainImage) ? $mainImage->getMediaObjectId() : null; }
Get the id of the main image if one is selected for this offer. @return UUID|null
public function deleteOrganizer($organizerId) { if ($this->organizerId === $organizerId) { $this->apply( $this->createOrganizerDeletedEvent($organizerId) ); } }
Delete the given organizer. @param string $organizerId
public function deleteCurrentOrganizer() { if (!is_null($this->organizerId)) { $this->apply( $this->createOrganizerDeletedEvent($this->organizerId) ); } }
Delete the current organizer regardless of the id.
public function updateContactPoint(ContactPoint $contactPoint) { if (is_null($this->contactPoint) || !$this->contactPoint->sameAs($contactPoint)) { $this->apply( $this->createContactPointUpdatedEvent($contactPoint) ); } }
Updated the contact info. @param ContactPoint $contactPoint
public function updateBookingInfo(BookingInfo $bookingInfo) { if (is_null($this->bookingInfo) || !$this->bookingInfo->sameAs($bookingInfo)) { $this->apply( $this->createBookingInfoUpdatedEvent($bookingInfo) ); } }
Updated the booking info. @param BookingInfo $bookingInfo
public function addImage(Image $image) { // Find the image based on UUID inside the internal state. $existingImage = $this->images->findImageByUUID($image->getMediaObjectId()); if ($existingImage === null) { $this->apply( $this->createImageAddedEvent($image) ); } }
Add a new image. @param Image $image
public function removeImage(Image $image) { // Find the image based on UUID inside the internal state. // Use the image from the internal state. $existingImage = $this->images->findImageByUUID($image->getMediaObjectId()); if ($existingImage) { $this->apply( $this->createImageRemovedEvent($existingImage) ); } }
Remove an image. @param Image $image
public function selectMainImage(Image $image) { if (!$this->images->findImageByUUID($image->getMediaObjectId())) { throw new \InvalidArgumentException('You can not select a random image to be main, it has to be added to the item.'); } $oldMainImage = $this->images->getMain(); if (!isset($oldMainImage) || $oldMainImage->getMediaObjectId() !== $image->getMediaObjectId()) { $this->apply( $this->createMainImageSelectedEvent($image) ); } }
Make an existing image of the item the main image. @param Image $image
public function publish(\DateTimeInterface $publicationDate) { $this->guardPublish() ?: $this->apply( $this->createPublishedEvent($publicationDate) ); }
Publish the offer when it has workflowstatus draft. @param \DateTimeInterface $publicationDate
public function reject(StringLiteral $reason) { $this->guardRejection($reason) ?: $this->apply($this->createRejectedEvent($reason)); }
Reject an offer that is waiting for validation with a given reason. @param StringLiteral $reason
protected function applyUdb2ImagesEvent(AbstractImagesEvent $imagesEvent) { $newMainImage = $imagesEvent->getImages()->getMain(); $dutchImagesList = $imagesEvent->getImages()->toArray(); $translatedImagesList = array_filter( $this->images->toArray(), function (Image $image) { return $image->getLanguage()->getCode() !== 'nl'; } ); $imagesList = array_merge($dutchImagesList, $translatedImagesList); $images = ImageCollection::fromArray($imagesList); $this->images = isset($newMainImage) ? $images->withMain($newMainImage) : $images; }
This indirect apply method can be called internally to deal with images coming from UDB2. Imports from UDB2 only contain the native Dutch content. @see https://github.com/cultuurnet/udb3-udb2-bridge/blob/db0a7ab2444f55bb3faae3d59b82b39aaeba253b/test/Media/ImageCollectionFactoryTest.php#L79-L103 Because of this we have to make sure translated images are left in place. @param AbstractImagesEvent $imagesEvent
public function removeImage($id, Image $image) { $this->guardId($id); return $this->commandBus->dispatch( $this->commandFactory->createRemoveImageCommand($id, $image) ); }
@param $id Id of the offer to remove the image from. @param Image $image The image that should be removed. @return string
public function guardId($id) { $offer = $this->readRepository->get($id); if (is_null($offer)) { throw new EntityNotFoundException( sprintf('Offer with id: %s not found.', $id) ); } }
@param string $id @throws EntityNotFoundException|DocumentGoneException
public function createPlace( Language $mainLanguage, Title $title, EventType $eventType, Address $address, CalendarInterface $calendar, Theme $theme = null ) { $id = $this->uuidGenerator->generate(); $place = Place::createPlace( $id, $mainLanguage, $title, $eventType, $address, $calendar, $theme, $this->publicationDate ); $this->writeRepository->save($place); return $id; }
{@inheritdoc}
public function updateMajorInfo($id, Title $title, EventType $eventType, Address $address, CalendarInterface $calendar, Theme $theme = null) { $this->guardId($id); return $this->commandBus->dispatch( new UpdateMajorInfo($id, $title, $eventType, $address, $calendar, $theme) ); }
{@inheritdoc}
private static function splitKeywordTagOnSemiColon( CultureFeed_Cdb_Item_Event $event ) { $event = clone $event; /** * @var CultureFeed_Cdb_Data_Keyword[] $keywords */ $keywords = $event->getKeywords(true); foreach ($keywords as $keyword) { $individualKeywords = explode(';', $keyword->getValue()); if (count($individualKeywords) > 1) { $event->deleteKeyword($keyword); foreach ($individualKeywords as $individualKeyword) { $newKeyword = new CultureFeed_Cdb_Data_Keyword( trim($individualKeyword), $keyword->isVisible() ); $event->addKeyword($newKeyword); } } } return $event; }
UDB2 contained a bug that allowed for a keyword to have a semicolon. @param CultureFeed_Cdb_Item_Event $event @return CultureFeed_Cdb_Item_Event
public function load($id) { /** @var Deleteable $variationAggregate */ $variationAggregate = parent::load($id); if ($variationAggregate->isDeleted()) { throw AggregateDeletedException::create($id); } return $variationAggregate; }
{@inheritDoc} @return OfferVariation @throws AggregateDeletedException
public function handleUpdateMajorInfo(UpdateMajorInfo $updateMajorInfo) { /** @var Place $place */ $place = $this->offerRepository->load($updateMajorInfo->getItemId()); $place->updateMajorInfo( $updateMajorInfo->getTitle(), $updateMajorInfo->getEventType(), $updateMajorInfo->getAddress(), $updateMajorInfo->getCalendar(), $updateMajorInfo->getTheme() ); $this->offerRepository->save($place); }
Handle an update the major info command. @param UpdateMajorInfo $updateMajorInfo
public function search(string $query, $limit = 30, $start = 0, $sort = null) { $response = $this->executeSearch($query, $limit, $start, $sort); $parser = $this->getPullParser(); return $parser->getResultSet($response->getBody(true)); }
{@inheritdoc}
private function executeSearch($query, $limit, $start, $sort = null) { $qParam = new Parameter\Query($query); $groupParam = new Parameter\Group(); $startParam = new Parameter\Start($start); $limitParam = new Parameter\Rows($limit); $typeParam = new Parameter\FilterQuery('type:event OR (type:actor AND category_id:8.15.0.0.0)'); $params = array( $qParam, $groupParam, $limitParam, $startParam, $typeParam, ); if ($this->includePrivateItems) { $privateParam = new Parameter\FilterQuery('private:*'); $params[] = $privateParam; } if ($sort) { $params[] = new Parameter\Parameter('sort', $sort); } $response = $this->searchAPI2->search($params); return $response; }
Finds items matching an arbitrary query. @param string $query An arbitrary query. @param int $limit How many items to retrieve. @param int $start Offset to start from. @param string $sort Sorting to use. @return \Guzzle\Http\Message\Response
public function deserialize(StringLiteral $data) { $data = parent::deserialize($data); if (empty($data->label)) { throw new MissingValueException('Missing value "label"!'); } return new Label($data->label); }
{@inheritdoc}
public function removeLabel(UUID $uuid, UUID $labelId) { $command = new RemoveLabel( $uuid, $labelId ); return $this->commandBus->dispatch($command); }
{@inheritdoc}
public function delete(UUID $uuid) { $command = new DeleteRole( $uuid ); return $this->commandBus->dispatch($command); }
{@inheritdoc}
public function stats($ip = null): Response { // Prepare required variables $url = $this->api.'app/stats'; $params = $this->params + ['query' => ['user_ip' => $ip]]; // Return Authy application stats return new Response($this->http->get($url, $params)); }
Return application stats. @param string|null $ip @return \Rinvex\Authy\Response
public function loadClass(string $class, string $type = null, ...$params){ $type = $type ?? $class; try{ $reflectionClass = new ReflectionClass($class); $reflectionType = new ReflectionClass($type); } catch(Exception $e){ throw new TraitException('ClassLoader: '.$e->getMessage()); } if($reflectionType->isTrait()){ throw new TraitException($class.' cannot be an instance of trait '.$type); } if($reflectionClass->isAbstract()){ throw new TraitException('cannot instance abstract class '.$class); } if($reflectionClass->isTrait()){ throw new TraitException('cannot instance trait '.$class); } if($class !== $type){ if($reflectionType->isInterface() && !$reflectionClass->implementsInterface($type)){ throw new TraitException($class.' does not implement '.$type); } elseif(!$reflectionClass->isSubclassOf($type)) { throw new TraitException($class.' does not inherit '.$type); } } try{ $object = $reflectionClass->newInstanceArgs($params); if(!$object instanceof $type){ throw new TraitException('how did u even get here?'); // @codeCoverageIgnore } return $object; } // @codeCoverageIgnoreStart // here be dragons catch(Exception $e){ throw new TraitException('ClassLoader: '.$e->getMessage()); } // @codeCoverageIgnoreEnd }
Instances an object of $class/$type with an arbitrary number of $params @param string $class class FQCN @param string $type class/parent/interface FQCN @param mixed $params [optional] the following arguments will be passed to the $class constructor @return mixed of type $type @throws \Exception
public function fromIntSize(int $size):ByteArray{ if(!$this->isAllowedInt($size)){ throw new TraitException('invalid size'); } return new $this->byteArrayClass($size); }
@param int $size @return \chillerlan\Traits\ArrayHelpers\ByteArray @throws \chillerlan\Traits\TraitException
public function fromArray(array $array, bool $save_indexes = null):ByteArray{ try{ $out = $this->fromIntSize(\count($array)); $array = ($save_indexes ?? true) ? $array : \array_values($array); foreach($array as $k => $v){ $out[$k] = $v; } return $out; } // this can be anything // @codeCoverageIgnoreStart catch(Exception $e){ throw new TraitException($e->getMessage()); } // @codeCoverageIgnoreEnd }
@param array $array @param bool $save_indexes @return \chillerlan\Traits\ArrayHelpers\ByteArray @throws \chillerlan\Traits\TraitException
public function fromArrayFill(int $len, $fill = null):ByteArray{ if(!$this->isAllowedInt($len)){ throw new TraitException('invalid length'); } return $this->fromArray(\array_fill(0, $len, $fill)); }
@param int $len @param mixed $fill @return \chillerlan\Traits\ArrayHelpers\ByteArray @throws \chillerlan\Traits\TraitException
public function fromHex(string $hex):ByteArray{ $hex = \preg_replace('/[\s\r\n\t ]/', '', $hex); if(!$this->isAllowedHex($hex)){ throw new TraitException('invalid hex string'); } return $this->fromString(\pack('H*', $hex)); }
@param string $hex @return \chillerlan\Traits\ArrayHelpers\ByteArray|mixed @throws \chillerlan\Traits\TraitException
public function fromJSON(string $json):ByteArray{ $json = \trim($json); if(!$this->isAllowedJSON($json)){ throw new TraitException('invalid JSON array'); } return $this->fromArray(\json_decode(\trim($json))); }
@param string $json @return \chillerlan\Traits\ArrayHelpers\ByteArray|mixed @throws \chillerlan\Traits\TraitException
public function fromBase64(string $base64):ByteArray{ $base64 = \trim($base64); if(!$this->isAllowedBase64($base64)){ throw new TraitException('invalid base64 string'); } return $this->fromString(\base64_decode($base64)); }
@param string $base64 @return \chillerlan\Traits\ArrayHelpers\ByteArray|mixed @throws \chillerlan\Traits\TraitException
public function fromBin(string $bin):ByteArray{ $bin = \trim($bin); if(!$this->isAllowedBin($bin)){ throw new TraitException('invalid binary string'); } return $this->fromArray(\array_map('bindec', \str_split($bin, 8))); }
@param string $bin @return \chillerlan\Traits\ArrayHelpers\ByteArray @throws \chillerlan\Traits\TraitException
public function guessFrom($data):ByteArray{ if($data instanceof Traversable){ return $this->fromArray(\iterator_to_array($data)); } if(\is_array($data)){ return $this->fromArray($data); } if(\is_string($data)){ foreach(['Bin', 'Hex', 'JSON', 'Base64'] as $type){ if(\call_user_func_array([$this, 'isAllowed'.$type], [$data]) === true){ return \call_user_func_array([$this, 'from'.$type], [$data]); } } return $this->fromString($data); } throw new TraitException('invalid input'); }
@param string|array|\SplFixedArray $data @return \chillerlan\Traits\ArrayHelpers\ByteArray @throws \chillerlan\Traits\TraitException
public function __map($callback):array { if(!\is_callable($callback)){ throw new TraitException('invalid callback'); } $return = []; foreach($this->array as $index => $element){ $return[$index] = \call_user_func_array($callback, [$element, $index]); } return $return; }
@link http://api.prototypejs.org/language/Enumerable/prototype/collect/ @link http://api.prototypejs.org/language/Enumerable/prototype/map/ @param callable $callback @return array @throws \chillerlan\Traits\TraitException
public function __findAll($callback):array{ if(!\is_callable($callback)){ throw new TraitException('invalid callback'); } $return = []; foreach($this->array as $index => $element){ if(\call_user_func_array($callback, [$element, $index]) === true){ $return[] = $element; } } return $return; }
@link http://api.prototypejs.org/language/Enumerable/prototype/findAll/ @param callable $callback @return array @throws \chillerlan\Traits\TraitException
protected function isSuccess($result): bool { return ! is_null($result) ? (is_string($result) && $result === 'true') || (is_bool($result) && $result) : false; }
Determine if the given result is success. @param mixed $result @return bool
public function copyFrom(SplFixedArray $src, int $length = null, int $offset = null, int $srcOffset = null):ByteArray{ $length = $length ?? $src->count(); $offset = $offset ?? $length; $srcOffset = $srcOffset ?? 0; $diff = $offset + $length; if($diff > $this->count()){ $this->setSize($diff); } for($i = 0; $i < $length; $i++){ $this[$i + $offset] = $src[$i + $srcOffset]; } return $this; }
@param \SplFixedArray $src @param int $length @param int|null $offset @param int|null $srcOffset @return \chillerlan\Traits\ArrayHelpers\ByteArray
public function slice(int $offset, int $length = null):ByteArray{ // keep an extended class /** @var \chillerlan\Traits\ArrayHelpers\ByteArray $slice */ $slice = (new ReflectionClass($this))->newInstanceArgs([$length ?? ($this->count() - $offset)]); foreach($slice as $i => $_){ $slice[$i] = $this[$offset + $i]; } return $slice; }
@param int $offset @param int|null $length @return \chillerlan\Traits\ArrayHelpers\ByteArray
public function equal(SplFixedArray $array):bool{ if($this->count() !== $array->count()){ return false; } $diff = 0; foreach($this as $k => $v){ $diff |= $v ^ $array[$k]; } $diff = ($diff - 1) >> 31; return ($diff & 1) === 1; }
@param \SplFixedArray $array @return bool
public function get(string $dotKey, $default = null){ if(isset($this->array[$dotKey])){ return $this->array[$dotKey]; } $array = &$this->array; foreach(\explode('.', $dotKey) as $segment){ if(!\is_array($array) || !\array_key_exists($segment, $array)){ return $default; } $array = &$array[$segment]; } return $array; }
Checks if $key isset in $array using dot notation and returns it on success. @param string $dotKey the key to search @param mixed $default [optional] a default value in case the key isn't being found @return mixed returns $array[$key], $default otherwise.
public function in(string $dotKey):bool{ if(empty($this->array)){ return false; } if(\array_key_exists($dotKey, $this->array)){ return true; } $array = &$this->array; foreach(\explode('.', $dotKey) as $segment){ if(!\is_array($array) || !\array_key_exists($segment, $array)){ return false; } $array = &$array[$segment]; } return true; }
Checks if $key exists in $array using dot notation and returns it on success @param string $dotKey the key to search @return bool
public function set(string $dotKey, $value){ if(empty($dotKey)){ $this->array = $value; return $this; } $array = &$this->array; $keys = \explode('.', $dotKey); while(\count($keys) > 1){ $dotKey = \array_shift($keys); // If the key doesn't exist at this depth, we will just create an empty array // to hold the next value, allowing us to create the arrays to hold final // values at the correct depth. Then we'll keep digging into the array. if(!isset($array[$dotKey]) || !\is_array($array[$dotKey])){ $array[$dotKey] = []; } $array = &$array[$dotKey]; } $array[\array_shift($keys)] = $value; return $this; }
Sets $key in $array using dot notation If no key is given to the method, the entire array will be replaced. @param string $dotKey @param mixed $value @return \chillerlan\Traits\ArrayHelpers\DotArray
public function send($authyId, $method = 'sms', $force = false, $action = null, $actionMessage = null): Response { // Prepare required variables $url = $this->api.$method."/{$authyId}"; $params = $this->params + ['query' => ['force' => $force ? 'true' : 'false', 'action' => $action, 'actionMessage' => $actionMessage]]; // Send Authy token, and return response return new Response($this->http->get($url, $params)); }
Send verification token to the given Authy user. @param int $authyId @param string $method @param bool $force @param string|null $action @param string|null $actionMessage @return \Rinvex\Authy\Response