code
stringlengths 52
7.75k
| docs
stringlengths 1
5.85k
|
---|---|
public function process( \Aimeos\MShop\Order\Item\Iface $orderItem, $serviceId, array $urls, array $params )
{
return $this->controller->process( $orderItem, $serviceId, $urls, $params );
}
|
Processes the service for the given order, e.g. payment and delivery services
@param \Aimeos\MShop\Order\Item\Iface $orderItem Order which should be processed
@param string $serviceId Unique service item ID
@param array $urls Associative list of keys and the corresponding URLs
(keys are <type>.url-self, <type>.url-success, <type>.url-update where type can be "delivery" or "payment")
@param array $params Request parameters and order service attributes
@return \Aimeos\MShop\Common\Helper\Form\Iface|null Form object with URL, parameters, etc.
or null if no form data is required
|
public function updatePush( ServerRequestInterface $request, ResponseInterface $response, $code )
{
return $this->controller->updatePush( $request, $response, $code );
}
|
Updates the order status sent by payment gateway notifications
@param ServerRequestInterface $request Request object
@param ResponseInterface $response Response object that will contain HTTP status and response body
@param string $code Unique code of the service used for the current order
@return \Psr\Http\Message\ResponseInterface Response object
|
public function updateSync( ServerRequestInterface $request, $code, $orderid )
{
return $this->controller->updateSync( $request, $code, $orderid );
}
|
Updates the payment or delivery status for the given request
@param ServerRequestInterface $request Request object with parameters and request body
@param string $code Unique code of the service used for the current order
@param string $orderid ID of the order whose payment status should be updated
@return \Aimeos\MShop\Order\Item\Iface $orderItem Order item that has been updated
|
public function parseLines(array $lines, string $vcsType = ''): Changeset
{
$parser = $this->getParser($vcsType);
return $parser->parse($lines);
}
|
Accepts an array of diff lines & returns a Changeset instance.
@param string[] $lines
@param string $vcsType
@return Changeset
|
public function parseFile(string $filename, string $vcsType = ''): Changeset
{
$parser = $this->getParser($vcsType);
if (!file_exists($filename)) {
throw new \RuntimeException(
'File "' . $filename . '" not found.'
);
}
return $parser->parse(
file($filename, FILE_IGNORE_NEW_LINES)
);
}
|
Accepts an filename for a diff & returns a Changeset instance.
|
private function getNormalizer(string $vcsType): DiffNormalizerInterface
{
$normalizer = new GitDiffNormalizer();
if (self::VCS_SVN === $vcsType) {
$normalizer = new SvnDiffNormalizer();
}
return $normalizer;
}
|
Returns an appropriate normalizer for the VCS type.
|
public function getFilename(string $fileStartLine): string
{
// In case of parse error fall back to returning the line minus the plus or minus symbols.
if (!preg_match(static::FILENAME_REGEX, $fileStartLine, $matches)) {
return substr($fileStartLine, 4);
}
return $matches['filename'];
}
|
Accepts a raw file start line from a unified diff & returns a normalized version of the filename.
|
public function tokenize(array $diffLineList)
{
$tokenList = [];
$hasStarted = false;
$lineCount = count($diffLineList);
for ($i = 0; $i < $lineCount; $i++) {
// First line of a file
if ($this->isFileStart($diffLineList, $i)) {
$hasStarted = true;
$tokenList = array_merge(
$tokenList,
$this->getFilenameTokens($diffLineList, $i)
);
$i++; // Skip next line - we know this is safe due to check for is file start
// Only proceed once a file beginning has been found
} elseif ($hasStarted) {
$tokenList = array_merge(
$tokenList,
$this->getHunkTokens($diffLineList, $i)
);
}
}
return $tokenList;
}
|
Tokenize a unified diff
@param string[] $diffLineList
@return Token[]
|
private function getHunkTokens(
array $diffLineList,
int &$currentLine
): array {
$tokenList = [];
$hunkTokens = $this->getHunkStartTokens($diffLineList[$currentLine]);
// We have found a hunk start, process hunk lines
if ($this->isHunkStart($hunkTokens)) {
$currentLine++;
[$originalLineCount, $newLineCount] = $this->getHunkLineCounts($hunkTokens);
$addedCount = 0;
$removedCount = 0;
$unchangedCount = 0;
// Iterate until we have the correct number of original & new lines
$lineCount = count($diffLineList);
for ($i = $currentLine; $i < $lineCount; $i++) {
$tokenList[] = $this->getHunkLineToken(
$addedCount,
$removedCount,
$unchangedCount,
$diffLineList[$i]
);
// We have reached the line count for original & new versions of hunk
if (
$removedCount + $unchangedCount === $originalLineCount
&& $addedCount + $unchangedCount === $newLineCount
) {
break;
}
}
}
return array_merge($hunkTokens, $tokenList);
}
|
Process a hunk.
@param string[] $diffLineList
@param int $currentLine
@return Token[]
|
private function isFileStart(array $diffLineList, int $currentLine): bool
{
return $currentLine + 1 < count($diffLineList)
&& '---' === substr($diffLineList[$currentLine], 0, 3)
&& '+++' === substr($diffLineList[$currentLine + 1], 0, 3);
}
|
Returns true if the current line is the beginning of a file section.
@param string[] $diffLineList
@param int $currentLine
@return bool
|
private function getHunkStartTokens(string $diffLine): array
{
$tokenList = [];
if (preg_match(self::HUNK_START_REGEX, $diffLine, $matches)) {
// File deletion
if ($this->hasToken($matches, Token::FILE_DELETION_LINE_COUNT)) {
$tokenList = [
new Token(Token::FILE_DELETION_LINE_COUNT, $matches[Token::FILE_DELETION_LINE_COUNT]),
new Token(Token::HUNK_NEW_START, $matches[Token::HUNK_NEW_START]),
new Token(Token::HUNK_NEW_COUNT, $matches[Token::HUNK_NEW_COUNT])
];
// File creation
} elseif ($this->hasToken($matches, Token::FILE_CREATION_LINE_COUNT)) {
$tokenList = [
new Token(Token::HUNK_ORIGINAL_START, $matches[Token::HUNK_ORIGINAL_START]),
new Token(Token::HUNK_ORIGINAL_COUNT, $matches[Token::HUNK_ORIGINAL_COUNT]),
new Token(Token::FILE_CREATION_LINE_COUNT, $matches[Token::FILE_CREATION_LINE_COUNT]),
];
// Standard Case
} else {
$tokenList = [
new Token(Token::HUNK_ORIGINAL_START, $matches[Token::HUNK_ORIGINAL_START]),
new Token(Token::HUNK_ORIGINAL_COUNT, $matches[Token::HUNK_ORIGINAL_COUNT]),
new Token(Token::HUNK_NEW_START, $matches[Token::HUNK_NEW_START]),
new Token(Token::HUNK_NEW_COUNT, $matches[Token::HUNK_NEW_COUNT])
];
}
}
return $tokenList;
}
|
Parses the hunk start into appropriate tokens.
@param string $diffLine
@return Token[]
|
private function getFilenameTokens(array $diffLineList, int $currentLine): array
{
$filenameTokens = [];
// Get hunk metadata
$hunkTokens = $this->getHunkStartTokens($diffLineList[$currentLine+2]);
// In some cases we may have a diff with no contents (e.g. diff of svn propedit)
if (count($hunkTokens)) {
// Simple change
if (4 == count($hunkTokens)) {
$originalFilename = $this->diffNormalizer->getFilename($diffLineList[$currentLine]);
$newFilename = $this->diffNormalizer->getFilename($diffLineList[$currentLine + 1]);
// File deletion
} elseif (Token::FILE_DELETION_LINE_COUNT === $hunkTokens[0]->getType()) {
$originalFilename = $this->diffNormalizer->getFilename($diffLineList[$currentLine]);
$newFilename = '';
// File creation
} else {
$originalFilename = '';
$newFilename = $this->diffNormalizer->getFilename($diffLineList[$currentLine + 1]);
}
$filenameTokens = [
new Token(Token::ORIGINAL_FILENAME, $originalFilename),
new Token(Token::NEW_FILENAME, $newFilename)
];
}
return $filenameTokens;
}
|
Get tokens for original & new filenames.
@param string[] $diffLineList
@param int $currentLine
@return Token[]
|
private function getHunkLineToken(
int &$addedCount,
int &$removedCount,
int &$unchangedCount,
string $diffLine
): Token {
// Line added
if ('+' === substr($diffLine, 0, 1)) {
$tokenType = Token::SOURCE_LINE_ADDED;
$addedCount++;
// Line removed
} elseif ('-' === substr($diffLine, 0, 1)) {
$tokenType = Token::SOURCE_LINE_REMOVED;
$removedCount++;
// Line unchanged
} else {
$tokenType = Token::SOURCE_LINE_UNCHANGED;
$unchangedCount++;
}
return new Token($tokenType, $this->normalizeChangedLine($diffLine));
}
|
Get a single line for a hunk.
|
private function normalizeChangedLine(string $line): string
{
$normalized = substr($line, 1);
return false === $normalized ? $line : $normalized;
}
|
Remove the prefixed '+', '-' or ' ' from a changed line of code.
|
private function hasToken(array $matchList, string $tokenKey): bool
{
return array_key_exists($tokenKey, $matchList) && strlen($matchList[$tokenKey]);
}
|
Returns true if the token key was found in the list.
@param string[] $matchList
@param string $tokenKey
@return bool
|
public function parse(array $diffLineList): Changeset
{
$tokenList = $this->tokenizer->tokenize($diffLineList);
$fileList = [];
$startIndex = 0;
$tokenCount = count($tokenList);
for ($i = 0; $i < $tokenCount; $i++) {
// File begin
if (Token::ORIGINAL_FILENAME === $tokenList[$i]->getType()) {
$startIndex = $i;
}
// File end, hydrate object
if ($this->fileEnd($tokenList, $i + 1, Token::ORIGINAL_FILENAME)) {
$fileList[] = $this->parseFile(
array_slice($tokenList, $startIndex, ($i - $startIndex) + 1)
);
}
}
return new Changeset($fileList);
}
|
Parse an array of tokens out into an object graph.
@param string[] $diffLineList
@return Changeset
|
private function parseFile(array $fileTokenList): File
{
$originalName = $fileTokenList[0]->getValue();
$newName = $fileTokenList[1]->getValue();
$hunkList = [];
$startIndex = 0;
$tokenCount = count($fileTokenList);
for ($i = 2; $i < $tokenCount; $i++) {
// Hunk begin
if ($this->hunkStart($fileTokenList[$i])) {
$startIndex = $i;
}
// End of file, hydrate object
if ($i === count($fileTokenList) - 1) {
$hunkList[] = $this->parseHunk(
array_slice($fileTokenList, $startIndex)
);
// End of hunk, hydrate object
} elseif ($this->hunkStart($fileTokenList[$i + 1])) {
$hunkList[] = $this->parseHunk(
array_slice($fileTokenList, $startIndex, $i - $startIndex + 1)
);
}
}
return new File(
$originalName,
$newName,
$this->getFileOperation($fileTokenList),
$hunkList
);
}
|
Process the tokens for a single file, returning a File instance on success.
@param Token[] $fileTokenList
@return File
|
private function parseHunk(array $hunkTokenList): Hunk
{
[$originalStart, $originalCount, $newStart, $newCount, $tokensReadCount] = $this->getHunkMeta($hunkTokenList);
$originalLineNo = $originalStart;
$newLineNo = $newStart;
$lineList = [];
$tokenCount = count($hunkTokenList);
for ($i = $tokensReadCount; $i < $tokenCount; $i++) {
$operation = $this->mapLineOperation($hunkTokenList[$i]);
$lineList[] = new Line(
(Line::ADDED) === $operation ? Line::LINE_NOT_PRESENT : $originalLineNo,
(Line::REMOVED) === $operation ? Line::LINE_NOT_PRESENT : $newLineNo,
$operation,
$hunkTokenList[$i]->getValue()
);
if (Line::ADDED === $operation) {
$newLineNo++;
} elseif (Line::REMOVED === $operation) {
$originalLineNo++;
} else {
$originalLineNo++;
$newLineNo++;
}
}
return new Hunk(
$originalStart,
$originalCount,
$newStart,
$newCount,
$lineList
);
}
|
Parse out the contents of a hunk.
@param Token[] $hunkTokenList
@return Hunk
|
private function getHunkMeta(array $hunkTokenList): array
{
switch (true) {
case Token::FILE_DELETION_LINE_COUNT === $hunkTokenList[0]->getType():
$originalStart = 1;
$originalCount = intval($hunkTokenList[0]->getValue());
$newStart = intval($hunkTokenList[1]->getValue());
$newCount = intval($hunkTokenList[2]->getValue());
$tokensReadCount = 3;
break;
case Token::FILE_CREATION_LINE_COUNT === $hunkTokenList[2]->getType():
$originalStart = intval($hunkTokenList[0]->getValue());
$originalCount = intval($hunkTokenList[1]->getValue());
$newStart = 1;
$newCount = intval($hunkTokenList[2]->getValue());
$tokensReadCount = 3;
break;
default:
$originalStart = intval($hunkTokenList[0]->getValue());
$originalCount = intval($hunkTokenList[1]->getValue());
$newStart = intval($hunkTokenList[2]->getValue());
$newCount = intval($hunkTokenList[3]->getValue());
$tokensReadCount = 4;
break;
}
return [
$originalStart,
$originalCount,
$newStart,
$newCount,
$tokensReadCount
];
}
|
Parse out hunk meta.
@param Token[] $hunkTokenList
@return array Containing Original Start, Original Count, New Start, New Count & number of tokens consumed.
|
private function fileEnd(array $tokenList, int $nextLine, string $delimiterToken): bool
{
return $nextLine == count($tokenList) || $delimiterToken === $tokenList[$nextLine]->getType();
}
|
Determine if we're at the end of a 'section' of tokens.
@param Token[] $tokenList
@param int $nextLine
@param string $delimiterToken
@return bool
|
private function hunkStart(Token $token): bool
{
return Token::HUNK_ORIGINAL_START === $token->getType()
|| Token::FILE_DELETION_LINE_COUNT === $token->getType();
}
|
Returns true if the token indicates the start of a hunk.
|
private function mapLineOperation(Token $token): string
{
if (Token::SOURCE_LINE_ADDED === $token->getType()) {
$operation = Line::ADDED;
} elseif (Token::SOURCE_LINE_REMOVED === $token->getType()) {
$operation = Line::REMOVED;
} else {
$operation = Line::UNCHANGED;
}
return $operation;
}
|
Maps between token representation of line operations and the correct const from the Line class.
|
private function getFileOperation(array $fileTokenList): string
{
$operation = File::CHANGED;
if (
Token::FILE_CREATION_LINE_COUNT === $fileTokenList[4]->getType()
|| ("0" === $fileTokenList[2]->getValue() && ("0" === $fileTokenList[2]->getValue()))
) {
$operation = File::CREATED;
} else if (
Token::FILE_DELETION_LINE_COUNT === $fileTokenList[2]->getType()
|| ("0" === $fileTokenList[4]->getValue() && ("0" === $fileTokenList[5]->getValue()))
) {
$operation = File::DELETED;
}
return $operation;
}
|
Get the operation performed on the file (create, delete, change).
@param Token[] $fileTokenList
@return string One of class constants File::CREATED, File::DELETED, File::CHANGED
|
protected function applyEventCreated(
EventCreated $eventCreated,
DomainMessage $domainMessage
) {
$eventId = $eventCreated->getEventId();
$location = $eventCreated->getLocation();
$this->addNewItemToIndex(
$domainMessage,
$eventId,
EntityType::EVENT(),
$eventCreated->getTitle(),
$location->getAddress()->getPostalCode(),
$location->getAddress()->getLocality(),
$location->getAddress()->getCountry()->getCode()
);
}
|
Listener for event created commands.
@param EventCreated $eventCreated
@param DomainMessage $domainMessage
|
protected function applyPlaceCreated(
PlaceCreated $placeCreated,
DomainMessage $domainMessage
) {
$placeId = $placeCreated->getPlaceId();
$address = $placeCreated->getAddress();
$this->addNewItemToIndex(
$domainMessage,
$placeId,
EntityType::PLACE(),
$placeCreated->getTitle(),
$address->getPostalCode(),
$address->getLocality(),
$address->getCountry()->getCode()
);
}
|
Listener for place created commands.
@param PlaceCreated $placeCreated
@param DomainMessage $domainMessage
|
public function applyEventDeleted(
EventDeleted $eventDeleted
) {
$this->repository->deleteIndex(
$eventDeleted->getItemId(),
EntityType::EVENT()
);
}
|
Remove the index for events
@param EventDeleted $eventDeleted
|
public function applyPlaceDeleted(
PlaceDeleted $placeDeleted
) {
$this->repository->deleteIndex(
$placeDeleted->getItemId(),
EntityType::PLACE()
);
}
|
Remove the index for places
@param PlaceDeleted $placeDeleted
|
public function write(StringLiteral $userId, StringLiteral $name, QueryString $queryString): void
{
$userId = (string) $userId;
$name = (string) $name;
$query = $queryString->toURLQueryString();
$savedSearch = new \CultureFeed_SavedSearches_SavedSearch(
$userId,
$name,
$query,
\CultureFeed_SavedSearches_SavedSearch::NEVER
);
try {
$this->savedSearches->subscribe($savedSearch);
} catch (\Exception $exception) {
if ($this->logger) {
$this->logger->error(
'saved_search_was_not_subscribed',
[
'error' => $exception->getMessage(),
'userId' => $userId,
'name' => $name,
'query' => (string) $queryString,
]
);
}
}
}
|
{@inheritdoc}
|
public function delete(StringLiteral $userId, StringLiteral $searchId): void
{
$userId = (string) $userId;
$searchId = (string) $searchId;
try {
$this->savedSearches->unsubscribe($searchId, $userId);
} catch (\Exception $exception) {
if ($this->logger) {
$this->logger->error(
'User was not unsubscribed from saved search.',
[
'error' => $exception->getMessage(),
'userId' => $userId,
'searchId' => $searchId,
]
);
}
}
}
|
{@inheritdoc}
|
public function createEventVariation(
Url $originUrl,
OwnerId $ownerId,
Purpose $purpose,
Description $description
) {
$variation = OfferVariation::create(
new Id($this->uuidGenerator->generate()),
$originUrl,
$ownerId,
$purpose,
$description
);
$this->eventVariationRepository->save($variation);
return $variation;
}
|
{@inheritdoc}
|
public function editDescription(Id $id, Description $description)
{
/** @var OfferVariation $variation */
$variation = $this->eventVariationRepository->load((string) $id);
$variation->editDescription($description);
$this->eventVariationRepository->save($variation);
}
|
{@inheritdoc}
|
public function deleteEventVariation(Id $id)
{
/** @var OfferVariation $variation */
$variation = $this->eventVariationRepository->load((string) $id);
$variation->markDeleted();
$this->eventVariationRepository->save($variation);
}
|
{@inheritdoc}
|
public function handle(DomainMessage $domainMessage)
{
$event = $domainMessage->getPayload();
$eventName = get_class($event);
$eventHandlers = $this->getEventHandlers();
if (isset($eventHandlers[$eventName])) {
$handler = $eventHandlers[$eventName];
$jsonDocuments = call_user_func(array($this, $handler), $event, $domainMessage);
} elseif ($methodName = $this->getHandleMethodName($event)) {
$jsonDocuments = $this->{$methodName}($event, $domainMessage);
} else {
return;
}
if (!$jsonDocuments) {
return;
}
if (!is_array($jsonDocuments)) {
$jsonDocuments = [$jsonDocuments];
}
foreach ($jsonDocuments as $jsonDocument) {
$jsonDocument = $this->jsonDocumentMetaDataEnricher->enrich($jsonDocument, $domainMessage->getMetadata());
$jsonDocument = $this->updateModified($jsonDocument, $domainMessage);
$this->repository->save($jsonDocument);
}
}
|
{@inheritdoc}
|
private function updateTerm(JsonDocument $document, Category $category)
{
$offerLD = $document->getBody();
$oldTerms = property_exists($offerLD, 'terms') ? $offerLD->terms : [];
$newTerm = (object) $category->serialize();
$newTerms = array_filter(
$oldTerms,
function ($term) use ($category) {
return !property_exists($term, 'domain') || $term->domain !== $category->getDomain();
}
);
array_push($newTerms, $newTerm);
$offerLD->terms = array_values($newTerms);
return $document->withBody($offerLD);
}
|
@param JsonDocument $document
@param Category $category
@return JsonDocument
|
protected function applyImageAdded(AbstractImageAdded $imageAdded)
{
$document = $this->loadDocumentFromRepository($imageAdded);
$offerLd = $document->getBody();
$offerLd->mediaObject = isset($offerLd->mediaObject) ? $offerLd->mediaObject : [];
$imageData = $this->mediaObjectSerializer
->serialize($imageAdded->getImage(), 'json-ld');
$offerLd->mediaObject[] = $imageData;
if (count($offerLd->mediaObject) === 1) {
$offerLd->image = $imageData['contentUrl'];
}
return $document->withBody($offerLd);
}
|
Apply the imageAdded event to the item repository.
@param AbstractImageAdded $imageAdded
@return JsonDocument
|
protected function applyImageUpdated(AbstractImageUpdated $imageUpdated)
{
$document = $this->loadDocumentFromRepository($imageUpdated);
$offerLd = $document->getBody();
if (!isset($offerLd->mediaObject)) {
throw new \Exception('The image to update could not be found.');
}
$updatedMediaObjects = [];
foreach ($offerLd->mediaObject as $mediaObject) {
$mediaObjectMatches = (
strpos(
$mediaObject->{'@id'},
(string)$imageUpdated->getMediaObjectId()
) > 0
);
if ($mediaObjectMatches) {
$mediaObject->description = (string)$imageUpdated->getDescription();
$mediaObject->copyrightHolder = (string)$imageUpdated->getCopyrightHolder();
$updatedMediaObjects[] = $mediaObject;
}
};
if (empty($updatedMediaObjects)) {
throw new \Exception('The image to update could not be found.');
}
return $document->withBody($offerLd);
}
|
Apply the ImageUpdated event to the item repository.
@param AbstractImageUpdated $imageUpdated
@return JsonDocument
@throws \Exception
|
protected function applyCalendarUpdated(AbstractCalendarUpdated $calendarUpdated)
{
$document = $this->loadDocumentFromRepository($calendarUpdated)
->apply(OfferUpdate::calendar($calendarUpdated->getCalendar()));
$offerLd = $document->getBody();
$availableTo = AvailableTo::createFromCalendar($calendarUpdated->getCalendar());
$offerLd->availableTo = (string)$availableTo;
return $document->withBody($offerLd);
}
|
@param AbstractCalendarUpdated $calendarUpdated
@return JsonDocument
|
protected function applyOrganizerUpdated(AbstractOrganizerUpdated $organizerUpdated)
{
$document = $this->loadDocumentFromRepository($organizerUpdated);
$offerLd = $document->getBody();
$offerLd->organizer = array(
'@type' => 'Organizer',
) + (array)$this->organizerJSONLD($organizerUpdated->getOrganizerId());
return $document->withBody($offerLd);
}
|
Apply the organizer updated event to the offer repository.
@param AbstractOrganizerUpdated $organizerUpdated
@return JsonDocument
|
protected function applyOrganizerDeleted(AbstractOrganizerDeleted $organizerDeleted)
{
$document = $this->loadDocumentFromRepository($organizerDeleted);
$offerLd = $document->getBody();
unset($offerLd->organizer);
return $document->withBody($offerLd);
}
|
Apply the organizer delete event to the offer repository.
@param AbstractOrganizerDeleted $organizerDeleted
@return JsonDocument
|
protected function applyBookingInfoUpdated(AbstractBookingInfoUpdated $bookingInfoUpdated)
{
$document = $this->loadDocumentFromRepository($bookingInfoUpdated);
$offerLd = $document->getBody();
$offerLd->bookingInfo = $bookingInfoUpdated->getBookingInfo()->toJsonLd();
return $document->withBody($offerLd);
}
|
Apply the booking info updated event to the offer repository.
@param AbstractBookingInfoUpdated $bookingInfoUpdated
@return JsonDocument
|
protected function applyContactPointUpdated(AbstractContactPointUpdated $contactPointUpdated)
{
$document = $this->loadDocumentFromRepository($contactPointUpdated);
$offerLd = $document->getBody();
$offerLd->contactPoint = $contactPointUpdated->getContactPoint()->toJsonLd();
return $document->withBody($offerLd);
}
|
Apply the contact point updated event to the offer repository.
@param AbstractContactPointUpdated $contactPointUpdated
@return JsonDocument
|
protected function applyDescriptionUpdated(
AbstractDescriptionUpdated $descriptionUpdated
) {
$document = $this->loadDocumentFromRepository($descriptionUpdated);
$offerLd = $document->getBody();
if (empty($offerLd->description)) {
$offerLd->description = new \stdClass();
}
$mainLanguage = isset($offerLd->mainLanguage) ? $offerLd->mainLanguage : 'nl';
$offerLd->description->{$mainLanguage} = $descriptionUpdated->getDescription()->toNative();
return $document->withBody($offerLd);
}
|
Apply the description updated event to the offer repository.
@param AbstractDescriptionUpdated $descriptionUpdated
@return JsonDocument
|
protected function applyTypicalAgeRangeUpdated(
AbstractTypicalAgeRangeUpdated $typicalAgeRangeUpdated
) {
$document = $this->loadDocumentFromRepository($typicalAgeRangeUpdated);
$offerLd = $document->getBody();
$offerLd->typicalAgeRange = (string) $typicalAgeRangeUpdated->getTypicalAgeRange();
return $document->withBody($offerLd);
}
|
Apply the typical age range updated event to the offer repository.
@param AbstractTypicalAgeRangeUpdated $typicalAgeRangeUpdated
@return JsonDocument
|
protected function applyTypicalAgeRangeDeleted(
AbstractTypicalAgeRangeDeleted $typicalAgeRangeDeleted
) {
$document = $this->loadDocumentFromRepository($typicalAgeRangeDeleted);
$offerLd = $document->getBody();
unset($offerLd->typicalAgeRange);
return $document->withBody($offerLd);
}
|
Apply the typical age range deleted event to the offer repository.
@param AbstractTypicalAgeRangeDeleted $typicalAgeRangeDeleted
@return JsonDocument
|
private function applyUdb2ImagesEvent(\stdClass $offerLd, AbstractImagesEvent $imagesEvent)
{
$images = $imagesEvent->getImages();
$currentMediaObjects = isset($offerLd->mediaObject) ? $offerLd->mediaObject : [];
$dutchMediaObjects = array_map(
function (Image $image) {
return $this->mediaObjectSerializer->serialize($image, 'json-ld');
},
$images->toArray()
);
$translatedMediaObjects = array_filter(
$currentMediaObjects,
function ($image) {
return $image->inLanguage !== 'nl';
}
);
$mainImage = $images->getMain();
unset($offerLd->mediaObject, $offerLd->image);
if (!empty($dutchMediaObjects) || !empty($translatedMediaObjects)) {
$offerLd->mediaObject = array_merge($dutchMediaObjects, $translatedMediaObjects);
}
if (isset($mainImage)) {
$offerLd->image = (string) $mainImage->getSourceLocation();
}
}
|
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 \stdClass $offerLd
@param AbstractImagesEvent $imagesEvent
|
public function search(array $params)
{
$request = $this->getClient()->get('search');
// use CdbXML 3.3
$params[] = new Parameter('version', '3.3');
// include past events and present events with an embargo date
$params[] = new BooleanParameter('past', true);
$params[] = new BooleanParameter('unavailable', true);
$params[] = new BooleanParameter('udb3filtering', false);
$collector = new Collector();
$collector->addParameters($params, $request->getQuery());
$response = $request->send();
return $response;
}
|
{@inheritdoc}
|
public function get($id)
{
$value = $this->cache->fetch($id);
if ($value === false) {
return null;
}
return unserialize($value);
}
|
{@inheritdoc}
|
public function save($id, Calendar $calendar)
{
$calendar = serialize($calendar);
$this->cache->save($id, $calendar, 0);
}
|
{@inheritdoc}
|
public function log($level, $message, array $context = array())
{
$enrichedContext = $this->context + $context;
$this->decoratee->log($level, $message, $enrichedContext);
}
|
{@inheritdoc}
|
public function create(
Language $mainLanguage,
Url $website,
Title $title,
Address $address = null,
ContactPoint $contactPoint = null
) {
$id = $this->uuidGenerator->generate();
$organizer = Organizer::create($id, $mainLanguage, $website, $title);
if (!is_null($address)) {
$organizer->updateAddress($address, $mainLanguage);
}
if (!is_null($contactPoint)) {
$organizer->updateContactPoint($contactPoint);
}
$this->organizerRepository->save($organizer);
return $id;
}
|
{@inheritdoc}
|
public function serialize()
{
$serializedTimestamps = array_map(
function (Timestamp $timestamp) {
return $timestamp->serialize();
},
$this->timestamps
);
$serializedOpeningHours = array_map(
function (OpeningHour $openingHour) {
return $openingHour->serialize();
},
$this->openingHours
);
$calendar = [
'type' => $this->type,
];
empty($this->startDate) ?: $calendar['startDate'] = $this->startDate->format(DateTime::ATOM);
empty($this->endDate) ?: $calendar['endDate'] = $this->endDate->format(DateTime::ATOM);
empty($serializedTimestamps) ?: $calendar['timestamps'] = $serializedTimestamps;
empty($serializedOpeningHours) ?: $calendar['openingHours'] = $serializedOpeningHours;
return $calendar;
}
|
{@inheritdoc}
|
public static function deserialize(array $data)
{
return new static(
CalendarType::fromNative($data['type']),
!empty($data['startDate']) ? self::deserializeDateTime($data['startDate']) : null,
!empty($data['endDate']) ? self::deserializeDateTime($data['endDate']) : null,
!empty($data['timestamps']) ? array_map(
function ($timestamp) {
return Timestamp::deserialize($timestamp);
},
$data['timestamps']
) : [],
!empty($data['openingHours']) ? array_map(
function ($openingHour) {
return OpeningHour::deserialize($openingHour);
},
$data['openingHours']
) : []
);
}
|
{@inheritdoc}
|
private static function deserializeDateTime($dateTimeData)
{
$dateTime = DateTime::createFromFormat(DateTime::ATOM, $dateTimeData);
if ($dateTime === false) {
$dateTime = DateTime::createFromFormat('Y-m-d\TH:i:s', $dateTimeData, new DateTimeZone('Europe/Brussels'));
if (!$dateTime) {
throw new InvalidArgumentException('Invalid date string provided for timestamp, ISO8601 expected!');
}
}
return $dateTime;
}
|
This deserialization function takes into account old data that might be missing a timezone.
It will fall back to creating a DateTime object and assume Brussels.
If this still fails an error will be thrown.
@param $dateTimeData
@return DateTime
@throws InvalidArgumentException
|
public function toJsonLd()
{
$jsonLd = [];
$jsonLd['calendarType'] = $this->getType()->toNative();
// All calendar types allow startDate (and endDate).
// One timestamp - full day.
// One timestamp - start hour.
// One timestamp - start and end hour.
empty($this->startDate) ?: $jsonLd['startDate'] = $this->getStartDate()->format(DateTime::ATOM);
empty($this->endDate) ?: $jsonLd['endDate'] = $this->getEndDate()->format(DateTime::ATOM);
$timestamps = $this->getTimestamps();
if (!empty($timestamps)) {
$jsonLd['subEvent'] = array();
foreach ($timestamps as $timestamp) {
$jsonLd['subEvent'][] = array(
'@type' => 'Event',
'startDate' => $timestamp->getStartDate()->format(DateTime::ATOM),
'endDate' => $timestamp->getEndDate()->format(DateTime::ATOM),
);
}
}
// Period.
// Period with openingtimes.
// Permanent - "altijd open".
// Permanent - with openingtimes
$openingHours = $this->getOpeningHours();
if (!empty($openingHours)) {
$jsonLd['openingHours'] = array();
foreach ($openingHours as $openingHour) {
$jsonLd['openingHours'][] = $openingHour->serialize();
}
}
return $jsonLd;
}
|
Return the jsonLD version of a calendar.
|
public function serialize()
{
$serializedData = parent::serialize() + array(
'images' => array_map(
function (Image $image) {
return $image->serialize();
},
$this->images->toArray()
),
);
$mainImage = $this->images->getMain();
if ($mainImage) {
$serializedData[] = $mainImage->serialize();
}
return $serializedData;
}
|
{@inheritdoc}
|
public function dispatch($command)
{
/** @var CommandHandlerInterface|ContextAwareInterface|LoggerAwareInterface $handler */
foreach ($this->commandHandlers as $handler) {
if ($this->logger && $handler instanceof LoggerAwareInterface) {
$handler->setLogger($this->logger);
}
if ($handler instanceof ContextAwareInterface) {
$handler->setContext($this->context);
}
$handler->handle($command);
}
}
|
{@inheritDoc}
|
public static function deserialize(array $data)
{
return new static(
new UUID($data['media_object_id']),
new MIMEType($data['mime_type']),
new StringLiteral($data['description']),
new StringLiteral($data['copyright_holder']),
Url::fromNative($data['source_location']),
array_key_exists('language', $data) ? new Language($data['language']) : new Language('nl')
);
}
|
@param array $data
@return MediaObjectCreated The object instance
|
private function guardValidAgeRange(Age $from = null, Age $to = null)
{
if ($from && $to && $from > $to) {
throw new InvalidAgeRangeException('"from" age should not exceed "to" age');
}
}
|
@param null|Age $from
@param null|Age $to
@throws InvalidAgeRangeException
|
public static function fromString($ageRangeString)
{
if (!is_string($ageRangeString)) {
throw new InvalidAgeRangeException(
'Date-range should be of type string.'
);
}
$stringValues = explode('-', $ageRangeString);
if (empty($stringValues) || !isset($stringValues[1])) {
throw new InvalidAgeRangeException(
'Date-range string is not valid because it is missing a hyphen.'
);
}
if (count($stringValues) !== 2) {
throw new InvalidAgeRangeException(
'Date-range string is not valid because it has too many hyphens.'
);
}
$fromString = $stringValues[0];
$toString = $stringValues[1];
if (is_numeric($fromString) || empty($fromString)) {
$from = is_numeric($fromString) ? new Age($fromString) : null;
} else {
throw new InvalidAgeRangeException(
'The "from" age should be a natural number or empty.'
);
}
if (is_numeric($toString) || empty($toString)) {
$to = is_numeric($toString) ? new Age($toString) : null;
} else {
throw new InvalidAgeRangeException(
'The "to" age should be a natural number or empty.'
);
}
return new self($from, $to);
}
|
@param string $ageRangeString
@return AgeRange
@throws InvalidAgeRangeException
|
public function addDayOfWeek(DayOfWeek $dayOfWeek)
{
$this->daysOfWeek = array_unique(
array_merge(
$this->daysOfWeek,
[
$dayOfWeek->toNative(),
]
)
);
return $this;
}
|
Keeps the collection of days of week unique.
Makes sure that the objects are stored as strings to allow PHP serialize method.
@param DayOfWeek $dayOfWeek
@return DayOfWeekCollection
|
protected function applyEventDeleted(EventDeleted $event)
{
$eventId = $event->getItemId();
$this->repository->removeRelations($eventId);
}
|
Delete the relations.
@param EventDeleted $event
|
protected function applyOrganizerUpdated(OrganizerUpdated $organizerUpdated)
{
$this->repository->storeOrganizer($organizerUpdated->getItemId(), $organizerUpdated->getOrganizerId());
}
|
Store the relation when the organizer was changed
@param OrganizerUpdated $organizerUpdated
|
private function matchesIdAndEntityType()
{
$expr = $this->connection->getExpressionBuilder();
return $expr->andX(
$expr->eq('entity_id', ':entity_id'),
$expr->eq('entity_type', ':entity_type')
);
}
|
Returns the WHERE predicates for matching the id and entity_type columns.
@return \Doctrine\DBAL\Query\Expression\CompositeExpression
|
public function serialize()
{
$serialized = array_filter(
[
'phone' => $this->phone,
'email' => $this->email,
'url' => $this->url,
]
);
if ($this->availabilityStarts) {
$serialized['availabilityStarts'] = $this->availabilityStarts->format(\DATE_ATOM);
}
if ($this->availabilityEnds) {
$serialized['availabilityEnds'] = $this->availabilityEnds->format(\DATE_ATOM);
}
if ($this->urlLabel) {
$serialized['urlLabel'] = $this->urlLabel->serialize();
}
return $serialized;
}
|
{@inheritdoc}
|
public static function deserialize(array $data)
{
$defaults = [
'url' => null,
'urlLabel' => null,
'phone' => null,
'email' => null,
'availabilityStarts' => null,
'availabilityEnds' => null,
];
$data = array_merge($defaults, $data);
$availabilityStarts = null;
if ($data['availabilityStarts']) {
$availabilityStarts = \DateTimeImmutable::createFromFormat(\DATE_ATOM, $data['availabilityStarts']);
}
$availabilityEnds = null;
if ($data['availabilityEnds']) {
$availabilityEnds = \DateTimeImmutable::createFromFormat(\DATE_ATOM, $data['availabilityEnds']);
}
$urlLabel = null;
if ($data['urlLabel']) {
$urlLabel = MultilingualString::deserialize($data['urlLabel']);
}
return new static(
$data['url'],
$urlLabel,
$data['phone'],
$data['email'],
$availabilityStarts,
$availabilityEnds
);
}
|
{@inheritdoc}
|
public function handle(DomainMessage $domainMessage)
{
$event = $domainMessage->getPayload();
$method = $this->getHandleMethodName($event);
if ($method) {
$this->$method($event, new DomainMessageAdapter($domainMessage));
}
}
|
{@inheritDoc}
|
public function rename(
UUID $uuid,
StringLiteral $name
) {
$this->apply(new RoleRenamed($uuid, $name));
}
|
Rename the role.
@param UUID $uuid
@param StringLiteral $name
|
public function addPermission(
UUID $uuid,
Permission $permission
) {
if (!in_array($permission, $this->permissions)) {
$this->apply(new PermissionAdded($uuid, $permission));
}
}
|
Add a permission to the role.
@param UUID $uuid
@param Permission $permission
|
public function removePermission(
UUID $uuid,
Permission $permission
) {
if (in_array($permission, $this->permissions)) {
$this->apply(new PermissionRemoved($uuid, $permission));
}
}
|
Remove a permission from the role.
@param UUID $uuid
@param Permission $permission
|
public static function calendar(Calendar $calendar)
{
$offerCalenderUpdate = function ($body) use ($calendar) {
// Purge any existing calendar data
unset(
$body->calendarType,
$body->startDate,
$body->endDate,
$body->subEvent,
$body->openingHours
);
return (object) array_merge(
(array) $body,
$calendar->toJsonLd()
);
};
return $offerCalenderUpdate;
}
|
@param Calendar $calendar
The calendar to use when updating the offer
@return \Closure
A closure that accepts the existing offer body and applies the update.
|
public function determineAvailableLanguages(JsonDocument $jsonDocument)
{
$jsonDocument = $this->polyFillMultilingualFields($jsonDocument);
return parent::determineAvailableLanguages($jsonDocument);
}
|
@todo Remove when full replay is done.
@replay_i18n
@see https://jira.uitdatabank.be/browse/III-2201
@param JsonDocument $jsonDocument
@return \CultuurNet\UDB3\Language[]
|
public function determineCompletedLanguages(JsonDocument $jsonDocument)
{
$jsonDocument = $this->polyFillMultilingualFields($jsonDocument);
return parent::determineCompletedLanguages($jsonDocument);
}
|
@todo Remove when full replay is done.
@replay_i18n
@see https://jira.uitdatabank.be/browse/III-2201
@param JsonDocument $jsonDocument
@return \CultuurNet\UDB3\Language[]
|
private function polyFillMultilingualFields(JsonDocument $jsonDocument)
{
$body = $jsonDocument->getBody();
$mainLanguage = isset($body->mainLanguage) ? $body->mainLanguage : 'nl';
if (is_string($body->name)) {
$body->name = (object) [
$mainLanguage => $body->name,
];
}
if (isset($body->address->streetAddress)) {
$body->address = (object) [
$mainLanguage => $body->address,
];
}
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
|
protected function applyEventCdbXmlFromUDB2(
$eventId,
$cdbXmlNamespaceUri,
$cdbXml
) {
$document = $this->newDocument($eventId);
$eventLd = $this->projectEventCdbXmlToObject(
$document->getBody(),
$eventId,
$cdbXmlNamespaceUri,
$cdbXml
);
return $document->withBody($eventLd);
}
|
Helper function to save a JSON-LD document from cdbxml coming from UDB2.
@param string $eventId
@param string $cdbXmlNamespaceUri
@param string $cdbXml
@return JsonDocument
|
private function UDB3Media($document)
{
$media = [];
if ($document) {
$item = $document->getBody();
// At the moment we do not include any media coming from UDB2.
// If the mediaObject property contains data it's coming from UDB3.
$item->mediaObject = isset($item->mediaObject) ? $item->mediaObject : [];
}
return $media;
}
|
Return the media of an event if it already exists.
@param JsonDocument $document The JsonDocument.
@return array
A list of media objects.
|
private function UDB3Location($document)
{
$location = null;
if ($document) {
$item = $document->getBody();
$location = isset($item->location) ? $item->location : null;
}
return $location;
}
|
Return the location of an event if it already exists.
@param JsonDocument $document The JsonDocument.
@return array|null
The location
|
protected function applyMajorInfoUpdated(MajorInfoUpdated $majorInfoUpdated)
{
$document = $this
->loadDocumentFromRepository($majorInfoUpdated)
->apply(OfferUpdate::calendar($majorInfoUpdated->getCalendar()));
$jsonLD = $document->getBody();
$jsonLD->name->{$this->getMainLanguage($jsonLD)->getCode()} = $majorInfoUpdated->getTitle();
$jsonLD->location = array(
'@type' => 'Place',
) + (array)$this->placeJSONLD($majorInfoUpdated->getLocation()->getCdbid());
$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;
});
$jsonLD->terms = array_values($jsonLD->terms);
$eventType = $majorInfoUpdated->getEventType();
$jsonLD->terms[] = $eventType->toJsonLd();
$theme = $majorInfoUpdated->getTheme();
if (!empty($theme)) {
$jsonLD->terms[] = $theme->toJsonLd();
}
return $document->withBody($jsonLD);
}
|
Apply the major info updated command to the projector.
@param MajorInfoUpdated $majorInfoUpdated
@return JsonDocument
|
public function applyLocationUpdated(LocationUpdated $locationUpdated)
{
$document = $this->loadDocumentFromRepository($locationUpdated);
$jsonLD = $document->getBody();
$jsonLD->location = [
'@type' => 'Place',
] + (array) $this->placeJSONLD($locationUpdated->getLocationId()->toNative());
return $document->withBody($jsonLD);
}
|
@param LocationUpdated $locationUpdated
@return JsonDocument
|
public function serialize()
{
return [
'streetAddress' => $this->streetAddress->toNative(),
'postalCode' => $this->postalCode->toNative(),
'addressLocality' => $this->locality->toNative(),
'addressCountry' => $this->countryCode,
];
}
|
{@inheritdoc}
|
public static function deserialize(array $data)
{
return new static(
new Street($data['streetAddress']),
new PostalCode($data['postalCode']),
new Locality($data['addressLocality']),
Country::fromNative($data['addressCountry'])
);
}
|
{@inheritdoc}
|
public function toJsonLd()
{
return [
'addressCountry' => $this->countryCode,
'addressLocality' => $this->locality->toNative(),
'postalCode' => $this->postalCode->toNative(),
'streetAddress' => $this->streetAddress->toNative(),
];
}
|
{@inheritdoc}
|
public static function deserialize(array $data)
{
return new static(
new UUID($data['media_object_id']),
new MIMEType($data['mime_type']),
new Description($data['description']),
new CopyrightHolder($data['copyright_holder']),
Url::fromNative($data['source_location']),
array_key_exists('language', $data) ? new Language($data['language']) : new Language('nl')
);
}
|
{@inheritdoc}
|
public function serialize()
{
return [
'media_object_id' => (string) $this->getMediaObjectId(),
'mime_type' => (string) $this->getMimeType(),
'description' => (string) $this->getDescription(),
'copyright_holder' => (string) $this->getCopyrightHolder(),
'source_location' => (string) $this->getSourceLocation(),
'language' => (string) $this->getLanguage(),
];
}
|
{@inheritdoc}
|
public function serialize()
{
return parent::serialize() + array(
'media_object_id' => (string) $this->mediaObjectId,
'description' => (string) $this->description,
'copyright_holder' => (string) $this->copyrightHolder,
);
}
|
{@inheritdoc}
|
public function filter($string)
{
foreach ($this->filters as $filter) {
$string = $filter->filter($string);
}
return $string;
}
|
{@inheritdoc}
|
public function deserialize(StringLiteral $data)
{
$json = parent::deserialize(
$data
);
$this->guardValidnessWithJSONSchema($json);
return $this->createTypedObject($json);
}
|
@inheritdoc
@return CreateOfferVariation
|
private function createTypedObject(stdClass $json)
{
$url = new Url($json->same_as);
foreach ($this->urlValidators as $urlValidator) {
$urlValidator->validateUrl($url);
}
return new CreateOfferVariation(
$url,
new OwnerId($json->owner),
new Purpose($json->purpose),
new Description($json->description)
);
}
|
@param stdClass $json
@return CreateOfferVariation
@throws ValidationException
|
public function parse($description)
{
$prices = array();
$possiblePriceDescriptions = preg_split('/\s*;\s*/', $description);
try {
foreach ($possiblePriceDescriptions as $possiblePriceDescription) {
$price = $this->parseSinglePriceDescription($possiblePriceDescription);
$prices += $price;
}
} catch (RuntimeException $e) {
$prices = array();
}
return $prices;
}
|
@param string $description
@return array
An array of price name value pairs.
|
public function handleUpdateMajorInfo(UpdateMajorInfo $updateMajorInfo)
{
/** @var Event $event */
$event = $this->offerRepository->load($updateMajorInfo->getItemId());
$event->updateMajorInfo(
$updateMajorInfo->getTitle(),
$updateMajorInfo->getEventType(),
$updateMajorInfo->getLocation(),
$updateMajorInfo->getCalendar(),
$updateMajorInfo->getTheme()
);
$this->offerRepository->save($event);
}
|
Handle an update the major info command.
@param UpdateMajorInfo $updateMajorInfo
|
public function append($id, DomainEventStreamInterface $eventStream)
{
// The original Broadway DBALEventStore implementation did only check
// the type of $id. It is better to test all UUIDs inside the event
// stream.
$this->guardStream($eventStream);
// Make the transaction more robust by using the transactional statement.
$this->connection->transactional(function (Connection $connection) use ($eventStream) {
try {
foreach ($eventStream as $domainMessage) {
$this->insertMessage($connection, $domainMessage);
}
} catch (DBALException $exception) {
throw DBALEventStoreException::create($exception);
}
});
}
|
{@inheritDoc}
|
private function guardStream(DomainEventStreamInterface $eventStream)
{
foreach ($eventStream as $domainMessage) {
/** @var DomainMessage $domainMessage */
$id = (string) $domainMessage->getId();
}
}
|
Ensure that an error will be thrown if the ID in the domain messages is
not something that can be converted to a string.
If we let this move on without doing this DBAL will eventually
give us a hard time but the true reason for the problem will be
obfuscated.
@param DomainEventStreamInterface $eventStream
|
public function setContext(Metadata $context = null)
{
$this->context = $context;
if ($this->decoratee instanceof ContextAwareInterface) {
$this->decoratee->setContext($this->context);
}
$this->eventDispatcher->dispatch(
self::EVENT_COMMAND_CONTEXT_SET,
array(
'context' => $this->context,
)
);
}
|
{@inheritdoc}
|
public function dispatch($command)
{
if ($this->decoratee instanceof AuthorizedCommandBusInterface &&
$command instanceof AuthorizableCommandInterface) {
if (!$this->decoratee->isAuthorized($command)) {
throw new CommandAuthorizationException(
$this->decoratee->getUserIdentification()->getId(),
$command
);
}
}
$args = array();
$args['command'] = base64_encode(serialize($command));
$args['context'] = base64_encode(serialize($this->context));
$id = \Resque::enqueue($this->queueName, QueueJob::class, $args, true);
return $id;
}
|
Dispatches the command $command to a queue.
@param mixed $command
@return string the command id
@throws CommandAuthorizationException
|
public function deferredDispatch($jobId, $command)
{
$exception = null;
$currentCommandLogger = null;
if ($this->logger) {
$jobMetadata = array(
'job_id' => $jobId,
);
$currentCommandLogger = new ContextEnrichingLogger(
$this->logger,
$jobMetadata
);
}
if ($currentCommandLogger) {
$currentCommandLogger->info('job_started');
}
if ($this->decoratee instanceof LoggerAwareInterface) {
$this->decoratee->setLogger($currentCommandLogger);
}
try {
parent::dispatch($command);
} catch (\Exception $e) {
if ($currentCommandLogger) {
$currentCommandLogger->error('job_failed');
$currentCommandLogger->debug(
'exception caused job failure',
['exception' => $e]
);
}
$exception = $e;
}
$this->setContext(null);
if ($currentCommandLogger) {
$currentCommandLogger->info('job_finished');
}
if ($exception) {
throw $exception;
}
}
|
Really dispatches the command to the proper handler to be executed.
@param string $jobId
@param mixed $command
@throws \Exception
|
public static function deserialize(array $data)
{
$type = !empty($data['type']) ? $data['type'] : null;
return new static($data['url'], $data['thumbnail_url'], $data['description'], $data['copyright_holder'], $data['internal_id'], $type);
}
|
{@inheritdoc}
|
public function serialize()
{
return [
'type' => $this->type,
'url' => $this->url,
'thumbnail_url' => $this->thumbnailUrl,
'description' => $this->description,
'copyright_holder' => $this->copyrightHolder,
'internal_id' => $this->internalId,
];
}
|
{@inheritdoc}
|
public function toJsonLd()
{
$jsonLd = [];
if (!empty($this->type)) {
$jsonLd['@type'] = $this->type;
}
$jsonLd['url'] = $this->url;
$jsonLd['thumbnailUrl'] = $this->thumbnailUrl;
$jsonLd['description'] = $this->description;
$jsonLd['copyrightHolder'] = $this->copyrightHolder;
return $jsonLd;
}
|
{@inheritdoc}
|
public static function create(
$eventId,
Language $mainLanguage,
Title $title,
EventType $eventType,
Location $location,
CalendarInterface $calendar,
Theme $theme = null,
\DateTimeImmutable $publicationDate = null
) {
$event = new self();
$event->apply(
new EventCreated(
$eventId,
$mainLanguage,
$title,
$eventType,
$location,
$calendar,
$theme,
$publicationDate
)
);
return $event;
}
|
Factory method to create a new event.
@param $eventId
@param Language $mainLanguage
@param Title $title
@param EventType $eventType
@param Location $location
@param CalendarInterface $calendar
@param Theme|null $theme
@param \DateTimeImmutable|null $publicationDate
@return Event
|
public function copy($newEventId, CalendarInterface $calendar)
{
if ($this->hasUncommittedEvents()) {
throw new \RuntimeException('I refuse to copy, there are uncommitted events present.');
}
// The copied event will have a playhead of the original event + 1
$copy = clone $this;
$copy->apply(
new EventCopied(
$newEventId,
$this->eventId,
$calendar
)
);
return $copy;
}
|
@param string $newEventId
@param CalendarInterface $calendar
@return Event
|
public function updateMajorInfo(
Title $title,
EventType $eventType,
Location $location,
CalendarInterface $calendar,
Theme $theme = null
) {
$this->apply(new MajorInfoUpdated($this->eventId, $title, $eventType, $location, $calendar, $theme));
}
|
Update the major info.
@param Title $title
@param EventType $eventType
@param Location $location
@param CalendarInterface $calendar
@param Theme|null $theme
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.