public function createAction()
{
$this->checkPermissions(Acl::RESOURCE_GENERAL_CUSTOM_EVENTS, Acl::PERM_GENERAL_CUSTOM_EVENTS_MANAGE);
$object = $this->request->getJsonBody();
$eventAdapter = $this->adapter('event');
//Pre validates the request object
$eventAdapter->validateObject($object, Request::METHOD_POST);
if (empty($object->id)) {
throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_STRUCTURE, "Required field 'id' is missing.");
}
$object->scope = $this->getScope();
$criteria = [['name' => $object->id]];
switch ($this->getScope()) {
case ScopeInterface::SCOPE_ACCOUNT:
$criteria[] = ['$or' => [['$and' => [['envId' => null], ['accountId' => null]]], ['accountId' => $this->getUser()->getAccountId()]]];
break;
case ScopeInterface::SCOPE_ENVIRONMENT:
$criteria[] = ['$and' => [['envId' => $this->getEnvironment()->id], ['accountId' => $this->getUser()->getAccountId()]]];
break;
default:
throw new ApiErrorException(500, ErrorMessage::ERR_NOT_IMPLEMENTED, sprintf("The Scope '%s' has not been implemented yet", $this->getScope()));
}
/* @var $oldEvent Entity\EventDefinition */
$oldEvent = Entity\EventDefinition::findOne($criteria);
if (!empty($oldEvent)) {
if ($this->getScope() == ScopeInterface::SCOPE_ACCOUNT && $this->request->get('replace', false)) {
$replacements = Entity\EventDefinition::find([['name' => $object->id], ['accountId' => $this->getUser()->getAccountId()], ['envId' => ['$ne' => null]]]);
if ($replacements->count()) {
foreach ($replacements as $lowerEvent) {
$lowerEvent->delete();
}
} else {
throw new ApiErrorException(409, ErrorMessage::ERR_UNICITY_VIOLATION, sprintf('Event with id %s already exists', $object->id));
}
} else {
throw new ApiErrorException(409, ErrorMessage::ERR_UNICITY_VIOLATION, sprintf('Event with id %s already exists', $object->id));
}
}
/* @var $event Entity\EventDefinition */
//Converts object into EventDefinition entity
$event = $eventAdapter->toEntity($object);
$event->id = null;
$eventAdapter->validateEntity($event);
//Saves entity
$event->save();
//Responds with 201 Created status
$this->response->setStatus(201);
return $this->result($eventAdapter->toData($event));
}