repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Host/Infrastructure/API/FindHosts/FindHostsOnPremPresenter.php | centreon/src/Core/Host/Infrastructure/API/FindHosts/FindHostsOnPremPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Host\Infrastructure\API\FindHosts;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Host\Application\UseCase\FindHosts\FindHostsPresenterInterface;
use Core\Host\Application\UseCase\FindHosts\FindHostsResponse;
use Core\Host\Application\UseCase\FindHosts\SimpleDto;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Infrastructure\Common\Presenter\PresenterTrait;
final class FindHostsOnPremPresenter extends AbstractPresenter implements FindHostsPresenterInterface
{
use PresenterTrait;
public function __construct(
private readonly RequestParametersInterface $requestParameters,
protected PresenterFormatterInterface $presenterFormatter,
) {
parent::__construct($presenterFormatter);
}
public function presentResponse(FindHostsResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
$result = [];
foreach ($response->hostDto as $dto) {
$result[] = [
'id' => $dto->id,
'name' => $dto->name,
'alias' => $this->emptyStringAsNull($dto->alias ?? ''),
'address' => $dto->ipAddress,
'monitoring_server' => [
'id' => $dto->poller->id,
'name' => $dto->poller->name,
],
'templates' => array_map(
fn (SimpleDto $template) => ['id' => $template->id, 'name' => $template->name],
$dto->templateParents
),
'normal_check_interval' => $dto->normalCheckInterval,
'retry_check_interval' => $dto->retryCheckInterval,
'notification_timeperiod' => $dto->notificationTimeperiod !== null
? [
'id' => $dto->notificationTimeperiod->id,
'name' => $dto->notificationTimeperiod->name,
] : null,
'check_timeperiod' => $dto->checkTimeperiod !== null
? [
'id' => $dto->checkTimeperiod->id,
'name' => $dto->checkTimeperiod->name,
] : null,
'severity' => $dto->severity !== null
? ['id' => $dto->severity->id, 'name' => $dto->severity->name]
: null,
'categories' => array_map(
fn (SimpleDto $category) => ['id' => $category->id, 'name' => $category->name],
$dto->categories
),
'groups' => array_map(
fn (SimpleDto $group) => ['id' => $group->id, 'name' => $group->name],
$dto->groups
),
'is_activated' => $dto->isActivated,
];
}
$this->present([
'result' => $result,
'meta' => $this->requestParameters->toArray(),
]);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Host/Infrastructure/API/PartialUpdateHost/PartialUpdateHostController.php | centreon/src/Core/Host/Infrastructure/API/PartialUpdateHost/PartialUpdateHostController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Host\Infrastructure\API\PartialUpdateHost;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Host\Application\Exception\HostException;
use Core\Host\Application\UseCase\PartialUpdateHost\PartialUpdateHost;
use Core\Host\Application\UseCase\PartialUpdateHost\PartialUpdateHostRequest;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class PartialUpdateHostController extends AbstractController
{
use LoggerTrait;
/**
* @param Request $request
* @param PartialUpdateHost $useCase
* @param DefaultPresenter $presenter
* @param bool $isCloudPlatform
* @param int $hostId
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
Request $request,
PartialUpdateHost $useCase,
DefaultPresenter $presenter,
bool $isCloudPlatform,
int $hostId,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
try {
$dto = $this->setDto($request, $isCloudPlatform);
$useCase($dto, $presenter, $hostId);
} catch (\InvalidArgumentException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(new ErrorResponse(HostException::editHost()));
}
return $presenter->show();
}
/**
* @param Request $request
* @param bool $isCloudPlatform
*
* @throws \Throwable|\InvalidArgumentException
*
* @return PartialUpdateHostRequest
*/
private function setDto(Request $request, bool $isCloudPlatform): PartialUpdateHostRequest
{
/**
* @var array{
* name?: string,
* address?: string,
* monitoring_server_id?: int,
* alias?: string,
* snmp_version?: string,
* snmp_community?: string,
* note_url?: string,
* note?: string,
* action_url?: string,
* icon_alternative?: string,
* comment?: string,
* geo_coords?: string,
* check_command_args?: string[],
* event_handler_command_args?: string[],
* active_check_enabled?: int,
* passive_check_enabled?: int,
* notification_enabled?: int,
* freshness_checked?: int,
* flap_detection_enabled?: int,
* event_handler_enabled?: int,
* timezone_id?: null|int,
* severity_id?: null|int,
* check_command_id?: null|int,
* check_timeperiod_id?: null|int,
* event_handler_command_id?: null|int,
* notification_timeperiod_id?: null|int,
* icon_id?: null|int,
* max_check_attempts?: null|int,
* normal_check_interval?: null|int,
* retry_check_interval?: null|int,
* notification_options?: null|int,
* notification_interval?: null|int,
* first_notification_delay?: null|int,
* recovery_notification_delay?: null|int,
* acknowledgement_timeout?: null|int,
* freshness_threshold?: null|int,
* low_flap_threshold?: null|int,
* high_flap_threshold?: null|int,
* categories?: int[],
* groups?: int[],
* templates?: int[],
* macros?: array<array{id?:int|null,name:string,value:null|string,is_password:bool,description:null|string}>,
* add_inherited_contact_group?: bool,
* add_inherited_contact?: bool,
* is_activated?: bool
* } $data
*/
$data = $this->validateAndRetrieveDataSent(
$request,
$isCloudPlatform
? __DIR__ . '/PartialUpdateHostSaasSchema.json'
: __DIR__ . '/PartialUpdateHostOnPremSchema.json'
);
$dto = new PartialUpdateHostRequest();
/** @var array<string,string> $nonEmptyProperties */
$nonEmptyProperties = [
'name' => 'name',
'address' => 'address',
'monitoringServerId' => 'monitoring_server_id',
];
foreach ($nonEmptyProperties as $dtoKey => $dataKey) {
if (\array_key_exists($dataKey, $data)) {
$dto->{$dtoKey} = $data[$dataKey];
}
}
/** @var array<string,string> $dataOrEmptyStringProperties */
$dataOrEmptyStringProperties = [
'alias' => 'alias',
'snmpVersion' => 'snmp_version',
'snmpCommunity' => 'snmp_community',
'noteUrl' => 'note_url',
'note' => 'note',
'actionUrl' => 'action_url',
'iconAlternative' => 'icon_alternative',
'comment' => 'comment',
'geoCoordinates' => 'geo_coords',
];
foreach ($dataOrEmptyStringProperties as $dtoKey => $dataKey) {
if (\array_key_exists($dataKey, $data)) {
$dto->{$dtoKey} = $data[$dataKey] ?? '';
}
}
/** @var array<string,string> $dataOrEmptyArrayProperties */
$dataOrEmptyArrayProperties = [
'checkCommandArgs' => 'check_command_args',
'eventHandlerCommandArgs' => 'event_handler_command_args',
'categories' => 'categories',
'groups' => 'groups',
'templates' => 'templates',
'macros' => 'macros',
];
foreach ($dataOrEmptyArrayProperties as $dtoKey => $dataKey) {
if (\array_key_exists($dataKey, $data)) {
$dto->{$dtoKey} = $data[$dataKey] ?? [];
}
}
/** @var array<string,string> $dataOrNullProperties */
$dataOrNullProperties = [
'timezoneId' => 'timezone_id',
'severityId' => 'severity_id',
'checkCommandId' => 'check_command_id',
'checkTimeperiodId' => 'check_timeperiod_id',
'notificationTimeperiodId' => 'notification_timeperiod_id',
'eventHandlerCommandId' => 'event_handler_command_id',
'iconId' => 'icon_id',
'maxCheckAttempts' => 'max_check_attempts',
'normalCheckInterval' => 'normal_check_interval',
'retryCheckInterval' => 'retry_check_interval',
'notificationOptions' => 'notification_options',
'notificationInterval' => 'notification_interval',
'firstNotificationDelay' => 'first_notification_delay',
'recoveryNotificationDelay' => 'recovery_notification_delay',
'acknowledgementTimeout' => 'acknowledgement_timeout',
'freshnessThreshold' => 'freshness_threshold',
'lowFlapThreshold' => 'low_flap_threshold',
'highFlapThreshold' => 'high_flap_threshold',
];
foreach ($dataOrNullProperties as $dtoKey => $dataKey) {
if (\array_key_exists($dataKey, $data)) {
$dto->{$dtoKey} = $data[$dataKey] ?? null;
}
}
/** @var array<string,string> $dataOrDefaultValueProperties */
$dataOrDefaultValueProperties = [
'activeCheckEnabled' => 'active_check_enabled',
'passiveCheckEnabled' => 'passive_check_enabled',
'notificationEnabled' => 'notification_enabled',
'freshnessChecked' => 'freshness_checked',
'flapDetectionEnabled' => 'flap_detection_enabled',
'eventHandlerEnabled' => 'event_handler_enabled',
];
foreach ($dataOrDefaultValueProperties as $dtoKey => $dataKey) {
if (\array_key_exists($dataKey, $data)) {
$dto->{$dtoKey} = $data[$dataKey] ?? 2;
}
}
if (\array_key_exists('add_inherited_contact_group', $data)) {
$dto->addInheritedContactGroup = $data['add_inherited_contact_group'];
}
if (\array_key_exists('add_inherited_contact', $data)) {
$dto->addInheritedContact = $data['add_inherited_contact'];
}
if (\array_key_exists('is_activated', $data)) {
$dto->isActivated = $data['is_activated'];
}
return $dto;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/FindNotification/FindNotificationPresenterInterface.php | centreon/src/Core/Notification/Application/UseCase/FindNotification/FindNotificationPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\FindNotification;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface FindNotificationPresenterInterface
{
public function presentResponse(FindNotificationResponse|ResponseStatusInterface $response): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/FindNotification/FindNotification.php | centreon/src/Core/Notification/Application/UseCase/FindNotification/FindNotification.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\FindNotification;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Contact\Domain\AdminResolver;
use Core\Contact\Domain\Model\ContactGroup;
use Core\Notification\Application\Exception\NotificationException;
use Core\Notification\Application\Repository\NotificationResourceRepositoryProviderInterface;
use Core\Notification\Application\Repository\ReadNotificationRepositoryInterface;
use Core\Notification\Domain\Model\Contact as NotificationContact;
use Core\Notification\Domain\Model\Message;
use Core\Notification\Domain\Model\Notification;
use Core\Notification\Domain\Model\NotificationResource;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
final class FindNotification
{
use LoggerTrait;
public function __construct(
private readonly ReadNotificationRepositoryInterface $notificationRepository,
private readonly ContactInterface $user,
private readonly NotificationResourceRepositoryProviderInterface $resourceRepositoryProvider,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly AdminResolver $adminResolver,
) {
}
/**
* @param int $notificationId
* @param FindNotificationPresenterInterface $presenter
*/
public function __invoke(int $notificationId, FindNotificationPresenterInterface $presenter): void
{
try {
if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_NOTIFICATIONS_READ_WRITE)) {
$this->error(
"User doesn't have sufficient rights to add notifications",
['user_id' => $this->user->getId()]
);
$presenter->presentResponse(
new ForbiddenResponse(NotificationException::listOneNotAllowed())
);
return;
}
$this->info('Retrieving details for notification', [
'notification_id' => $notificationId,
]);
if (($notification = $this->notificationRepository->findById($notificationId)) === null) {
$this->info('Notification not found', [
'notification_id' => $notificationId,
]);
$presenter->presentResponse(new NotFoundResponse(_('Notification')));
} else {
$notificationMessages = $this->notificationRepository->findMessagesByNotificationId($notificationId);
$isAdmin = $this->adminResolver->isAdmin($this->user);
$notifiedUsers = $this->findNotificationUsers($notificationId, $isAdmin);
$notifiedContactGroups = $this->findContactGroupsByNotificationId($notificationId, $isAdmin);
$notificationResources = $this->findResourcesByNotificationId($notificationId, $isAdmin);
$presenter->presentResponse($this->createResponse(
$notification,
$notificationMessages,
$notifiedUsers,
$notifiedContactGroups,
$notificationResources
));
}
} catch (AssertionFailedException $ex) {
$this->error('An error occurred while retrieving the details of the notification', [
'notification_id' => $notificationId,
'trace' => (string) $ex,
]);
$presenter->presentResponse(new InvalidArgumentResponse($ex->getMessage()));
} catch (\Throwable $ex) {
$this->error('Unable to retrieve the details of the notification', [
'notification_id' => $notificationId,
'trace' => (string) $ex,
]);
$presenter->presentResponse(new ErrorResponse(NotificationException::errorWhileRetrievingObject()));
}
}
/**
* @return NotificationContact[]
*/
private function findNotificationUsers(int $notificationId, bool $isAdmin): array
{
if ($isAdmin === true) {
$notifiedUsers = array_values($this->notificationRepository->findUsersByNotificationId($notificationId));
} else {
$accessGroups = $this->readAccessGroupRepository->findByContact($this->user);
$notifiedUsers = array_values($this->notificationRepository->findUsersByNotificationIdUserAndAccessGroups(
$notificationId,
$this->user,
$accessGroups
));
}
return $notifiedUsers;
}
/**
* @return NotificationResource[]
*/
private function findResourcesByNotificationId(int $notificationId, bool $isAdmin): array
{
$resources = [];
foreach ($this->resourceRepositoryProvider->getRepositories() as $repository) {
if ($isAdmin === true) {
$resource = $repository->findByNotificationId($notificationId);
} else {
$accessGroups = $this->readAccessGroupRepository->findByContact($this->user);
$resource = $repository->findByNotificationIdAndAccessGroups($notificationId, $accessGroups);
}
if ($resource !== null) {
$resources[] = $resource;
}
}
return $resources;
}
/**
* @return ContactGroup[]
*/
private function findContactGroupsByNotificationId(int $notificationId, bool $isAdmin): array
{
if ($isAdmin === true) {
return $this->notificationRepository->findContactGroupsByNotificationId($notificationId);
}
$accessGroups = $this->readAccessGroupRepository->findByContact($this->user);
return $this->notificationRepository->findContactGroupsByNotificationIdAndAccessGroups(
$notificationId,
$this->user,
$accessGroups
);
}
/**
* create FindNotificationResponse Dto.
*
* @param Notification $notification
* @param Message[] $notificationMessages
* @param NotificationContact[] $notifiedUsers
* @param ContactGroup[] $notifiedContactGroups
* @param NotificationResource[] $notificationResources
*
* @return FindNotificationResponse
*/
private function createResponse(
Notification $notification,
array $notificationMessages,
array $notifiedUsers,
array $notifiedContactGroups,
array $notificationResources,
): FindNotificationResponse {
$response = new FindNotificationResponse();
$response->id = $notification->getId();
$response->name = $notification->getName();
$response->timeperiodId = $notification->getTimePeriod()->getId();
$response->timeperiodName = $notification->getTimePeriod()->getName();
$response->isActivated = $notification->isActivated();
$response->messages = array_map(
static fn (Message $message): array => [
'channel' => $message->getChannel()->value,
'subject' => $message->getSubject(),
'message' => $message->getRawMessage(),
'formatted_message' => $message->getFormattedMessage(),
],
$notificationMessages
);
$response->users = array_map(
static fn (NotificationContact $user): array => ['id' => $user->getId(), 'alias' => $user->getAlias()],
$notifiedUsers
);
$response->contactGroups = array_map(
static fn (ContactGroup $contactGroup): array => [
'id' => $contactGroup->getId(),
'name' => $contactGroup->getName(),
],
$notifiedContactGroups
);
foreach ($notificationResources as $resource) {
$responseResource = [
'type' => $resource->getType(),
'events' => $resource->getEvents(),
'ids' => array_map(
static fn ($resource): array => ['id' => $resource->getId(), 'name' => $resource->getName()],
$resource->getResources()
),
];
if (
$resource->getType() === NotificationResource::TYPE_HOST_GROUP
&& ! empty($resource->getServiceEvents())
) {
$responseResource['extra'] = [
'event_services' => $resource->getServiceEvents(),
];
}
$response->resources[] = $responseResource;
}
return $response;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/FindNotification/FindNotificationResponse.php | centreon/src/Core/Notification/Application/UseCase/FindNotification/FindNotificationResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\FindNotification;
use Core\Notification\Domain\Model\HostEvent;
use Core\Notification\Domain\Model\NotificationResource;
use Core\Notification\Domain\Model\ServiceEvent;
/**
* @phpstan-type _Resource array{
* type: NotificationResource::TYPE_*,
* events: ServiceEvent[]|HostEvent[],
* ids: array<array{id: int, name: string}>,
* extra?: array{
* event_services: ServiceEvent[]
* }
* }
*/
final class FindNotificationResponse
{
public int $id = 0;
public string $name = '';
public int $timeperiodId = 1;
public string $timeperiodName = '24x7';
public bool $isActivated = true;
/**
* @var array<array{
* channel: string,
* subject: string,
* message: string
* }>
*/
public array $messages = [];
/**
* @var array<array{
* id: int,
* alias: string
* }>
*/
public array $users = [];
/**
* @var array<array{
* id: int,
* name: string
* }>
*/
public array $contactGroups = [];
/** @var array<_Resource> */
public array $resources = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/DeleteNotification/DeleteNotification.php | centreon/src/Core/Notification/Application/UseCase/DeleteNotification/DeleteNotification.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\DeleteNotification;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\{
ErrorResponse,
ForbiddenResponse,
NoContentResponse,
NotFoundResponse,
ResponseStatusInterface,
};
use Core\Notification\Application\Exception\NotificationException;
use Core\Notification\Application\Repository\WriteNotificationRepositoryInterface;
final class DeleteNotification
{
use LoggerTrait;
/**
* @param ContactInterface $contact
* @param WriteNotificationRepositoryInterface $writeRepository
*/
public function __construct(
private readonly ContactInterface $contact,
private readonly WriteNotificationRepositoryInterface $writeRepository,
) {
}
/**
* @param int $notificationId
* @param DeleteNotificationPresenterInterface $presenter
*/
public function __invoke(int $notificationId, DeleteNotificationPresenterInterface $presenter): void
{
try {
if ($this->contactCanExecuteUseCase()) {
$response = $this->deleteNotification($notificationId);
} else {
$this->error(
"User doesn't have sufficient rights to delete notifications",
['user_id' => $this->contact->getId()]
);
$response = new ForbiddenResponse(NotificationException::deleteNotAllowed());
}
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$response = new ErrorResponse(NotificationException::errorWhileDeletingObject());
}
$presenter->presentResponse($response);
}
/**
* @param int $notificationId
*
* @throws \Throwable
*
* @return ResponseStatusInterface
*/
private function deleteNotification(int $notificationId): ResponseStatusInterface
{
if ($this->writeRepository->deleteNotification($notificationId) === 1) {
return new NoContentResponse();
}
$this->error('Notification (%s) not found', ['id' => $notificationId]);
return new NotFoundResponse('Notification');
}
/**
* @return bool
*/
private function contactCanExecuteUseCase(): bool
{
return $this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_NOTIFICATIONS_READ_WRITE);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/DeleteNotification/DeleteNotificationPresenterInterface.php | centreon/src/Core/Notification/Application/UseCase/DeleteNotification/DeleteNotificationPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\DeleteNotification;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface DeleteNotificationPresenterInterface
{
/**
* @param NoContentResponse|ResponseStatusInterface $data
*/
public function presentResponse(NoContentResponse|ResponseStatusInterface $data): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/FindNotifiableRule/FindNotifiableRule.php | centreon/src/Core/Notification/Application/UseCase/FindNotifiableRule/FindNotifiableRule.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\FindNotifiableRule;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Contact\Domain\AdminResolver;
use Core\Contact\Domain\Model\BasicContact;
use Core\Contact\Domain\Model\ContactGroup;
use Core\Notification\Application\Exception\NotificationException;
use Core\Notification\Application\Repository\ReadNotificationRepositoryInterface;
use Core\Notification\Application\UseCase\FindNotifiableRule\Response\ContactDto;
use Core\Notification\Application\UseCase\FindNotifiableRule\Response\EmailDto;
use Core\Notification\Domain\Model\Channel;
use Core\Notification\Domain\Model\Contact as NotificationContact;
use Core\Notification\Domain\Model\Message;
use Core\Notification\Domain\Model\Notification;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
final class FindNotifiableRule
{
use LoggerTrait;
/** @var AccessGroup[]|null */
private ?array $accessGroups = null;
public function __construct(
private readonly ReadNotificationRepositoryInterface $notificationRepository,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly ContactInterface $user,
private readonly AdminResolver $adminResolver,
) {
}
public function __invoke(
int $notificationId,
FindNotifiableRulePresenterInterface $presenter,
): void {
try {
if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_NOTIFICATIONS_READ_WRITE)) {
$this->error(
"User doesn't have sufficient rights to get notifications rule",
['user_id' => $this->user->getId()]
);
$presenter->presentResponse(
new ForbiddenResponse(NotificationException::listOneNotAllowed())
);
return;
}
$this->info(
'Retrieving details for notification',
['notification_id' => $notificationId]
);
if ($notification = $this->notificationRepository->findById($notificationId)) {
$presenter->presentResponse(
$this->createResponse(
notification: $notification,
messages: $this->notificationRepository->findMessagesByNotificationId($notificationId),
contacts: $this->findUsersByNotificationId($notificationId),
contactGroups: $this->findContactGroupsByNotificationId($notificationId),
)
);
} else {
$this->info('Notification not found', ['notification_id' => $notificationId]);
$presenter->presentResponse(new NotFoundResponse('Notification'));
}
} catch (AssertionFailedException $ex) {
$this->error(
'An error occurred while retrieving the details of the notification',
['notification_id' => $notificationId, 'trace' => (string) $ex]
);
$presenter->presentResponse(new InvalidArgumentResponse($ex->getMessage()));
} catch (\Throwable $ex) {
$this->error(
'Unable to retrieve the details of the notification',
['notification_id' => $notificationId, 'trace' => (string) $ex]
);
$presenter->presentResponse(new ErrorResponse(NotificationException::errorWhileRetrievingObject()));
}
}
/**
* @param int $notificationId
*
* @throws \Throwable
*
* @return ContactGroup[]
*/
private function findContactGroupsByNotificationId(int $notificationId): array
{
if ($this->adminResolver->isAdmin($this->user)) {
return $this->notificationRepository->findContactGroupsByNotificationId($notificationId);
}
return $this->notificationRepository->findContactGroupsByNotificationIdAndAccessGroups(
$notificationId,
$this->user,
$this->findAccessGroupsOfNonAdminUser()
);
}
/**
* @param int $notificationId
*
* @throws \Throwable
*
* @return NotificationContact[]
*/
private function findUsersByNotificationId(int $notificationId): array
{
if ($this->adminResolver->isAdmin($this->user)) {
return $this->notificationRepository->findUsersByNotificationId($notificationId);
}
return $this->notificationRepository->findUsersByNotificationIdUserAndAccessGroups(
$notificationId,
$this->user,
$this->findAccessGroupsOfNonAdminUser()
);
}
/**
* @throws \Throwable
*
* @return AccessGroup[]
*/
private function findAccessGroupsOfNonAdminUser(): array
{
if ($this->accessGroups === null) {
$this->accessGroups = $this->readAccessGroupRepository->findByContact($this->user);
}
return $this->accessGroups;
}
/**
* @param Notification $notification
* @param Message[] $messages
* @param array<int, NotificationContact> $contacts
* @param ContactGroup[] $contactGroups
*
* @throws \Throwable
*
* @return FindNotifiableRuleResponse
*/
private function createResponse(
Notification $notification,
array $messages,
array $contacts,
array $contactGroups,
): FindNotifiableRuleResponse {
$response = new FindNotifiableRuleResponse();
$response->notificationId = $notification->getId();
// Retrieve contacts from contact groups
$contactGroupIds = array_map(
static fn (ContactGroup $contactGroup) => $contactGroup->getId(),
$contactGroups
);
$contactDtos = $this->createContactDto($contacts);
foreach ($messages as $message) {
switch ($message->getChannel()) {
case Channel::Email:
$response->channels->email = new EmailDto(
contacts: $contactDtos,
subject: $message->getSubject(),
formattedMessage: $message->getFormattedMessage(),
);
break;
case Channel::Slack:
case Channel::Sms:
// Not implemented yet, 2023-09-07.
break;
}
}
return $response;
}
/**
* @param NotificationContact[]|BasicContact[] $contacts
*
* @return ContactDto[]
*/
private function createContactDto(array $contacts): array
{
$contactDtos = [];
$contactIdsAlreadyCreated = [];
foreach ($contacts as $contact) {
if (in_array($contact->getId(), $contactIdsAlreadyCreated, true)) {
continue;
}
$contactDtos[] = new ContactDto(
fullName: $contact->getName(),
emailAddress: $contact->getEmail(),
);
$contactIdsAlreadyCreated[] = $contact->getId();
}
return $contactDtos;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/FindNotifiableRule/FindNotifiableRulePresenterInterface.php | centreon/src/Core/Notification/Application/UseCase/FindNotifiableRule/FindNotifiableRulePresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\FindNotifiableRule;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface FindNotifiableRulePresenterInterface
{
public function presentResponse(FindNotifiableRuleResponse|ResponseStatusInterface $data): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/FindNotifiableRule/FindNotifiableRuleResponse.php | centreon/src/Core/Notification/Application/UseCase/FindNotifiableRule/FindNotifiableRuleResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\FindNotifiableRule;
final class FindNotifiableRuleResponse
{
public function __construct(
public int $notificationId = 0,
public Response\ChannelsDto $channels = new Response\ChannelsDto(),
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/FindNotifiableRule/Response/ChannelSlackDto.php | centreon/src/Core/Notification/Application/UseCase/FindNotifiableRule/Response/ChannelSlackDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\FindNotifiableRule\Response;
final class ChannelSlackDto
{
public function __construct(
public string $slackChannel = '',
public string $message = '',
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/FindNotifiableRule/Response/ChannelSmsDto.php | centreon/src/Core/Notification/Application/UseCase/FindNotifiableRule/Response/ChannelSmsDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\FindNotifiableRule\Response;
final class ChannelSmsDto
{
public function __construct(
public string $phoneNumber = '',
public string $message = '',
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/FindNotifiableRule/Response/ContactDto.php | centreon/src/Core/Notification/Application/UseCase/FindNotifiableRule/Response/ContactDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\FindNotifiableRule\Response;
final class ContactDto
{
public function __construct(
public string $fullName = '',
public string $emailAddress = '',
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/FindNotifiableRule/Response/ChannelsDto.php | centreon/src/Core/Notification/Application/UseCase/FindNotifiableRule/Response/ChannelsDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\FindNotifiableRule\Response;
final class ChannelsDto
{
public function __construct(
public null|EmailDto $email = null,
public null|ChannelSlackDto $slack = null,
public null|ChannelSmsDto $sms = null,
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/FindNotifiableRule/Response/EmailDto.php | centreon/src/Core/Notification/Application/UseCase/FindNotifiableRule/Response/EmailDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\FindNotifiableRule\Response;
final class EmailDto
{
/**
* @param list<ContactDto> $contacts
* @param string $subject
* @param string $formattedMessage
*/
public function __construct(
public array $contacts = [],
public string $subject = '',
public string $formattedMessage = '',
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/FindNotifiableResources/NotifiableResourceDto.php | centreon/src/Core/Notification/Application/UseCase/FindNotifiableResources/NotifiableResourceDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\FindNotifiableResources;
class NotifiableResourceDto
{
/** @var int */
public int $notificationId = 0;
/** @var array<NotifiableHostDto> */
public array $hosts = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/FindNotifiableResources/NotifiableHostDto.php | centreon/src/Core/Notification/Application/UseCase/FindNotifiableResources/NotifiableHostDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\FindNotifiableResources;
class NotifiableHostDto
{
/** @var int */
public int $id = 0;
/** @var string */
public string $name = '';
/** @var string|null */
public ?string $alias = null;
/** @var int */
public int $events = 0;
/** @var array<NotifiableServiceDto> */
public array $services = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/FindNotifiableResources/FindNotifiableResourcesResponse.php | centreon/src/Core/Notification/Application/UseCase/FindNotifiableResources/FindNotifiableResourcesResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\FindNotifiableResources;
final class FindNotifiableResourcesResponse
{
/** @var string */
public string $uid = '';
/** @var array<NotifiableResourceDto> */
public array $notifiableResources = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/FindNotifiableResources/NotifiableServiceDto.php | centreon/src/Core/Notification/Application/UseCase/FindNotifiableResources/NotifiableServiceDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\FindNotifiableResources;
class NotifiableServiceDto
{
/** @var int */
public int $id = 0;
/** @var string */
public string $name = '';
/** @var string|null */
public ?string $alias = null;
/** @var int */
public int $events = 0;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/FindNotifiableResources/FindNotifiableResourcesPresenterInterface.php | centreon/src/Core/Notification/Application/UseCase/FindNotifiableResources/FindNotifiableResourcesPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\FindNotifiableResources;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface FindNotifiableResourcesPresenterInterface
{
/**
* @param FindNotifiableResourcesResponse|ResponseStatusInterface $response
*/
public function presentResponse(FindNotifiableResourcesResponse|ResponseStatusInterface $response): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/FindNotifiableResources/FindNotifiableResources.php | centreon/src/Core/Notification/Application/UseCase/FindNotifiableResources/FindNotifiableResources.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\FindNotifiableResources;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\{ErrorResponse, ForbiddenResponse, NotModifiedResponse};
use Core\Contact\Domain\AdminResolver;
use Core\Notification\Application\Converter\{NotificationHostEventConverter, NotificationServiceEventConverter};
use Core\Notification\Application\Exception\NotificationException;
use Core\Notification\Application\Repository\ReadNotifiableResourceRepositoryInterface;
use Core\Notification\Domain\Model\NotifiableResource;
final class FindNotifiableResources
{
use LoggerTrait;
/**
* @param ContactInterface $contact
* @param ReadNotifiableResourceRepositoryInterface $readRepository
*/
public function __construct(
private readonly ContactInterface $contact,
private readonly ReadNotifiableResourceRepositoryInterface $readRepository,
private readonly AdminResolver $adminResolver,
) {
}
/**
* @param FindNotifiableResourcesPresenterInterface $presenter
* @param string $requestUid
*
* @throws \Throwable
*/
public function __invoke(FindNotifiableResourcesPresenterInterface $presenter, string $requestUid): void
{
try {
if ($this->adminResolver->isAdmin($this->contact)) {
$this->info('Retrieving all notifiable resources');
$responseDto = $this->createResponseDto($this->readRepository->findAllForActivatedNotifications());
$responseJson = \json_encode($responseDto, JSON_THROW_ON_ERROR);
$calculatedUid = \hash('md5', $responseJson);
if ($calculatedUid === $requestUid) {
$response = new NotModifiedResponse();
} else {
$responseDto->uid = $calculatedUid;
$response = $responseDto;
}
} else {
$this->error(
"User doesn't have sufficient rights to list notification resources",
['user_id' => $this->contact->getId()]
);
$response = new ForbiddenResponse(NotificationException::listResourcesNotAllowed());
}
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$response = new ErrorResponse(NotificationException::errorWhileListingResources());
}
$presenter->presentResponse($response);
}
/**
* @param NotifiableResource[] $notifiableResources
*
* @return FindNotifiableResourcesResponse
*/
private function createResponseDto(iterable $notifiableResources): FindNotifiableResourcesResponse
{
$responseDto = new FindNotifiableResourcesResponse();
foreach ($notifiableResources as $notifiableResource) {
$notifiableResourceDto = new NotifiableResourceDto();
$notifiableResourceDto->notificationId = $notifiableResource->getNotificationId();
foreach ($notifiableResource->getHosts() as $notificationHost) {
$notificationHostDto = new NotifiableHostDto();
$notificationHostDto->id = $notificationHost->getId();
$notificationHostDto->name = $notificationHost->getName();
$notificationHostDto->alias = $notificationHost->getAlias();
if ($notificationHost->getEvents() !== []) {
$notificationHostDto->events = NotificationHostEventConverter::toBitFlags(
$notificationHost->getEvents()
);
}
foreach ($notificationHost->getServices() as $notificationService) {
$notificationServiceDto = new NotifiableServiceDto();
$notificationServiceDto->id = $notificationService->getId();
$notificationServiceDto->name = $notificationService->getName();
$notificationServiceDto->alias = $notificationService->getAlias();
if ($notificationService->getEvents() !== []) {
$notificationServiceDto->events = NotificationServiceEventConverter::toBitFlags(
$notificationService->getEvents()
);
}
$notificationHostDto->services[] = $notificationServiceDto;
}
$notifiableResourceDto->hosts[] = $notificationHostDto;
}
$responseDto->notifiableResources[] = $notifiableResourceDto;
}
return $responseDto;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/AddNotification/AddNotificationRequest.php | centreon/src/Core/Notification/Application/UseCase/AddNotification/AddNotificationRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\AddNotification;
final class AddNotificationRequest
{
public string $name = '';
public int $timePeriodId = 0;
/** @var int[] */
public array $users = [];
/** @var int[] */
public array $contactGroups = [];
/** @var array<array{
* type:string,
* ids:int[],
* events:int,
* includeServiceEvents:int
* }> $resources
*/
public array $resources = [];
/** @var array<array{
* channel:string,
* subject:string,
* message:string,
* formatted_message:string
* }> $messages
*/
public array $messages = [];
public bool $isActivated = true;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/AddNotification/AddNotificationResponse.php | centreon/src/Core/Notification/Application/UseCase/AddNotification/AddNotificationResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\AddNotification;
use Core\Notification\Application\Converter\NotificationHostEventConverter;
use Core\Notification\Application\Converter\NotificationServiceEventConverter;
use Core\Notification\Domain\Model\HostEvent;
use Core\Notification\Domain\Model\ServiceEvent;
final class AddNotificationResponse
{
public int $id = 0;
public string $name = '';
/**
* @var array{
* id:int,
* name:string,
* } $timeperiod
*/
public array $timeperiod = ['id' => 0, 'name' => ''];
public bool $isActivated = true;
/**
* @var array<array{
* id:int,
* name:string,
* }> $users
*/
public array $users = [];
/**
* @var array<array{
* id:int,
* name:string,
* }> $contactGroups
*/
public array $contactGroups = [];
/**
* @var array<array{
* type:string,
* ids:array<array{id:int,name:string}>,
* events:int,
* extra?:array{events_services?: int}
* }> $resources
*/
public array $resources = [];
/**
* @var array<array{
* channel:string,
* subject:string,
* message:string,
* formatted_message:string
* }> $messages
*/
public array $messages = [];
/**
* @param HostEvent[]|ServiceEvent[] $enums
*
* @return int
*/
public function convertHostEventsToBitFlags(array $enums): int
{
/**
* @var HostEvent[] $enums
*/
return NotificationHostEventConverter::toBitFlags($enums);
}
/**
* @param ServiceEvent[]|HostEvent[] $enums
*
* @return int
*/
public function convertServiceEventsToBitFlags(array $enums): int
{
/**
* @var ServiceEvent[] $enums
*/
return NotificationServiceEventConverter::toBitFlags($enums);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/AddNotification/AddNotification.php | centreon/src/Core/Notification/Application/UseCase/AddNotification/AddNotification.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\AddNotification;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Core\Application\Common\UseCase\CreatedResponse;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Application\Common\UseCase\PresenterInterface;
use Core\Contact\Domain\AdminResolver;
use Core\Contact\Domain\Model\ContactGroup;
use Core\Notification\Application\Exception\NotificationException;
use Core\Notification\Application\Repository\NotificationResourceRepositoryProviderInterface;
use Core\Notification\Application\Repository\ReadNotificationRepositoryInterface;
use Core\Notification\Application\Repository\WriteNotificationRepositoryInterface;
use Core\Notification\Application\UseCase\AddNotification\Factory\NewNotificationFactory;
use Core\Notification\Application\UseCase\AddNotification\Factory\NotificationMessageFactory;
use Core\Notification\Application\UseCase\AddNotification\Factory\NotificationResourceFactory;
use Core\Notification\Application\UseCase\AddNotification\Validator\NotificationValidator;
use Core\Notification\Domain\Model\Contact as NotificationContact;
use Core\Notification\Domain\Model\Message;
use Core\Notification\Domain\Model\Notification;
use Core\Notification\Domain\Model\NotificationResource;
use Core\Notification\Infrastructure\API\AddNotification\AddNotificationPresenter;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
final class AddNotification
{
use LoggerTrait;
public function __construct(
private readonly ReadNotificationRepositoryInterface $readNotificationRepository,
private readonly WriteNotificationRepositoryInterface $writeNotificationRepository,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly NotificationResourceRepositoryProviderInterface $resourceRepositoryProvider,
private readonly DataStorageEngineInterface $dataStorageEngine,
private readonly NewNotificationFactory $newNotificationFactory,
private readonly NotificationResourceFactory $notificationResourceFactory,
private readonly NotificationValidator $notificationValidator,
private readonly ContactInterface $user,
private readonly AdminResolver $adminResolver,
) {
}
/**
* @param AddNotificationRequest $request
* @param AddNotificationPresenter $presenter
*/
public function __invoke(
AddNotificationRequest $request,
PresenterInterface $presenter,
): void {
try {
$this->info('Add notification', ['request' => $request]);
if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_NOTIFICATIONS_READ_WRITE)) {
$this->error(
"User doesn't have sufficient rights to add notifications",
['user_id' => $this->user->getId()]
);
$presenter->setResponseStatus(
new ForbiddenResponse(NotificationException::addNotAllowed())
);
return;
}
$this->notificationValidator->validateTimePeriod($request->timePeriodId);
$this->notificationValidator->validateUsersAndContactGroups(
$request->users,
$request->contactGroups,
$this->user
);
$newNotification = $this->newNotificationFactory->create(
$request->name,
$request->isActivated,
$request->timePeriodId
);
$newMessages = NotificationMessageFactory::createNotificationMessages($request->messages);
$newResources = $this->notificationResourceFactory->createNotificationResources($request->resources);
try {
$this->dataStorageEngine->startTransaction();
$newNotificationId = $this->writeNotificationRepository->addNewNotification($newNotification);
$this->writeNotificationRepository->addMessagesToNotification($newNotificationId, $newMessages);
$this->writeNotificationRepository->addUsersToNotification($newNotificationId, $request->users);
$this->writeNotificationRepository->addContactGroupsToNotification($newNotificationId, $request->contactGroups);
$this->addResources($newNotificationId, $newResources);
$this->dataStorageEngine->commitTransaction();
} catch (\Throwable $ex) {
$this->error("Rollback of 'Add Notification' transaction.");
$this->dataStorageEngine->rollbackTransaction();
throw $ex;
}
$createdNotificationInformation = $this->findCreatedNotificationInformation($newNotificationId);
$presenter->present($this->createResponse(
$createdNotificationInformation['notification'],
$createdNotificationInformation['users'],
$createdNotificationInformation['contactGroups'],
$createdNotificationInformation['resources'],
$createdNotificationInformation['messages']
));
} catch (AssertionFailedException|\ValueError $ex) {
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (NotificationException $ex) {
$presenter->setResponseStatus(
match ($ex->getCode()) {
NotificationException::CODE_CONFLICT => new InvalidArgumentResponse($ex),
default => new ErrorResponse($ex),
}
);
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (\Throwable $ex) {
$presenter->setResponseStatus(new ErrorResponse(NotificationException::addNotification()));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
}
}
/**
* @param int $notificationId
* @param NotificationResource[] $newResources
*
* @throws \Throwable
*/
private function addResources(int $notificationId, array $newResources): void
{
foreach ($newResources as $resourceType => $newResource) {
$repository = $this->resourceRepositoryProvider->getRepository($resourceType);
$repository->add($notificationId, $newResource);
}
}
/**
* @param int $notificationId
*
* @throws \Throwable
*
* @return NotificationResource[]
*/
private function findResources(int $notificationId): array
{
$resources = [];
foreach ($this->resourceRepositoryProvider->getRepositories() as $repository) {
if ($this->adminResolver->isAdmin($this->user)) {
$resource = $repository->findByNotificationId($notificationId);
} else {
$accessGroups = $this->readAccessGroupRepository->findByContact($this->user);
$resource = $repository->findByNotificationIdAndAccessGroups($notificationId, $accessGroups);
}
if ($resource !== null) {
$resources[$resource->getType()] = $resource;
}
}
return $resources;
}
/**
* @param Notification $notification
* @param NotificationContact[] $users
* @param ContactGroup[] $contactGroups
* @param NotificationResource[] $resources
* @param Message[] $messages
*
* @return CreatedResponse<int,AddNotificationResponse>
*/
private function createResponse(
Notification $notification,
array $users,
array $contactGroups,
array $resources,
array $messages,
): CreatedResponse {
$response = new AddNotificationResponse();
$response->id = $notification->getId();
$response->name = $notification->getName();
$response->timeperiod = [
'id' => $notification->getTimePeriod()->getId(),
'name' => $notification->getTimePeriod()->getName(),
];
$response->isActivated = $notification->isActivated();
$response->messages = array_map(
static fn (Message $message): array => [
'channel' => $message->getChannel()->value,
'subject' => $message->getSubject(),
'message' => $message->getRawMessage(),
'formatted_message' => $message->getFormattedMessage(),
],
$messages
);
$response->users = array_map(
static fn (NotificationContact $user): array => ['id' => $user->getId(), 'name' => $user->getName()],
$users
);
$response->contactGroups = array_map(
static fn (ContactGroup $contactGroup): array => [
'id' => $contactGroup->getId(),
'name' => $contactGroup->getName(),
],
$contactGroups
);
foreach ($resources as $resource) {
$responseResource = [
'type' => $resource->getType(),
'events' => $resource->getType() === NotificationResource::TYPE_HOST_GROUP
? $response->convertHostEventsToBitFlags($resource->getEvents())
: $response->convertServiceEventsToBitFlags($resource->getEvents()),
'ids' => array_map(
static fn ($resource): array => ['id' => $resource->getId(), 'name' => $resource->getName()],
$resource->getResources()
),
];
if (
$resource->getType() === NotificationResource::TYPE_HOST_GROUP
&& ! empty($resource->getServiceEvents())
) {
$responseResource['extra'] = [
'event_services' => $response->convertServiceEventsToBitFlags($resource->getServiceEvents()),
];
}
$response->resources[] = $responseResource;
}
return new CreatedResponse($response->id, $response);
}
/**
* Find freshly created notification information.
*
* @param int $newNotificationId
*
* @throws \Throwable|NotificationException
*
* @return array{
* notification: Notification,
* messages: Message[],
* users: NotificationContact[],
* contactGroups: ContactGroup[],
* resources: NotificationResource[]
* }
*/
private function findCreatedNotificationInformation(int $newNotificationId): array
{
return [
'notification' => $this->readNotificationRepository->findById($newNotificationId)
?? throw NotificationException::errorWhileRetrievingObject(),
'messages' => $this->readNotificationRepository->findMessagesByNotificationId($newNotificationId),
'users' => array_values($this->readNotificationRepository->findUsersByNotificationId($newNotificationId)),
'contactGroups' => $this->readNotificationRepository->findContactGroupsByNotificationId($newNotificationId),
'resources' => $this->findResources($newNotificationId),
];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/AddNotification/Validator/NotificationValidator.php | centreon/src/Core/Notification/Application/UseCase/AddNotification/Validator/NotificationValidator.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\AddNotification\Validator;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Contact\Application\Repository\ReadContactGroupRepositoryInterface;
use Core\Contact\Application\Repository\ReadContactRepositoryInterface;
use Core\Contact\Domain\AdminResolver;
use Core\Contact\Domain\Model\BasicContact;
use Core\Contact\Domain\Model\ContactGroup;
use Core\Notification\Application\Exception\NotificationException;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\TimePeriod\Application\Repository\ReadTimePeriodRepositoryInterface;
use Utility\Difference\BasicDifference;
class NotificationValidator
{
use LoggerTrait;
private ContactInterface $currentContact;
public function __construct(
private readonly ReadContactRepositoryInterface $contactRepository,
private readonly ReadContactGroupRepositoryInterface $contactGroupRepository,
private readonly ReadAccessGroupRepositoryInterface $accessGroupRepository,
private readonly ReadTimePeriodRepositoryInterface $readTimePeriodRepository,
private readonly AdminResolver $adminResolver,
) {
}
/**
* Validate that provided user and contact group ids exists.
*
* @param int[] $userIds
* @param int[] $contactGroupsIds
* @param ContactInterface $currentContact
*
* @throws NotificationException
* @throws \Throwable
*/
public function validateUsersAndContactGroups(
array $userIds,
array $contactGroupsIds,
ContactInterface $currentContact,
): void {
if ($userIds === [] && $contactGroupsIds === []) {
throw NotificationException::emptyArrayNotAllowed('users, contact groups');
}
$this->currentContact = $currentContact;
$isAdmin = $this->adminResolver->isAdmin($currentContact);
if ($userIds !== []) {
$this->validateUsers($userIds, $isAdmin);
}
if ($contactGroupsIds !== []) {
$this->validateContactGroups($contactGroupsIds, $isAdmin);
}
}
/**
* Validate that provided time period id exists.
*
* @param int $timePeriodId
*
* @throws \Throwable|NotificationException
*/
public function validateTimePeriod(int $timePeriodId): void
{
if ($this->readTimePeriodRepository->exists($timePeriodId) === false) {
$this->error('Time period does not exist', ['timePeriodId' => $timePeriodId]);
throw NotificationException::invalidId('timeperiodId');
}
}
/**
* Validate that provided user ids exists.
*
* @param int[] $contactIdsToValidate
*
* @throws \Throwable|NotificationException
*/
private function validateUsers(array $contactIdsToValidate, bool $isAdmin): void
{
$contactIdsToValidate = array_unique($contactIdsToValidate);
if ($isAdmin === true) {
$existingContactIds = $this->contactRepository->retrieveExistingContactIds($contactIdsToValidate);
} else {
$accessGroups = $this->accessGroupRepository->findByContact($this->currentContact);
$existingContacts = $this->contactRepository->findByAccessGroupsAndUserAndRequestParameters(
$accessGroups,
$this->currentContact
);
$existingContactIds = array_map(fn (BasicContact $contact) => $contact->getId(), $existingContacts);
}
$contactDifference = new BasicDifference($contactIdsToValidate, $existingContactIds);
$missingContact = $contactDifference->getRemoved();
if ($missingContact !== []) {
$this->error(
'Invalid ID(s) provided',
['propertyName' => 'users', 'propertyValues' => array_values($missingContact)]
);
throw NotificationException::invalidId('users');
}
}
/**
* Validate that provided contact group ids exists.
*
* @param int[] $contactGroupIds
*
* @throws \Throwable|NotificationException
*/
private function validateContactGroups(array $contactGroupIds, bool $isAdmin): void
{
$contactGroupIds = array_unique($contactGroupIds);
if ($isAdmin === true) {
$contactGroups = $this->contactGroupRepository->findByIds($contactGroupIds);
} else {
$accessGroups = $this->accessGroupRepository->findByContact($this->currentContact);
$contactGroups = $this->contactGroupRepository->findByAccessGroupsAndUserAndRequestParameter(
$accessGroups,
$this->currentContact
);
}
$existingContactGroupIds = array_map(fn (ContactGroup $contactGroup) => $contactGroup->getId(), $contactGroups);
$difference = new BasicDifference($contactGroupIds, $existingContactGroupIds);
$missingContactGroups = $difference->getRemoved();
if ($missingContactGroups !== []) {
$this->error(
'Invalid ID(s) provided',
['propertyName' => 'contactgroups', 'propertyValues' => array_values($missingContactGroups)]
);
throw NotificationException::invalidId('contactgroups');
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/AddNotification/Factory/NotificationMessageFactory.php | centreon/src/Core/Notification/Application/UseCase/AddNotification/Factory/NotificationMessageFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\AddNotification\Factory;
use Core\Notification\Application\Exception\NotificationException;
use Core\Notification\Domain\Model\Channel;
use Core\Notification\Domain\Model\Message;
class NotificationMessageFactory
{
/**
* Create multiple NotificationMessage.
*
* @param array<array{
* channel: string,
* subject: string,
* message: string,
* formatted_message: string
* }> $messages
*
* @throws \Assert\AssertionFailedException
* @throws NotificationException
*
* @return Message[]
*/
public static function createNotificationMessages(array $messages): array
{
if ($messages === []) {
throw NotificationException::emptyArrayNotAllowed('message');
}
$notificationMessages = [];
foreach ($messages as $message) {
$messageType = Channel::from($message['channel']);
// If multiple message with same type are defined, only the last one of each type is kept
$notificationMessages[$messageType->value] = new Message(
$messageType,
$message['subject'],
$message['message'],
$message['formatted_message']
);
}
return $notificationMessages;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/AddNotification/Factory/NotificationResourceFactory.php | centreon/src/Core/Notification/Application/UseCase/AddNotification/Factory/NotificationResourceFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\AddNotification\Factory;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Contact\Domain\AdminResolver;
use Core\Notification\Application\Converter\NotificationServiceEventConverter;
use Core\Notification\Application\Exception\NotificationException;
use Core\Notification\Application\Repository\NotificationResourceRepositoryInterface;
use Core\Notification\Application\Repository\NotificationResourceRepositoryProviderInterface;
use Core\Notification\Domain\Model\ConfigurationResource;
use Core\Notification\Domain\Model\NotificationResource;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Utility\Difference\BasicDifference;
class NotificationResourceFactory
{
use LoggerTrait;
public function __construct(
private readonly NotificationResourceRepositoryProviderInterface $notificationResourceRepositoryProvider,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly ContactInterface $user,
private readonly AdminResolver $adminResolver,
) {
}
/**
* Create multiple NotificationResource.
*
* @param array<array{
* type: string,
* ids: int[],
* events: int,
* includeServiceEvents: int
* }> $resources
*
* @throws \Assert\AssertionFailedException
* @throws NotificationException
* @throws \Throwable
*
* @return NotificationResource[]
*/
public function createNotificationResources(array $resources): array
{
if ($resources === []) {
throw NotificationException::emptyArrayNotAllowed('resource');
}
$newResources = [];
foreach ($resources as $resourceData) {
$resourceIds = array_unique($resourceData['ids']);
if ($resourceIds === []) {
continue;
}
$resourceRepository = $this->notificationResourceRepositoryProvider->getRepository($resourceData['type']);
// If multiple resources with same type are defined, only the last one of each type is kept
$newResources[$resourceRepository->resourceType()] = $this->createNotificationResource(
$resourceRepository,
$resourceData
);
}
$totalResources = 0;
foreach ($newResources as $newResource) {
$totalResources += $newResource->getResourcesCount();
}
if ($totalResources <= 0) {
throw NotificationException::emptyArrayNotAllowed('resource.ids');
}
return $newResources;
}
/**
* Create a NotificationResource.
*
* @param NotificationResourceRepositoryInterface $resourceRepository
* @param array{
* type: string,
* ids: int[],
* events: int,
* includeServiceEvents: int
* } $resource
*
* @throws NotificationException
* @throws \Throwable
*
* @return NotificationResource
*/
private function createNotificationResource(
NotificationResourceRepositoryInterface $resourceRepository,
array $resource,
): NotificationResource {
$resourceIds = array_unique($resource['ids']);
if ($this->adminResolver->isAdmin($this->user)) {
// Assert IDs validity without ACLs
$existingResources = $resourceRepository->exist($resourceIds);
} else {
// Assert IDs validity with ACLs
$accessGroups = $this->readAccessGroupRepository->findByContact($this->user);
$existingResources = $resourceRepository->existByAccessGroups($resourceIds, $accessGroups);
}
$difference = new BasicDifference($resourceIds, $existingResources);
$missingResources = $difference->getRemoved();
if ($missingResources !== []) {
$this->error(
'Invalid ID(s) provided',
['propertyName' => 'resources', 'propertyValues' => array_values($missingResources)]
);
throw NotificationException::invalidId('resource.ids');
}
// If multiple resources with same type are defined, only the last one of each type is kept
return new NotificationResource(
$resourceRepository->resourceType(),
$resourceRepository->eventEnum(),
array_map((fn ($resourceId) => new ConfigurationResource($resourceId, '')), $resourceIds),
($resourceRepository->eventEnumConverter())::fromBitFlags($resource['events']),
$resource['includeServiceEvents']
? NotificationServiceEventConverter::fromBitFlags($resource['includeServiceEvents'])
: []
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/AddNotification/Factory/NewNotificationFactory.php | centreon/src/Core/Notification/Application/UseCase/AddNotification/Factory/NewNotificationFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\AddNotification\Factory;
use Centreon\Domain\Log\LoggerTrait;
use Core\Common\Domain\TrimmedString;
use Core\Notification\Application\Exception\NotificationException;
use Core\Notification\Application\Repository\ReadNotificationRepositoryInterface;
use Core\Notification\Domain\Model\NewNotification;
use Core\Notification\Domain\Model\TimePeriod;
class NewNotificationFactory
{
use LoggerTrait;
public function __construct(private readonly ReadNotificationRepositoryInterface $notificationRepository)
{
}
/**
* Create New Notification.
*
* @param string $name
* @param bool $isActivated
* @param int $timePeriodId
*
* @throws NotificationException
* @throws \Assert\AssertionFailedException
* @throws \Throwable
*
* @return NewNotification
*/
public function create(string $name, bool $isActivated, int $timePeriodId): NewNotification
{
$this->assertNameDoesNotAlreadyExists($name);
return new NewNotification(
$name,
new TimePeriod($timePeriodId, ''),
$isActivated
);
}
/**
* Validate that a notification with this name doesn't already exist.
*
* @param string $name
*
* @throws NotificationException
* @throws \Throwable
*/
private function assertNameDoesNotAlreadyExists(string $name): void
{
if ($this->notificationRepository->existsByName(new TrimmedString($name))) {
$this->error('Notification name already exists', ['name' => $name]);
throw NotificationException::nameAlreadyExists();
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/DeleteNotifications/DeleteNotificationsPresenterInterface.php | centreon/src/Core/Notification/Application/UseCase/DeleteNotifications/DeleteNotificationsPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\DeleteNotifications;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface DeleteNotificationsPresenterInterface
{
/**
* @param DeleteNotificationsResponse|ResponseStatusInterface $data
*/
public function presentResponse(DeleteNotificationsResponse|ResponseStatusInterface $data): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/DeleteNotifications/DeleteNotifications.php | centreon/src/Core/Notification/Application/UseCase/DeleteNotifications/DeleteNotifications.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\DeleteNotifications;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Repository\RepositoryException;
use Core\Application\Common\UseCase\{
ErrorResponse,
ForbiddenResponse,
NoContentResponse,
NotFoundResponse,
ResponseStatusInterface
};
use Core\Notification\Application\Exception\NotificationException;
use Core\Notification\Application\Repository\WriteNotificationRepositoryInterface;
use Core\Notification\Domain\Model\ResponseCode;
final class DeleteNotifications
{
use LoggerTrait;
/**
* @param ContactInterface $contact
* @param WriteNotificationRepositoryInterface $writeRepository
*/
public function __construct(
private readonly ContactInterface $contact,
private readonly WriteNotificationRepositoryInterface $writeRepository,
) {
}
/**
* @param DeleteNotificationsRequest $request
* @param DeleteNotificationsPresenterInterface $presenter
*/
public function __invoke(
DeleteNotificationsRequest $request,
DeleteNotificationsPresenterInterface $presenter,
): void {
try {
if ($this->contactCanExecuteUseCase()) {
$response = new DeleteNotificationsResponse();
$results = [];
foreach ($request->ids as $notificationId) {
try {
$statusResponse = $this->deleteNotification($notificationId);
$responseStatusDto = $this->createStatusResponseDto($statusResponse, $notificationId);
$results[] = $responseStatusDto;
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$statusResponse = new ErrorResponse(NotificationException::errorWhileDeletingObject());
$responseStatusDto = $this->createStatusResponseDto($statusResponse, $notificationId);
$results[] = $responseStatusDto;
}
}
$response->results = $results;
} else {
$this->error(
"User doesn't have sufficient rights to delete notifications",
['user_id' => $this->contact->getId()]
);
$response = new ForbiddenResponse(NotificationException::deleteNotAllowed());
}
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$response = new ErrorResponse(NotificationException::errorWhileDeletingObject());
}
$presenter->presentResponse($response);
}
/**
* @param int $notificationId
*
* @throws RepositoryException
* @throws \Throwable
*
* @return ResponseStatusInterface
*/
private function deleteNotification(int $notificationId): ResponseStatusInterface
{
$this->info('Deleting notification', ['id' => $notificationId]);
if ($this->writeRepository->deleteNotification($notificationId) === 1) {
return new NoContentResponse();
}
$this->error('Notification (%s) not found', ['id' => $notificationId]);
return new NotFoundResponse('Notification');
}
/**
* @return bool
*/
private function contactCanExecuteUseCase(): bool
{
return $this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_NOTIFICATIONS_READ_WRITE);
}
/**
* @param ResponseStatusInterface $statusResponse
* @param int $notificationId
*
* @return DeleteNotificationsStatusResponse
*/
private function createStatusResponseDto(
ResponseStatusInterface $statusResponse,
int $notificationId,
): DeleteNotificationsStatusResponse {
$responseStatusDto = new DeleteNotificationsStatusResponse();
$responseStatusDto->id = $notificationId;
if ($statusResponse instanceof NoContentResponse) {
$responseStatusDto->status = ResponseCode::OK;
$responseStatusDto->message = null;
} elseif ($statusResponse instanceof NotFoundResponse) {
$responseStatusDto->status = ResponseCode::NotFound;
$responseStatusDto->message = $statusResponse->getMessage();
} else {
$responseStatusDto->status = ResponseCode::Error;
$responseStatusDto->message = NotificationException::errorWhileDeletingObject()->getMessage();
}
return $responseStatusDto;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/DeleteNotifications/DeleteNotificationsRequest.php | centreon/src/Core/Notification/Application/UseCase/DeleteNotifications/DeleteNotificationsRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\DeleteNotifications;
final class DeleteNotificationsRequest
{
/** @var int[] */
public array $ids = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/DeleteNotifications/DeleteNotificationsResponse.php | centreon/src/Core/Notification/Application/UseCase/DeleteNotifications/DeleteNotificationsResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\DeleteNotifications;
final class DeleteNotificationsResponse
{
/** @var DeleteNotificationsStatusResponse[] */
public array $results = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/DeleteNotifications/DeleteNotificationsStatusResponse.php | centreon/src/Core/Notification/Application/UseCase/DeleteNotifications/DeleteNotificationsStatusResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\DeleteNotifications;
use Core\Notification\Domain\Model\ResponseCode;
final class DeleteNotificationsStatusResponse
{
public int $id = 0;
public ResponseCode $status = ResponseCode::OK;
public ?string $message = null;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/PartialUpdateNotification/PartialUpdateNotificationRequest.php | centreon/src/Core/Notification/Application/UseCase/PartialUpdateNotification/PartialUpdateNotificationRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\PartialUpdateNotification;
use Core\Common\Application\Type\NoValue;
final class PartialUpdateNotificationRequest
{
/**
* @param NoValue|bool $isActivated
*/
public function __construct(public NoValue|bool $isActivated = new NoValue())
{
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/PartialUpdateNotification/PartialUpdateNotification.php | centreon/src/Core/Notification/Application/UseCase/PartialUpdateNotification/PartialUpdateNotification.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\PartialUpdateNotification;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Core\Application\Common\UseCase\{
ErrorResponse,
ForbiddenResponse,
NoContentResponse,
NotFoundResponse,
ResponseStatusInterface
};
use Core\Common\Application\Type\NoValue;
use Core\Notification\Application\Exception\NotificationException;
use Core\Notification\Application\Repository\{
ReadNotificationRepositoryInterface,
WriteNotificationRepositoryInterface
};
use Core\Notification\Domain\Model\Notification;
final class PartialUpdateNotification
{
use LoggerTrait;
/**
* @param ContactInterface $contact
* @param ReadNotificationRepositoryInterface $readRepository
* @param WriteNotificationRepositoryInterface $writeRepository
* @param DataStorageEngineInterface $dataStorageEngine
*/
public function __construct(
private readonly ContactInterface $contact,
private readonly ReadNotificationRepositoryInterface $readRepository,
private readonly WriteNotificationRepositoryInterface $writeRepository,
private readonly DataStorageEngineInterface $dataStorageEngine,
) {
}
/**
* @param PartialUpdateNotificationRequest $request
* @param PartialUpdateNotificationPresenterInterface $presenter
* @param int $notificationId
*/
public function __invoke(
PartialUpdateNotificationRequest $request,
PartialUpdateNotificationPresenterInterface $presenter,
int $notificationId,
): void {
try {
if ($this->contactCanExecuteUseCase()) {
$response = $this->partiallyUpdateNotification($request, $notificationId);
} else {
$this->error(
"User doesn't have sufficient rights to delete notifications",
['user_id' => $this->contact->getId()]
);
$response = new ForbiddenResponse(NotificationException::partialUpdateNotAllowed()->getMessage());
}
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$response = new ErrorResponse(NotificationException::errorWhilePartiallyUpdatingObject());
}
$presenter->presentResponse($response);
}
/**
* @return bool
*/
private function contactCanExecuteUseCase(): bool
{
return $this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_NOTIFICATIONS_READ_WRITE);
}
/**
* @param PartialUpdateNotificationRequest $request
* @param int $notificationId
*
* @throws \Throwable
*
* @return ResponseStatusInterface
*/
private function partiallyUpdateNotification(
PartialUpdateNotificationRequest $request,
int $notificationId,
): ResponseStatusInterface {
if (! ($notification = $this->readRepository->findById($notificationId))) {
$this->error('Notification not found', ['notification_id' => $notificationId]);
return new NotFoundResponse('Notification');
}
$this->updatePropertiesInTransaction($request, $notification);
return new NoContentResponse();
}
/**
* @param PartialUpdateNotificationRequest $request
* @param Notification $notification
*
* @throws \Throwable
*/
private function updatePropertiesInTransaction(
PartialUpdateNotificationRequest $request,
Notification $notification,
): void {
try {
$this->dataStorageEngine->startTransaction();
$this->updateNotification($request, $notification);
$this->dataStorageEngine->commitTransaction();
} catch (\Throwable $ex) {
$this->error('Rollback of \'PartialUpdateNotification\' transaction');
$this->dataStorageEngine->rollbackTransaction();
throw $ex;
}
}
/**
* @param PartialUpdateNotificationRequest $request
* @param Notification $notification
*
* @throws \Throwable
*/
private function updateNotification(PartialUpdateNotificationRequest $request, Notification $notification): void
{
$this->info(
'PartialUpdateNotification: update is_activated',
['notification_id' => $notification->getId(), 'is_activated' => $request->isActivated]
);
if ($request->isActivated instanceof NoValue) {
$this->info('is_activated property is not provided. Nothing to update');
return;
}
$notification->setIsActivated($request->isActivated);
$this->writeRepository->updateNotification($notification);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/PartialUpdateNotification/PartialUpdateNotificationPresenterInterface.php | centreon/src/Core/Notification/Application/UseCase/PartialUpdateNotification/PartialUpdateNotificationPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\PartialUpdateNotification;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface PartialUpdateNotificationPresenterInterface
{
/**
* @param ResponseStatusInterface $response
*/
public function presentResponse(ResponseStatusInterface $response): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/FindNotifications/FindNotificationsResponse.php | centreon/src/Core/Notification/Application/UseCase/FindNotifications/FindNotificationsResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\FindNotifications;
final class FindNotificationsResponse
{
/** @var NotificationDto[] */
public array $notifications = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/FindNotifications/FindNotifications.php | centreon/src/Core/Notification/Application/UseCase/FindNotifications/FindNotifications.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\FindNotifications;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Infrastructure\RequestParameters\RequestParametersTranslatorException;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Contact\Domain\AdminResolver;
use Core\Notification\Application\Exception\NotificationException;
use Core\Notification\Application\Repository\NotificationResourceRepositoryInterface;
use Core\Notification\Application\Repository\NotificationResourceRepositoryProviderInterface;
use Core\Notification\Application\Repository\ReadNotificationRepositoryInterface;
use Core\Notification\Domain\Model\Channel;
use Core\Notification\Domain\Model\Notification;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
final class FindNotifications
{
use LoggerTrait;
public function __construct(
private readonly ContactInterface $user,
private readonly ReadNotificationRepositoryInterface $notificationRepository,
private readonly NotificationResourceRepositoryProviderInterface $repositoryProvider,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly RequestParametersInterface $requestParameters,
private readonly AdminResolver $adminResolver,
) {
}
public function __invoke(FindNotificationsPresenterInterface $presenter): void
{
$this->info('Search for notifications', ['request_parameter' => $this->requestParameters->toArray()]);
if (
! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_NOTIFICATIONS_READ_WRITE)
) {
$this->error(
"User doesn't have sufficient rights to list notifications",
['user_id' => $this->user->getId()]
);
$presenter->presentResponse(
new ForbiddenResponse(NotificationException::listNotAllowed())
);
return;
}
try {
$notifications = $this->notificationRepository->findAll($this->requestParameters);
if ($notifications === []) {
$presenter->presentResponse(new FindNotificationsResponse());
return;
}
$notificationsIds = array_map(fn (Notification $notification) => $notification->getId(), $notifications);
$this->info(
'Retrieving notification channels for notifications',
['notifications' => implode(', ', $notificationsIds)]
);
$notificationChannelByNotifications = $this->notificationRepository
->findNotificationChannelsByNotificationIds($notificationsIds);
$notificationCounts = $this->countUsersAndResourcesPerNotification($notificationsIds);
$presenter->presentResponse(
$this->createResponse($notifications, $notificationCounts, $notificationChannelByNotifications)
);
} catch (RequestParametersTranslatorException $ex) {
$presenter->presentResponse(new ErrorResponse($ex->getMessage()));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (\Throwable $ex) {
$this->error('An error occurred while retrieving the notifications listing', ['trace' => (string) $ex]);
$presenter->presentResponse(
new ErrorResponse(_('An error occurred while retrieving the notifications listing'))
);
}
}
/**
* Counts the number of users, host groups and service groups for given notifications.
*
* @param non-empty-array<int> $notificationsIds
*
* @throws \Throwable $ex
*
* @return NotificationCounts
*/
private function countUsersAndResourcesPerNotification(array $notificationsIds): NotificationCounts
{
$this->debug(
'Retrieving user counts for notifications',
['notification' => implode(', ', $notificationsIds)]
);
$isAdmin = $this->adminResolver->isAdmin($this->user);
if ($isAdmin === true) {
$numberOfUsers = $this->notificationRepository->countContactsByNotificationIds($notificationsIds);
} else {
$accessGroups = $this->readAccessGroupRepository->findByContact($this->user);
$numberOfUsers = $this->notificationRepository->countContactsByNotificationIdsAndAccessGroup(
$notificationsIds,
$this->user,
$accessGroups
);
}
$this->debug(sprintf('Found %d users for notifications', count($numberOfUsers)));
$repositories = $this->repositoryProvider->getRepositories();
$this->debug(
'Retrieving resource counts for notifications',
['notification' => implode(', ', $notificationsIds)]
);
$numberOfResources = $isAdmin === true
? $this->countResourcesForAdmin($repositories, $notificationsIds)
: $this->countResourcesWithACL($repositories, $notificationsIds);
$this->debug(sprintf('Found %d resources for notifications', count($numberOfResources)));
return new NotificationCounts($numberOfUsers, $numberOfResources);
}
/**
* Get count of resources by listed notifications id and ACL.
*
* @param NotificationResourceRepositoryInterface[] $repositories
* @param non-empty-array<int> $notificationsIds
*
* @throws \Throwable $ex
*
* @return array<string, array<int,int>>
*/
private function countResourcesWithACL(array $repositories, array $notificationsIds): array
{
$this->info(
'Retrieving host group resource counts for a non-admin user',
['user' => $this->user->getId()]
);
$accessGroups = $this->readAccessGroupRepository->findByContact($this->user);
$resourcesCount = [];
foreach ($repositories as $repository) {
$count = $repository->countResourcesByNotificationIdsAndAccessGroups($notificationsIds, $accessGroups);
$resourcesCount[$repository->resourceType()] = $count;
}
return $resourcesCount;
}
/**
* Get count of resources by listed notifications id.
*
* @param NotificationResourceRepositoryInterface[] $repositories
* @param non-empty-array<int> $notificationsIds
*
* @throws \Throwable $ex
*
* @return array<string, array<int,int>>
*/
private function countResourcesForAdmin(array $repositories, array $notificationsIds): array
{
$this->info('Retrieving host group resource counts for an admin user', ['user' => $this->user->getId()]);
$resourcesCount = [];
foreach ($repositories as $repository) {
$count = $repository->countResourcesByNotificationIds($notificationsIds);
$resourcesCount[$repository->resourceType()] = $count;
}
return $resourcesCount;
}
/**
* Create Response Object.
*
* @param Notification[] $notifications
* @param NotificationCounts $notificationCounts
* @param array<int, Channel[]> $notificationChannelByNotifications
*
* @return FindNotificationsResponse
*/
private function createResponse(
array $notifications,
NotificationCounts $notificationCounts,
array $notificationChannelByNotifications,
): FindNotificationsResponse {
$response = new FindNotificationsResponse();
$notificationDtos = [];
foreach ($notifications as $notification) {
$notificationDto = new NotificationDto();
$notificationDto->id = $notification->getId();
$notificationDto->name = $notification->getName();
$notificationDto->isActivated = $notification->isActivated();
if (($usersCount = $notificationCounts->getUsersCountByNotificationId($notification->getId())) !== 0) {
$notificationDto->usersCount = $usersCount;
}
$resourcesCounts = $notificationCounts->getResourcesCount();
foreach ($resourcesCounts as $type => $resourcesCount) {
$count = $resourcesCount[$notification->getId()] ?? 0;
if ($count !== 0) {
$notificationDto->resources[] = [
'type' => $type,
'count' => $count,
];
}
}
$notificationDto->timeperiodId = $notification->getTimePeriod()->getId();
$notificationDto->timeperiodName = $notification->getTimePeriod()->getName();
$notificationDto->notificationChannels = $notificationChannelByNotifications[$notification->getId()] ?? [];
$notificationDtos[] = $notificationDto;
}
$response->notifications = $notificationDtos;
return $response;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/FindNotifications/NotificationCounts.php | centreon/src/Core/Notification/Application/UseCase/FindNotifications/NotificationCounts.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\FindNotifications;
class NotificationCounts
{
/**
* @param array<int,int> $notificationsUsersCount
* @param array<string, array<int,int>> $resourcesCount
*/
public function __construct(
private readonly array $notificationsUsersCount,
private readonly array $resourcesCount,
) {
}
public function getUsersCountByNotificationId(int $notificationId): int
{
return $this->notificationsUsersCount[$notificationId] ?? 0;
}
/**
* @return array<string, array<int,int>>
*/
public function getResourcesCount(): array
{
return $this->resourcesCount;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/FindNotifications/FindNotificationsPresenterInterface.php | centreon/src/Core/Notification/Application/UseCase/FindNotifications/FindNotificationsPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\FindNotifications;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface FindNotificationsPresenterInterface
{
public function presentResponse(FindNotificationsResponse|ResponseStatusInterface $response): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/FindNotifications/NotificationDto.php | centreon/src/Core/Notification/Application/UseCase/FindNotifications/NotificationDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\FindNotifications;
use Core\Notification\Domain\Model\Channel;
class NotificationDto
{
public int $id = 0;
public string $name = '';
public int $usersCount = 0;
public bool $isActivated = true;
/** @var Channel[] */
public array $notificationChannels = [];
/**
* @var array<array{
* type: string,
* count: int
* }>
*/
public array $resources = [];
public int $timeperiodId = 0;
public string $timeperiodName = '';
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/UpdateNotification/UpdateNotification.php | centreon/src/Core/Notification/Application/UseCase/UpdateNotification/UpdateNotification.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\UpdateNotification;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Contact\Domain\AdminResolver;
use Core\Contact\Domain\Model\ContactGroup;
use Core\Notification\Application\Exception\NotificationException;
use Core\Notification\Application\Repository\NotificationResourceRepositoryInterface;
use Core\Notification\Application\Repository\NotificationResourceRepositoryProviderInterface;
use Core\Notification\Application\Repository\ReadNotificationRepositoryInterface;
use Core\Notification\Application\Repository\WriteNotificationRepositoryInterface;
use Core\Notification\Application\UseCase\UpdateNotification\Factory\NotificationFactory;
use Core\Notification\Application\UseCase\UpdateNotification\Factory\NotificationMessageFactory;
use Core\Notification\Application\UseCase\UpdateNotification\Factory\NotificationResourceFactory;
use Core\Notification\Application\UseCase\UpdateNotification\Validator\NotificationValidator;
use Core\Notification\Domain\Model\Message;
use Core\Notification\Domain\Model\Notification;
use Core\Notification\Domain\Model\NotificationResource;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
final class UpdateNotification
{
use LoggerTrait;
public function __construct(
private readonly ReadNotificationRepositoryInterface $readNotificationRepository,
private readonly WriteNotificationRepositoryInterface $writeNotificationRepository,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly NotificationResourceRepositoryProviderInterface $resourceRepositoryProvider,
private readonly DataStorageEngineInterface $dataStorageEngine,
private readonly NotificationValidator $notificationValidator,
private readonly NotificationFactory $notificationFactory,
private readonly NotificationResourceFactory $notificationResourceFactory,
private readonly ContactInterface $user,
private readonly AdminResolver $adminResolver,
) {
}
public function __invoke(UpdateNotificationRequest $request, UpdateNotificationPresenterInterface $presenter): void
{
if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_NOTIFICATIONS_READ_WRITE)) {
$this->error(
"User doesn't have sufficient rights to add notifications",
['user_id' => $this->user->getId()]
);
$presenter->presentResponse(new ForbiddenResponse(NotificationException::updateNotAllowed()));
return;
}
try {
$this->info('Update notification', ['request' => $request]);
if ($this->readNotificationRepository->exists($request->id) === false) {
$presenter->presentResponse(new NotFoundResponse('Notification'));
return;
}
$notification = $this->notificationFactory->create($request);
$messages = NotificationMessageFactory::createMultipleMessage($request->messages);
$resources = $this->notificationResourceFactory->createMultipleResource($request->resources);
$this->notificationValidator->validateUsersAndContactGroups(
$request->users,
$request->contactGroups,
$this->user
);
$this->updateNotificationConfiguration(
$notification,
$messages,
$request->users,
$request->contactGroups,
$resources
);
$presenter->presentResponse(new NoContentResponse());
} catch (NotificationException|AssertionFailedException|\ValueError $ex) {
$this->error('Unable to update notification configuration', ['trace' => (string) $ex]);
$presenter->presentResponse(
new InvalidArgumentResponse($ex->getMessage())
);
} catch (\Throwable $ex) {
$this->error('Unable to update notification configuration', ['trace' => (string) $ex]);
$presenter->presentResponse(
new ErrorResponse(_('Error while updating a notification configuration'))
);
}
}
/**
* @param Notification $notification
* @param Message[] $messages
* @param int[] $users
* @param int[] $contactGroups
* @param NotificationResource[] $resources
*
* @throws \Throwable
*/
private function updateNotificationConfiguration(
Notification $notification,
array $messages,
array $users,
array $contactGroups,
array $resources,
): void {
try {
$this->dataStorageEngine->startTransaction();
$this->writeNotificationRepository->updateNotification($notification);
$this->writeNotificationRepository->deleteNotificationMessages($notification->getId());
$this->writeNotificationRepository->addMessagesToNotification($notification->getId(), $messages);
$this->writeNotificationRepository->deleteUsersFromNotification($notification->getId());
$this->writeNotificationRepository->addUsersToNotification($notification->getId(), $users);
$this->updateResources($notification->getId(), $resources);
$this->updateContactGroups($notification->getId(), $contactGroups);
$this->dataStorageEngine->commitTransaction();
} catch (\Throwable $ex) {
$this->error("Rollback of 'Update Notification' transaction.");
$this->dataStorageEngine->rollbackTransaction();
throw $ex;
}
}
/**
* @param int $notificationId
* @param NotificationResource[] $resources
*
* @throws \Throwable
*/
private function updateResources(int $notificationId, array $resources): void
{
foreach ($this->resourceRepositoryProvider->getRepositories() as $repository) {
if (! $this->adminResolver->isAdmin($this->user)) {
$this->deleteResourcesForUserWithACL($repository, $notificationId);
} else {
$repository->deleteAllByNotification($notificationId);
}
}
foreach ($resources as $resourceType => $resource) {
$repository = $this->resourceRepositoryProvider->getRepository($resourceType);
$repository->add($notificationId, $resource);
}
}
/**
* Update the Notification's Contact Groups with ACL Calculation.
*
* @param int $notificationId
* @param int[] $contactGroups
*
* @throws \Throwable
*/
private function updateContactGroups(int $notificationId, array $contactGroups): void
{
if (! $this->adminResolver->isAdmin($this->user)) {
$this->deleteContactGroupsForUserWithACL($notificationId);
} else {
$this->writeNotificationRepository->deleteContactGroupsFromNotification($notificationId);
}
$this->writeNotificationRepository->addContactGroupsToNotification($notificationId, $contactGroups);
}
/**
* Delete Resources for a user with ACL.
*
* @param NotificationResourceRepositoryInterface $repository
* @param int $notificationId
*
* @throws \Throwable
*/
private function deleteResourcesForUserWithACL(
NotificationResourceRepositoryInterface $repository,
int $notificationId,
): void {
$accessGroups = $this->readAccessGroupRepository->findByContact($this->user);
$existingResources = $repository->findByNotificationIdAndAccessGroups($notificationId, $accessGroups);
if ($existingResources !== null && ! empty($existingResources->getResources())) {
$existingResourcesIds = [];
foreach ($existingResources->getResources() as $existingResource) {
$existingResourcesIds[] = $existingResource->getId();
}
$repository->deleteByNotificationIdAndResourcesId($notificationId, $existingResourcesIds);
}
}
/**
* Delete Contact Groups for a user with ACL.
*
* @param int $notificationId
*
* @throws \Throwable
*/
private function deleteContactGroupsForUserWithACL(int $notificationId): void
{
$accessGroups = $this->readAccessGroupRepository->findByContact($this->user);
$contactGroups = $this->readNotificationRepository->findContactGroupsByNotificationIdAndAccessGroups(
$notificationId,
$this->user,
$accessGroups
);
if ($contactGroups !== []) {
$contactGroupsIds = array_map(
fn (ContactGroup $contactGroup): int => $contactGroup->getId(),
$contactGroups
);
$this->writeNotificationRepository->deleteContactGroupsByNotificationAndContactGroupIds(
$notificationId,
$contactGroupsIds
);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/UpdateNotification/UpdateNotificationPresenterInterface.php | centreon/src/Core/Notification/Application/UseCase/UpdateNotification/UpdateNotificationPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\UpdateNotification;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface UpdateNotificationPresenterInterface
{
public function presentResponse(ResponseStatusInterface $response): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/UpdateNotification/UpdateNotificationRequest.php | centreon/src/Core/Notification/Application/UseCase/UpdateNotification/UpdateNotificationRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\UpdateNotification;
final class UpdateNotificationRequest
{
public int $id = 0;
public string $name = '';
public int $timePeriodId = 0;
/**
* User IDs.
*
* @var int[]
*/
public array $users = [];
/**
* Contact Groups IDs.
*
* @var int[]
*/
public array $contactGroups = [];
/**
* @var array<array{
* type:string,
* ids:int[],
* events:int,
* includeServiceEvents:int
* }> $resources
*/
public array $resources = [];
/** @var array<array{
* channel:string,
* subject:string,
* message:string,
* formatted_message:string
* }> $messages
*/
public array $messages = [];
public bool $isActivated = true;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/UpdateNotification/Validator/NotificationValidator.php | centreon/src/Core/Notification/Application/UseCase/UpdateNotification/Validator/NotificationValidator.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\UpdateNotification\Validator;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Contact\Application\Repository\ReadContactGroupRepositoryInterface;
use Core\Contact\Application\Repository\ReadContactRepositoryInterface;
use Core\Contact\Domain\AdminResolver;
use Core\Contact\Domain\Model\BasicContact;
use Core\Contact\Domain\Model\ContactGroup;
use Core\Notification\Application\Exception\NotificationException;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Utility\Difference\BasicDifference;
class NotificationValidator
{
use LoggerTrait;
private ContactInterface $currentContact;
public function __construct(
private readonly ReadContactRepositoryInterface $contactRepository,
private readonly ReadContactGroupRepositoryInterface $contactGroupRepository,
private readonly ReadAccessGroupRepositoryInterface $accessGroupRepository,
private readonly AdminResolver $adminResolver,
) {
}
/**
* Validate that provided user and contactgroup ids exists.
*
* @param int[] $userIds
* @param int[] $contactGroupsIds
* @param ContactInterface $currentContact
*
* @throws \Throwable|NotificationException
*/
public function validateUsersAndContactGroups(
array $userIds,
array $contactGroupsIds,
ContactInterface $currentContact,
): void {
if ($userIds === [] && $contactGroupsIds === []) {
throw NotificationException::emptyArrayNotAllowed('users, contactgroups');
}
$this->currentContact = $currentContact;
$isAdmin = $this->adminResolver->isAdmin($currentContact);
if ($userIds !== []) {
$this->validateUsers($userIds, $isAdmin);
}
if ($contactGroupsIds !== []) {
$this->validateContactGroups($contactGroupsIds, $isAdmin);
}
}
/**
* Validate that provided user ids exists.
*
* @param int[] $contactIdsToValidate
*
* @throws \Throwable|NotificationException
*/
private function validateUsers(array $contactIdsToValidate, bool $isAdmin): void
{
$contactIdsToValidate = array_unique($contactIdsToValidate);
if ($isAdmin === true) {
$existingContactIds = $this->contactRepository->retrieveExistingContactIds($contactIdsToValidate);
} else {
$accessGroups = $this->accessGroupRepository->findByContact($this->currentContact);
$existingContacts = $this->contactRepository->findByAccessGroupsAndUserAndRequestParameters(
$accessGroups,
$this->currentContact
);
$existingContactIds = array_map(fn (BasicContact $contact) => $contact->getId(), $existingContacts);
}
$contactDifference = new BasicDifference($contactIdsToValidate, $existingContactIds);
$missingContact = $contactDifference->getRemoved();
if ($missingContact !== []) {
$this->error(
'Invalid ID(s) provided',
['propertyName' => 'users', 'propertyValues' => array_values($missingContact)]
);
throw NotificationException::invalidId('users');
}
}
/**
* Validate that provided contact group ids exists.
*
* @param int[] $contactGroupIds
*
* @throws \Throwable|NotificationException
*/
private function validateContactGroups(array $contactGroupIds, bool $isAdmin): void
{
$contactGroupIds = array_unique($contactGroupIds);
if ($isAdmin === true) {
$contactGroups = $this->contactGroupRepository->findByIds($contactGroupIds);
} else {
$accessGroups = $this->accessGroupRepository->findByContact($this->currentContact);
$contactGroups = $this->contactGroupRepository->findByAccessGroupsAndUserAndRequestParameter(
$accessGroups,
$this->currentContact
);
}
$existingContactGroups = array_map(fn (ContactGroup $contactGroup) => $contactGroup->getId(), $contactGroups);
$difference = new BasicDifference($contactGroupIds, $existingContactGroups);
$missingContactGroups = $difference->getRemoved();
if ($missingContactGroups !== []) {
$this->error(
'Invalid ID(s) provided',
['propertyName' => 'contactgroups', 'propertyValues' => array_values($missingContactGroups)]
);
throw NotificationException::invalidId('contactgroups');
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/UpdateNotification/Factory/NotificationMessageFactory.php | centreon/src/Core/Notification/Application/UseCase/UpdateNotification/Factory/NotificationMessageFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\UpdateNotification\Factory;
use Core\Notification\Application\Exception\NotificationException;
use Core\Notification\Domain\Model\Channel;
use Core\Notification\Domain\Model\Message;
class NotificationMessageFactory
{
/**
* Create a NotificationMessage.
*
* @param Channel $messageType
* @param array{
* channel: string,
* subject: string,
* message: string,
* formatted_message: string
* } $message
*
* @throws \Assert\AssertionFailedException
*
* @return Message
*/
public static function create(Channel $messageType, array $message): Message
{
return new Message(
$messageType,
$message['subject'],
$message['message'],
$message['formatted_message']
);
}
/**
* Create multiple NotificationMessage.
*
* @param array<array{
* channel: string,
* subject: string,
* message: string,
* formatted_message: string
* }> $messages
*
* @throws \Assert\AssertionFailedException
*
* @return Message[]
*/
public static function createMultipleMessage(array $messages): array
{
if ($messages === []) {
throw NotificationException::emptyArrayNotAllowed('message');
}
$newMessages = [];
foreach ($messages as $message) {
$messageType = Channel::from($message['channel']);
// If multiple message with same type are defined, only the last one of each type is kept
$newMessages[$messageType->value] = self::create($messageType, $message);
}
return $newMessages;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/UpdateNotification/Factory/NotificationResourceFactory.php | centreon/src/Core/Notification/Application/UseCase/UpdateNotification/Factory/NotificationResourceFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\UpdateNotification\Factory;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Contact\Domain\AdminResolver;
use Core\Notification\Application\Converter\NotificationServiceEventConverter;
use Core\Notification\Application\Exception\NotificationException;
use Core\Notification\Application\Repository\NotificationResourceRepositoryInterface;
use Core\Notification\Application\Repository\NotificationResourceRepositoryProviderInterface;
use Core\Notification\Domain\Model\ConfigurationResource;
use Core\Notification\Domain\Model\NotificationResource;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Utility\Difference\BasicDifference;
class NotificationResourceFactory
{
use LoggerTrait;
public function __construct(
private NotificationResourceRepositoryProviderInterface $repositoryProvider,
private ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private ContactInterface $user,
private AdminResolver $adminResolver,
) {
}
/**
* Create a NotificationResource.
*
* @param NotificationResourceRepositoryInterface $repository
* @param array{
* type: string,
* ids: int[],
* events: int,
* includeServiceEvents: int
* } $resource
*
* @throws \Assert\AssertionFailedException
*
* @return NotificationResource
*/
public function create(NotificationResourceRepositoryInterface $repository, array $resource): NotificationResource
{
$resourceIds = array_unique($resource['ids']);
if ($this->adminResolver->isAdmin($this->user)) {
// Assert IDs validity without ACLs
$existingResources = $repository->exist($resourceIds);
} else {
// Assert IDs validity with ACLs
$accessGroups = $this->readAccessGroupRepository->findByContact($this->user);
$existingResources = $repository->existByAccessGroups($resourceIds, $accessGroups);
}
$difference = new BasicDifference($resourceIds, $existingResources);
$missingResources = $difference->getRemoved();
if ($missingResources !== []) {
$this->error(
'Invalid ID(s) provided',
['propertyName' => 'resources', 'propertyValues' => array_values($missingResources)]
);
throw NotificationException::invalidId('resource.ids');
}
// If multiple resources with same type are defined, only the last one of each type is kept
return new NotificationResource(
$repository->resourceType(),
$repository->eventEnum(),
array_map((fn ($resourceId) => new ConfigurationResource($resourceId, '')), $resourceIds),
($repository->eventEnumConverter())::fromBitFlags($resource['events']),
$resource['includeServiceEvents']
? NotificationServiceEventConverter::fromBitFlags($resource['includeServiceEvents'])
: []
);
}
/**
* Create multiple NotificationResource.
*
* @param array<array{
* type: string,
* ids: int[],
* events: int,
* includeServiceEvents: int
* }> $resources
*
* @throws \Assert\AssertionFailedException
*
* @return NotificationResource[]
*/
public function createMultipleResource(array $resources): array
{
if ($resources === []) {
throw NotificationException::emptyArrayNotAllowed('resource');
}
$newResources = [];
foreach ($resources as $resourceData) {
$resourceIds = array_unique($resourceData['ids']);
if ($resourceIds === []) {
continue;
}
$repository = $this->repositoryProvider->getRepository($resourceData['type']);
// If multiple resources with same type are defined, only the last one of each type is kept
$newResources[$repository->resourceType()] = $this->create($repository, $resourceData);
}
$totalResources = 0;
foreach ($newResources as $newResource) {
$totalResources += $newResource->getResourcesCount();
}
if ($totalResources <= 0) {
throw NotificationException::emptyArrayNotAllowed('resource.ids');
}
return $newResources;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/UseCase/UpdateNotification/Factory/NotificationFactory.php | centreon/src/Core/Notification/Application/UseCase/UpdateNotification/Factory/NotificationFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\UseCase\UpdateNotification\Factory;
use Assert\AssertionFailedException;
use Centreon\Domain\Log\LoggerTrait;
use Core\Common\Domain\TrimmedString;
use Core\Notification\Application\Exception\NotificationException;
use Core\Notification\Application\Repository\ReadNotificationRepositoryInterface;
use Core\Notification\Application\UseCase\UpdateNotification\UpdateNotificationRequest;
use Core\Notification\Domain\Model\Notification;
use Core\Notification\Domain\Model\TimePeriod;
class NotificationFactory
{
use LoggerTrait;
public function __construct(private readonly ReadNotificationRepositoryInterface $repository)
{
}
/**
* Create an instance of Notification.
*
* @param UpdateNotificationRequest $request
*
* @throws NotificationException
* @throws AssertionFailedException
*
* @return Notification
*/
public function create(UpdateNotificationRequest $request): Notification
{
$this->assertNameDoesNotAlreadyExists($request->name, $request->id);
return new Notification(
$request->id,
$request->name,
new TimePeriod($request->timePeriodId, ''),
$request->isActivated
);
}
/**
* Validate that a notification with this name doesn't already exist.
*
* @param string $name
* @param int $id
*
* @throws NotificationException
*/
private function assertNameDoesNotAlreadyExists(string $name, int $id): void
{
$notification = $this->repository->findByName(new TrimmedString($name));
if ($notification !== null && $notification->getId() !== $id) {
$this->error(
'Notification name already exists for another notification',
['name' => $name, 'existing_notification_id' => $notification->getId()]
);
throw NotificationException::nameAlreadyExists();
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/Exception/NotificationException.php | centreon/src/Core/Notification/Application/Exception/NotificationException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\Exception;
class NotificationException extends \Exception
{
public const CODE_CONFLICT = 1;
public static function addNotification(): self
{
return new self(_('Error when adding a notification configuration'));
}
public static function addNotAllowed(): self
{
return new self(_('You are not allowed to add a notification configuration'));
}
public static function errorWhileRetrievingObject(): self
{
return new self(_('Error while retrieving a notification configuration'));
}
public static function nameAlreadyExists(): self
{
return new self(_('The notification configuration name already exists'), self::CODE_CONFLICT);
}
public static function emptyArrayNotAllowed(string $name): self
{
return new self(sprintf(_('You must provide at least one %s'), $name), self::CODE_CONFLICT);
}
public static function invalidId(string $propertyName): self
{
return new self(sprintf(_('Invalid ID provided for %s'), $propertyName), self::CODE_CONFLICT);
}
public static function invalidResourceType(): self
{
return new self(_('Invalid resource type'), self::CODE_CONFLICT);
}
public static function listNotAllowed(): self
{
return new self(_('You are not allowed to list notifications configurations'));
}
public static function invalidUsers(int $notificationId): self
{
return new self(sprintf(_('Notification #%d should have at least one user'), $notificationId));
}
public static function listOneNotAllowed(): self
{
return new self(_('You are not allowed to display the details of the notification'));
}
public static function updateNotAllowed(): self
{
return new self(_('You are not allowed to update the notification configuration'));
}
public static function partialUpdateNotAllowed(): self
{
return new self(_('You are not allowed to partially update a notification configuration'));
}
public static function errorWhilePartiallyUpdatingObject(): self
{
return new self(_('Error while partially updating a notification configuration'));
}
public static function deleteNotAllowed(): self
{
return new self(_('You are not allowed to delete a notification configuration'));
}
public static function errorWhileDeletingObject(): self
{
return new self(_('Error while deleting a notification configuration'));
}
public static function listResourcesNotAllowed(): self
{
return new self(_('You are not allowed to list notification resources'));
}
public static function errorWhileListingResources(): self
{
return new self(_('Error while listing notification resources'));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/Converter/NotificationHostEventConverter.php | centreon/src/Core/Notification/Application/Converter/NotificationHostEventConverter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\Converter;
use Core\Notification\Domain\Model\HostEvent;
class NotificationHostEventConverter
{
private const CASE_UP_AS_BIT = 0b001;
private const CASE_DOWN_AS_BIT = 0b010;
private const CASE_UNREACHABLE_AS_BIT = 0b100;
private const MAX_BITFLAGS = 0b111;
private const CASE_UP_AS_STR = 'o';
private const CASE_DOWN_AS_STR = 'd';
private const CASE_UNREACHABLE_AS_STR = 'u';
/**
* Convert an array of NotificationHostEvent to a string.
* ex: [NotificationHostEvent::Down, NotificationHostEvent::Unreachable] => 'd,u'.
*
* @param HostEvent[] $events
*
* @return string
*/
public static function toString(array $events): string
{
$eventsAsBitFlags = [];
foreach ($events as $event) {
$eventsAsBitFlags[] = match ($event) {
HostEvent::Up => self::CASE_UP_AS_STR,
HostEvent::Down => self::CASE_DOWN_AS_STR,
HostEvent::Unreachable => self::CASE_UNREACHABLE_AS_STR,
};
}
return implode(',', array_unique($eventsAsBitFlags));
}
/**
* Convert a string to an array of NotificationHostEvent.
* ex: 'd,u' => [NotificationHostEvent::Down, NotificationHostEvent::Unreachable].
*
* @param string $legacyStr
*
* @return HostEvent[]
*/
public static function fromString(string $legacyStr): array
{
if ($legacyStr === '') {
return [];
}
$legacyValues = explode(',', $legacyStr);
$legacyValues = array_unique(array_map(trim(...), $legacyValues));
$events = [];
foreach ($legacyValues as $value) {
$events[] = match ($value) {
self::CASE_UP_AS_STR => HostEvent::Up,
self::CASE_DOWN_AS_STR => HostEvent::Down,
self::CASE_UNREACHABLE_AS_STR => HostEvent::Unreachable,
default => throw new \LogicException('Should never occur, only for phpstan'),
};
}
return $events;
}
/**
* Convert a NotificationHostEvent into bitFlags.
*
* @param HostEvent $event
*
* @return int
*/
public static function toBit(HostEvent $event): int
{
return match ($event) {
HostEvent::Up => self::CASE_UP_AS_BIT,
HostEvent::Down => self::CASE_DOWN_AS_BIT,
HostEvent::Unreachable => self::CASE_UNREACHABLE_AS_BIT,
};
}
/**
* Convert a bitFlags into an array of NotificationHostEvent.
*
* @param int $bitFlags
*
* @throws \Throwable
*
* @return HostEvent[]
*/
public static function fromBitFlags(int $bitFlags): array
{
if ($bitFlags > self::MAX_BITFLAGS || $bitFlags < 0) {
throw new \ValueError("\"{$bitFlags}\" is not a valid bit flag for enum NotificationHostEvent");
}
$enums = [];
foreach (HostEvent::cases() as $enum) {
if ($bitFlags & self::toBit($enum)) {
$enums[] = $enum;
}
}
return $enums;
}
/**
* Convert an array of NotificationHostEvent into a bitFlags
* If the array contains NotificationHostEvent::None or is empty, an empty bitFlags will be returned.
*
* @param HostEvent[] $enums
*
* @return int
*/
public static function toBitFlags(array $enums): int
{
if ($enums === []) {
return 0;
}
$bitFlags = 0;
foreach ($enums as $event) {
// Value 0 is not a bit, we consider it resets the bitFlags
if (self::toBit($event) === 0) {
return 0;
}
$bitFlags |= self::toBit($event);
}
return $bitFlags;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/Converter/NotificationServiceEventConverter.php | centreon/src/Core/Notification/Application/Converter/NotificationServiceEventConverter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\Converter;
use Core\Notification\Domain\Model\ServiceEvent;
class NotificationServiceEventConverter
{
private const CASE_OK_AS_BIT = 0b0001;
private const CASE_WARNING_AS_BIT = 0b0010;
private const CASE_CRITICAL_AS_BIT = 0b0100;
private const CASE_UNKNOWN_AS_BIT = 0b1000;
private const MAX_BITFLAGS = 0b1111;
private const CASE_OK_AS_STR = 'o';
private const CASE_WARNING_AS_STR = 'w';
private const CASE_CRITICAL_AS_STR = 'c';
private const CASE_UNKNOWN_AS_STR = 'u';
/**
* Convert an array of NotificationServiceEvent to a string.
* ex: [NotificationServiceEvent::Ok, NotificationServiceEvent::Unknown] => 'o,u'.
*
* @param ServiceEvent[] $events
*
* @return string
*/
public static function toString(array $events): string
{
$eventsAsBitFlags = [];
foreach ($events as $event) {
$eventsAsBitFlags[] = match ($event) {
ServiceEvent::Ok => self::CASE_OK_AS_STR,
ServiceEvent::Warning => self::CASE_WARNING_AS_STR,
ServiceEvent::Critical => self::CASE_CRITICAL_AS_STR,
ServiceEvent::Unknown => self::CASE_UNKNOWN_AS_STR,
};
}
return implode(',', array_unique($eventsAsBitFlags));
}
/**
* Convert a string to an array of NotificationServiceEvent.
* ex: 'd,u' => [NotificationServiceEvent::Down, NotificationServiceEvent::Unreachable].
*
* @param string $legacyStr
*
* @return ServiceEvent[]
*/
public static function fromString(string $legacyStr): array
{
if ($legacyStr === '') {
return [];
}
$legacyValues = explode(',', $legacyStr);
$legacyValues = array_unique(array_map(trim(...), $legacyValues));
$events = [];
foreach ($legacyValues as $value) {
$events[] = match ($value) {
self::CASE_OK_AS_STR => ServiceEvent::Ok,
self::CASE_WARNING_AS_STR => ServiceEvent::Warning,
self::CASE_CRITICAL_AS_STR => ServiceEvent::Critical,
self::CASE_UNKNOWN_AS_STR => ServiceEvent::Unknown,
default => throw new \LogicException('Should never occur, only for phpstan'),
};
}
return $events;
}
/**
* Convert a NotificationServiceEvent into bitFlags.
*
* @param ServiceEvent $event
*
* @return int
*/
public static function toBit(ServiceEvent $event): int
{
return match ($event) {
ServiceEvent::Ok => self::CASE_OK_AS_BIT,
ServiceEvent::Warning => self::CASE_WARNING_AS_BIT,
ServiceEvent::Critical => self::CASE_CRITICAL_AS_BIT,
ServiceEvent::Unknown => self::CASE_UNKNOWN_AS_BIT,
};
}
/**
* Convert a bitmask into an array of NotificationServiceEvent.
*
* @param int $bitFlags
*
* @throws \Throwable
*
* @return ServiceEvent[]
*/
public static function fromBitFlags(int $bitFlags): array
{
if ($bitFlags > self::MAX_BITFLAGS || $bitFlags < 0) {
throw new \ValueError("\"{$bitFlags}\" is not a valid bitFlags for enum NotificationServiceEvent");
}
$enums = [];
foreach (ServiceEvent::cases() as $enum) {
if ($bitFlags & self::toBit($enum)) {
$enums[] = $enum;
}
}
return $enums;
}
/**
* Convert an array of NotificationServiceEvent into a bitFlags
* If the array contains NotificationServiceEvent::None or is empty, an empty bitFlags will be returned.
*
* @param ServiceEvent[] $enums
*
* @return int
*/
public static function toBitFlags(array $enums): int
{
if ($enums === []) {
return 0;
}
$bitFlags = 0;
foreach ($enums as $event) {
// Value 0 is not a bit, we consider it resets the bitFlags
if (self::toBit($event) === 0) {
return 0;
}
$bitFlags |= self::toBit($event);
}
return $bitFlags;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/Repository/NotificationResourceRepositoryInterface.php | centreon/src/Core/Notification/Application/Repository/NotificationResourceRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\Repository;
use Core\Notification\Application\Converter\NotificationHostEventConverter;
use Core\Notification\Application\Converter\NotificationServiceEventConverter;
use Core\Notification\Application\Repository\ReadNotificationResourceRepositoryInterface as ReadRepositoryInterface;
use Core\Notification\Application\Repository\WriteNotificationResourceRepositoryInterface as WriteRepositoryInterface;
use Core\Notification\Domain\Model\HostEvent;
use Core\Notification\Domain\Model\NotificationResource;
use Core\Notification\Domain\Model\ServiceEvent;
interface NotificationResourceRepositoryInterface extends ReadRepositoryInterface, WriteRepositoryInterface
{
/**
* Indicate whether the repository is valid for the provided resource type.
*
* @param string $type
*
* @return bool
*/
public function supportResourceType(string $type): bool;
/**
* Get associated Event enum class.
*
* @return class-string<HostEvent|ServiceEvent>
*/
public function eventEnum(): string;
/**
* Get associated Event enum converter class.
*
* @return class-string<NotificationHostEventConverter|NotificationServiceEventConverter>
*/
public function eventEnumConverter(): string;
/**
* Get associated resource type.
*
* @return NotificationResource::TYPE_*
*/
public function resourceType(): string;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/Repository/WriteNotificationRepositoryInterface.php | centreon/src/Core/Notification/Application/Repository/WriteNotificationRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\Repository;
use Centreon\Domain\Repository\RepositoryException;
use Core\Notification\Domain\Model\Message;
use Core\Notification\Domain\Model\NewNotification;
use Core\Notification\Domain\Model\Notification;
interface WriteNotificationRepositoryInterface
{
/**
* Add a notification
* Return the id of the notification.
*
* @param NewNotification $notification
*
* @throws \Throwable
*
* @return int
*/
public function addNewNotification(NewNotification $notification): int;
/**
* Add messages to a notification.
*
* @param int $notificationId
* @param Message[] $messages
*
* @throws \Throwable
*/
public function addMessagesToNotification(int $notificationId, array $messages): void;
/**
* Add users to a notification.
*
* @param int $notificationId
* @param int[] $userIds
*
* @throws \Throwable
*/
public function addUsersToNotification(int $notificationId, array $userIds): void;
/**
* Add Contact Groups to a notification.
*
* @param int $notificationId
* @param int[] $contactGroupIds
*
* @throws \Throwable
*/
public function addContactGroupsToNotification(int $notificationId, array $contactGroupIds): void;
/**
* Update notification.
*
* @param Notification $notification
*
* @throws \Throwable
*/
public function updateNotification(Notification $notification): void;
/**
* delete all the messages of a notification.
*
* @param int $notificationId
*
* @throws \Throwable
*/
public function deleteNotificationMessages(int $notificationId): void;
/**
* delete all the users of a notification.
*
* @param int $notificationId
*
* @throws \Throwable
*/
public function deleteUsersFromNotification(int $notificationId): void;
/**
* delete all the contactGroups of a notification.
*
* @param int $notificationId
*
* @throws \Throwable
*/
public function deleteContactGroupsFromNotification(int $notificationId): void;
/**
* delete the given contactGroups of a notification.
*
* @param int $notificationId
* @param int[] $contactGroupsIds
*
* @throws \Throwable
*/
public function deleteContactGroupsByNotificationAndContactGroupIds(
int $notificationId,
array $contactGroupsIds,
): void;
/**
* Delete a notification.
*
* @param int $notificationId
*
* @throws \Throwable|RepositoryException
*
* @return int
*/
public function deleteNotification(int $notificationId): int;
/**
* Delete multiple dependencies.
*
* @param int[] $dependencyIds
*
* @throws \Throwable
*/
public function deleteDependencies(array $dependencyIds): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/Repository/ReadNotifiableResourceRepositoryInterface.php | centreon/src/Core/Notification/Application/Repository/ReadNotifiableResourceRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\Repository;
use Core\Notification\Domain\Model\NotifiableResource;
interface ReadNotifiableResourceRepositoryInterface
{
/**
* Return all notification resources (hosts, services, metaservices) and resources' events for activated
* notifications.
*
* @throws \Throwable
*
* @return iterable<NotifiableResource>
*/
public function findAllForActivatedNotifications(): iterable;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/Repository/ReadNotificationResourceRepositoryInterface.php | centreon/src/Core/Notification/Application/Repository/ReadNotificationResourceRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\Repository;
use Core\Notification\Domain\Model\NotificationResource;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
interface ReadNotificationResourceRepositoryInterface
{
/**
* Indicate whether the IDs provided exist (without ACLs)
* Return an array of the existing resource IDs out of the provided ones.
*
* @param int[] $resourceIds
*
* @throws \Throwable
*
* @return int[]
*/
public function exist(array $resourceIds): array;
/**
* Indicate whether the IDs provided exist (with ACLs)
* Return an array of the existing resource IDs out of the provided ones.
*
* @param int[] $resourceIds
* @param AccessGroup[] $accessGroups
*
* @throws \Throwable
*
* @return int[]
*/
public function existByAccessGroups(array $resourceIds, array $accessGroups): array;
/**
* Retrieve a notification resource by notification ID.
*
* @param int $notificationId
*
* @throws \Throwable
*
* @return null|NotificationResource
*/
public function findByNotificationId(int $notificationId): ?NotificationResource;
/**
* Retrieve a notification resource by notification ID and AccessGroups.
*
* @param int $notificationId
* @param AccessGroup[] $accessGroups
*
* @throws \Throwable
*
* @return null|NotificationResource
*/
public function findByNotificationIdAndAccessGroups(
int $notificationId,
array $accessGroups,
): ?NotificationResource;
/**
* Count the Resource by their notification id.
*
* @param non-empty-array<int> $notificationIds
* @param AccessGroup[] $accessGroups
*
* @return array<int,int> [notification_id => resource_count]
*/
public function countResourcesByNotificationIdsAndAccessGroups(
array $notificationIds,
array $accessGroups,
): array;
/**
* Count the Resource by their notification id.
*
* @param non-empty-array<int> $notificationIds
*
* @return array<int,int> [notification_id => resource_count]
*/
public function countResourcesByNotificationIds(array $notificationIds): array;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/Repository/WriteNotificationResourceRepositoryInterface.php | centreon/src/Core/Notification/Application/Repository/WriteNotificationResourceRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\Repository;
use Core\Notification\Domain\Model\NotificationResource;
interface WriteNotificationResourceRepositoryInterface
{
/**
* Add a notification resource and associated event configuration.
*
* @param int $notificationId
* @param NotificationResource $resource
*
* @throws \Throwable
*/
public function add(int $notificationId, NotificationResource $resource): void;
/**
* Delete given resources for a notification.
*
* @param int $notificationId
* @param int[] $resourcesIds
*
* @throws \Throwable
*/
public function deleteByNotificationIdAndResourcesId(int $notificationId, array $resourcesIds): void;
/**
* Delete all the resources of a notification.
*
* @param int $notificationId
*
* @throws \Throwable
*/
public function deleteAllByNotification(int $notificationId): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/Repository/NotifiableResourceRequestProviderInterface.php | centreon/src/Core/Notification/Application/Repository/NotifiableResourceRequestProviderInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\Repository;
interface NotifiableResourceRequestProviderInterface
{
/**
* @return string
*/
public function getNotifiableResourceSubRequest(): string;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/Repository/ReadNotificationRepositoryInterface.php | centreon/src/Core/Notification/Application/Repository/ReadNotificationRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\Repository;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Common\Domain\TrimmedString;
use Core\Contact\Domain\Model\ContactGroup;
use Core\Notification\Domain\Model\Channel;
use Core\Notification\Domain\Model\Contact;
use Core\Notification\Domain\Model\Message;
use Core\Notification\Domain\Model\Notification;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
interface ReadNotificationRepositoryInterface
{
/**
* Find one notification.
*
* @param int $notificationId
*
* @throws \Throwable
*
* @return Notification|null
*/
public function findById(int $notificationId): ?Notification;
/**
* Find one notification by its name.
*
* @param TrimmedString $notificationName
*
* @throws \Throwable
*
* @return Notification|null
*/
public function findByName(TrimmedString $notificationName): ?Notification;
/**
* Find notification message for a notification.
*
* @param int $notificationId
*
* @throws \Throwable
*
* @return Message[]
*/
public function findMessagesByNotificationId(int $notificationId): array;
/**
* Find notification channels for multiple notification.
*
* @param non-empty-array<int> $notificationIds
*
* @return array<int, Channel[]> [notification_id => ["Slack","Sms","Email"]]
*/
public function findNotificationChannelsByNotificationIds(array $notificationIds): array;
/**
* Find notification users and those defined in contact groups.
*
* @param int $notificationId
*
* @throws \Throwable
*
* @return array<int, Contact>
*/
public function findUsersByNotificationId(int $notificationId): array;
/**
* Find notification users and those defined in contact groups by access groups and user based on ACL.
*
* @param int $notificationId
* @param ContactInterface $user
* @param AccessGroup[] $accessGroups
*
* @throws \Throwable
*
* @return array<int, Contact>
*/
public function findUsersByNotificationIdUserAndAccessGroups(
int $notificationId,
ContactInterface $user,
array $accessGroups,
): array;
/**
* Find notification users for a list of contact group Ids.
*
* @param int ...$contactGroupIds
*
* @throws \Throwable
*
* @return array<int, Contact>
*/
public function findUsersByContactGroupIds(int ...$contactGroupIds): array;
/**
* Find notification Contact Groups for a notification.
*
* @param int $notificationId
*
* @throws \Throwable
*
* @return ContactGroup[]
*/
public function findContactGroupsByNotificationId(int $notificationId): array;
/**
* Count notification users for notifications.
*
* @param int[] $notificationIds
*
* @throws \Throwable
*
* @return array<int,int> [notification_id => user_count]
*/
public function countContactsByNotificationIds(array $notificationIds): array;
/**
* Count notification users for notifications by access groups and current user based on ACL.
*
* @param int[] $notificationIds
* @param ContactInterface $user
* @param AccessGroup[] $accessGroups
*
* @throws \Throwable
*
* @return array<int,int> [notification_id => user_count]
*/
public function countContactsByNotificationIdsAndAccessGroup(
array $notificationIds,
ContactInterface $user,
array $accessGroups,
): array;
/**
* Find notification Contact Groups linked to a given user for a notification.
*
* @param int $notificationId
* @param ContactInterface $user
* @param AccessGroup[] $accessGroups
*
* @throws \Throwable
*
* @return ContactGroup[]
*/
public function findContactGroupsByNotificationIdAndAccessGroups(
int $notificationId,
ContactInterface $user,
array $accessGroups,
): array;
/**
* Tells whether the notification exists.
*
* @param int $notificationId
*
* @throws \Throwable
*
* @return bool
*/
public function exists(int $notificationId): bool;
/**
* Tells whether the notification name already exists.
* This method does not need an acl version of it.
*
* @param TrimmedString $notificationName
*
* @throws \Throwable
*
* @return bool
*/
public function existsByName(TrimmedString $notificationName): bool;
/**
* Return all the notifications.
*
* @param RequestParametersInterface|null $requestParameters
*
* @throws \Throwable
*
* @return Notification[]
*/
public function findAll(?RequestParametersInterface $requestParameters): array;
/**
* Return the dependency ids where the given host group is the only one linked to.
*
* @param int $hostGroupId
*
* @throws \Throwable
*
* @return int[]
*/
public function findLastNotificationDependencyIdsByHostGroup(int $hostGroupId): array;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Application/Repository/NotificationResourceRepositoryProviderInterface.php | centreon/src/Core/Notification/Application/Repository/NotificationResourceRepositoryProviderInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Application\Repository;
interface NotificationResourceRepositoryProviderInterface
{
/**
* Return the repository matching the provided type.
*
* @param string $type
*
* @return NotificationResourceRepositoryInterface
*/
public function getRepository(string $type): NotificationResourceRepositoryInterface;
/**
* Return all repositories.
*
* @return NotificationResourceRepositoryInterface[]
*/
public function getRepositories(): array;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Domain/Model/ServiceEvent.php | centreon/src/Core/Notification/Domain/Model/ServiceEvent.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Domain\Model;
enum ServiceEvent
{
case Ok;
case Warning;
case Critical;
case Unknown;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Domain/Model/ConfigurationResource.php | centreon/src/Core/Notification/Domain/Model/ConfigurationResource.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Domain\Model;
use Centreon\Domain\Common\Assertion\Assertion;
class ConfigurationResource
{
/**
* @param int $id
* @param string $name
*
* @throws \Assert\AssertionFailedException
*/
public function __construct(
private readonly int $id,
private readonly string $name,
) {
Assertion::positiveInt($id, 'Resource::id');
}
/**
* Get the resource id.
*
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* Get the resource name.
*
* @return string
*/
public function getName(): string
{
return $this->name;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Domain/Model/TimePeriod.php | centreon/src/Core/Notification/Domain/Model/TimePeriod.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Domain\Model;
use Centreon\Domain\Common\Assertion\Assertion;
class TimePeriod
{
public const ALL_TIME_PERIOD = '24x7';
/**
* @param int $id
* @param string $name
*
* @throws \Assert\AssertionFailedException
*/
public function __construct(
private readonly int $id,
private readonly string $name,
) {
Assertion::positiveInt($id, 'timePeriod::id');
}
/**
* Get the time period id.
*
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* Get the time period name.
*
* @return string
*/
public function getName(): string
{
return $this->name;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Domain/Model/HostEvent.php | centreon/src/Core/Notification/Domain/Model/HostEvent.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Domain\Model;
enum HostEvent
{
case Up;
case Down;
case Unreachable;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Domain/Model/Notification.php | centreon/src/Core/Notification/Domain/Model/Notification.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Domain\Model;
use Centreon\Domain\Common\Assertion\Assertion;
class Notification extends NewNotification
{
/**
* @param int $id
* @param string $name
* @param TimePeriod $timePeriod
* @param bool $isActivated
*
* @throws \Assert\AssertionFailedException
*/
public function __construct(
private readonly int $id,
string $name,
TimePeriod $timePeriod,
bool $isActivated = true,
) {
Assertion::positiveInt($id, 'Notification::id');
parent::__construct(
$name,
$timePeriod,
$isActivated
);
}
public function getId(): int
{
return $this->id;
}
public function setIsActivated(bool $isActivated): self
{
$this->isActivated = $isActivated;
return $this;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Domain/Model/NotifiableHost.php | centreon/src/Core/Notification/Domain/Model/NotifiableHost.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Domain\Model;
class NotifiableHost
{
/**
* @param int $id
* @param string $name
* @param string|null $alias
* @param array<HostEvent> $events
* @param array<NotifiableService> $services
*/
public function __construct(
private readonly int $id,
private readonly string $name,
private readonly ?string $alias,
private readonly array $events,
private readonly array $services = [],
) {
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @return string|null
*/
public function getAlias(): ?string
{
return $this->alias;
}
/**
* @return array<HostEvent>
*/
public function getEvents(): array
{
return $this->events;
}
/**
* @return array<NotifiableService>
*/
public function getServices(): array
{
return $this->services;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Domain/Model/ResponseCode.php | centreon/src/Core/Notification/Domain/Model/ResponseCode.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Domain\Model;
enum ResponseCode
{
case OK;
case NotFound;
case Error;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Domain/Model/Channel.php | centreon/src/Core/Notification/Domain/Model/Channel.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Domain\Model;
enum Channel: string
{
case Email = 'Email';
case Sms = 'Sms';
case Slack = 'Slack';
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Domain/Model/NotifiableService.php | centreon/src/Core/Notification/Domain/Model/NotifiableService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Domain\Model;
class NotifiableService
{
/**
* @param int $id
* @param string $name
* @param string|null $alias
* @param array<ServiceEvent> $events
*/
public function __construct(
private readonly int $id,
private readonly string $name,
private readonly ?string $alias,
private readonly array $events,
) {
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @return string|null
*/
public function getAlias(): ?string
{
return $this->alias;
}
/**
* @return array<ServiceEvent>
*/
public function getEvents(): array
{
return $this->events;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Domain/Model/NotificationResource.php | centreon/src/Core/Notification/Domain/Model/NotificationResource.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Domain\Model;
class NotificationResource
{
public const TYPE_HOST_GROUP = 'hostgroup';
public const TYPE_SERVICE_GROUP = 'servicegroup';
/**
* @param self::TYPE_* $type
* @param class-string<HostEvent|ServiceEvent> $eventEnum
* @param ConfigurationResource[] $resources
* @param array<HostEvent|ServiceEvent> $events
* @param ServiceEvent[] $serviceEvents
*
* @throws \ValueError
*/
public function __construct(
private readonly string $type,
private readonly string $eventEnum,
private readonly array $resources,
private array $events,
private array $serviceEvents = [],
) {
$this->setEvents($events);
$this->setServiceEvents($serviceEvents);
}
/**
* @return self::TYPE_*
*/
public function getType(): string
{
return $this->type;
}
/**
* @return ConfigurationResource[]
*/
public function getResources(): array
{
return $this->resources;
}
/**
* @return int
*/
public function getResourcesCount(): int
{
return count($this->resources);
}
/**
* @return array<HostEvent>|array<ServiceEvent>
*/
public function getEvents(): array
{
return $this->events;
}
/**
* @param HostEvent|ServiceEvent $event
*
* @throws \ValueError
*/
public function addEvent(HostEvent|ServiceEvent $event): void
{
if ($event instanceof $this->eventEnum) {
$this->events[] = $event;
} else {
throw new \ValueError("\"{$event->name}\" is not a valid backing value for enum {$this->eventEnum}");
}
}
/**
* Should only be used for Notification of type host group.
*
* @return ServiceEvent[]
*/
public function getServiceEvents(): array
{
return $this->serviceEvents;
}
/**
* Should only be used for Notification of type host group.
*
* @param ServiceEvent $serviceEvent
*/
public function addServiceEvent(ServiceEvent $serviceEvent): void
{
$this->serviceEvents[] = $serviceEvent;
}
/**
* @param array<HostEvent>|array<ServiceEvent> $events
*
* @throws \ValueError
*/
private function setEvents(array $events): void
{
$this->events = [];
foreach ($events as $event) {
$this->addEvent($event);
}
}
/**
* Should only be used for Notification of type hostgroup.
*
* @param ServiceEvent[] $serviceEvents
*/
private function setServiceEvents(array $serviceEvents): void
{
$this->serviceEvents = [];
foreach ($serviceEvents as $serviceEvent) {
$this->addServiceEvent($serviceEvent);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Domain/Model/NotifiableResource.php | centreon/src/Core/Notification/Domain/Model/NotifiableResource.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Domain\Model;
class NotifiableResource
{
/**
* @param int $notificationId
* @param array<NotifiableHost> $hosts
*/
public function __construct(
private readonly int $notificationId,
private readonly array $hosts,
) {
}
/**
* @return int
*/
public function getNotificationId(): int
{
return $this->notificationId;
}
/**
* @return array<NotifiableHost>
*/
public function getHosts(): array
{
return $this->hosts;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Domain/Model/NewNotification.php | centreon/src/Core/Notification/Domain/Model/NewNotification.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Domain\Model;
use Centreon\Domain\Common\Assertion\Assertion;
class NewNotification
{
public const MAX_NAME_LENGTH = 255;
/**
* @param string $name
* @param TimePeriod $timePeriod
* @param bool $isActivated
*
* @throws \Assert\AssertionFailedException
*/
public function __construct(
protected string $name,
protected TimePeriod $timePeriod,
protected bool $isActivated = true,
) {
$shortName = (new \ReflectionClass($this))->getShortName();
$this->name = trim($this->name);
Assertion::notEmptyString($this->name, "{$shortName}::name");
Assertion::maxLength($this->name, self::MAX_NAME_LENGTH, "{$shortName}::name");
}
public function getName(): string
{
return $this->name;
}
public function getTimePeriod(): TimePeriod
{
return $this->timePeriod;
}
public function isActivated(): bool
{
return $this->isActivated;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Domain/Model/Message.php | centreon/src/Core/Notification/Domain/Model/Message.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Domain\Model;
use Centreon\Domain\Common\Assertion\Assertion;
class Message
{
public const MAX_SUBJECT_LENGTH = 255;
public const MAX_MESSAGE_LENGTH = 65535;
/**
* @param Channel $channel
* @param string $subject
* @param string $message
* @param string $formattedMessage
*
* @throws \Assert\AssertionFailedException
*/
public function __construct(
protected Channel $channel,
protected string $subject = '',
protected string $message = '',
protected string $formattedMessage = '',
) {
$shortName = (new \ReflectionClass($this))->getShortName();
$this->subject = trim($subject);
$this->message = trim($message);
$this->formattedMessage = trim($formattedMessage);
Assertion::notEmptyString($this->subject, "{$shortName}::subject");
Assertion::notEmptyString($this->message, "{$shortName}::message");
Assertion::maxLength($this->subject, self::MAX_SUBJECT_LENGTH, "{$shortName}::subject");
Assertion::maxLength($this->message, self::MAX_MESSAGE_LENGTH, "{$shortName}::message");
Assertion::maxLength($this->formattedMessage, self::MAX_MESSAGE_LENGTH, "{$shortName}::formattedMessage");
}
public function getChannel(): Channel
{
return $this->channel;
}
public function getSubject(): string
{
return $this->subject;
}
public function getRawMessage(): string
{
return $this->message;
}
public function getFormattedMessage(): string
{
return $this->formattedMessage;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Domain/Model/Contact.php | centreon/src/Core/Notification/Domain/Model/Contact.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
class Contact
{
/**
* @param int $id
* @param string $name
* @param string $email
*
* @throws AssertionFailedException
*/
public function __construct(
private readonly int $id,
private readonly string $name,
private readonly string $email,
private readonly string $alias,
) {
Assertion::positiveInt($id, 'User::id');
Assertion::notEmpty($name, 'User::name');
Assertion::notEmpty($email, 'User::email');
Assertion::notEmpty($alias, 'User::alias');
}
/**
* Get the user id.
*
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* Get the username, ie "full name".
*
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* Get the email.
*
* @return string
*/
public function getEmail(): string
{
return $this->email;
}
public function getAlias(): string
{
return $this->alias;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Infrastructure/Repository/ServiceGroupRequestProvider.php | centreon/src/Core/Notification/Infrastructure/Repository/ServiceGroupRequestProvider.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Infrastructure\Repository;
use Core\Notification\Application\Repository\NotifiableResourceRequestProviderInterface;
class ServiceGroupRequestProvider implements NotifiableResourceRequestProviderInterface
{
/**
* @inheritDoc
*/
public function getNotifiableResourceSubRequest(): string
{
return <<<'SQL'
SELECT n.`id` AS `notification_id`,
hsr.`host_host_id` AS `host_id`,
h.`host_name` AS `host_name`,
h.`host_alias` AS `host_alias`,
n.`hostgroup_events` AS `host_events`,
s.`service_id` AS `service_id`,
s.`service_description` AS `service_name`,
s.`service_alias` AS `service_alias`,
n.`servicegroup_events` AS `service_events`,
0 AS `included_service_events`
FROM `:db`.`service` s
INNER JOIN `:db`.`servicegroup_relation` sgr ON sgr.`service_service_id` = s.`service_id`
INNER JOIN `:db`.`host_service_relation` hsr ON hsr.`service_service_id` = s.`service_id`
INNER JOIN `:db`.`notification_sg_relation` nsgr ON nsgr.`sg_id` = sgr.`servicegroup_sg_id`
INNER JOIN `:db`.`notification` n ON n.`id` = nsgr.`notification_id`
INNER JOIN `:db`.`host` h ON h.`host_id` = hsr.`host_host_id`
WHERE n.`is_activated` = 1
SQL;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Infrastructure/Repository/DbReadNotificationRepository.php | centreon/src/Core/Notification/Infrastructure/Repository/DbReadNotificationRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Infrastructure\Repository;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use Core\Common\Domain\TrimmedString;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait;
use Core\Contact\Domain\Model\ContactGroup;
use Core\Notification\Application\Repository\ReadNotificationRepositoryInterface;
use Core\Notification\Domain\Model\Channel;
use Core\Notification\Domain\Model\Contact;
use Core\Notification\Domain\Model\Message;
use Core\Notification\Domain\Model\Notification;
use Core\Notification\Domain\Model\TimePeriod;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
class DbReadNotificationRepository extends AbstractRepositoryRDB implements ReadNotificationRepositoryInterface
{
use LoggerTrait;
use SqlMultipleBindTrait;
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* {@inheritDoc}
*/
public function findById(int $notificationId): ?Notification
{
$this->info('Get a notification configuration with ID #' . $notificationId);
$request = $this->translateDbName(
<<<'SQL'
SELECT id, name, timeperiod_id, tp_name, is_activated
FROM `:db`.notification
INNER JOIN timeperiod ON timeperiod_id = tp_id
WHERE id = :notificationId
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':notificationId', $notificationId, \PDO::PARAM_INT);
$statement->execute();
$result = $statement->fetch(\PDO::FETCH_ASSOC);
if ($result === false) {
return null;
}
/**
* @var array{id:int,name:string,timeperiod_id:int,tp_name:string,is_activated:int} $result
*/
return new Notification(
$result['id'],
$result['name'],
new TimePeriod($result['timeperiod_id'], $result['tp_name']),
(bool) $result['is_activated'],
);
}
/**
* {@inheritDoc}
*/
public function findByName(TrimmedString $notificationName): ?Notification
{
$statement = $this->db->prepare(
$this->translateDbName(
<<<'SQL'
SELECT id, name, timeperiod_id, tp_name, is_activated
FROM `:db`.notification
INNER JOIN timeperiod ON timeperiod_id = tp_id
WHERE name = :notificationName
SQL
)
);
$statement->bindValue(':notificationName', $notificationName, \PDO::PARAM_STR);
$statement->execute();
$result = $statement->fetch(\PDO::FETCH_ASSOC);
if ($result === false) {
return null;
}
/**
* @var array{id:int,name:string,timeperiod_id:int,tp_name:string,is_activated:int} $result
*/
return new Notification(
$result['id'],
$result['name'],
new TimePeriod($result['timeperiod_id'], $result['tp_name']),
(bool) $result['is_activated'],
);
}
/**
* {@inheritDoc}
*/
public function findMessagesByNotificationId(int $notificationId): array
{
$this->info('Get all notification messages for notification with ID #' . $notificationId);
$request = $this->translateDbName(
<<<'SQL'
SELECT id, channel, subject, message, formatted_message
FROM `:db`.notification_message
WHERE notification_id = :notificationId
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':notificationId', $notificationId, \PDO::PARAM_INT);
$statement->execute();
$messages = [];
foreach ($statement->fetchAll(\PDO::FETCH_ASSOC) as $result) {
$messages[] = new Message(
Channel::from($result['channel']),
$result['subject'],
$result['message'],
$result['formatted_message']
);
}
return $messages;
}
/**
* @inheritDoc
*/
public function findUsersByNotificationId(int $notificationId): array
{
$statement = $this->db->prepare(
$this->translateDbName(
<<<'SQL'
SELECT contact.contact_id, contact.contact_name, contact.contact_email, contact.contact_alias
FROM `:db`.contact
LEFT JOIN `:db`.notification_user_relation nur
ON nur.user_id = contact.contact_id
INNER JOIN `:db`.notification notif
ON notif.id = nur.notification_id
WHERE notif.id = :notification_id
SQL
)
);
$statement->bindValue(':notification_id', $notificationId, \PDO::PARAM_INT);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
$users = [];
foreach ($statement as $result) {
/**
* @var array{
* contact_id: int,
* contact_name: string,
* contact_email: string,
* contact_alias: string
* } $result
*/
$users[] = new Contact(
$result['contact_id'],
$result['contact_name'],
$result['contact_email'],
$result['contact_alias'],
);
}
return $users;
}
/**
* @inheritDoc
*/
public function findUsersByNotificationIdUserAndAccessGroups(
int $notificationId,
ContactInterface $user,
array $accessGroups,
): array {
$accessGroupIds = array_map(fn (AccessGroup $accessGroup) => $accessGroup->getId(), $accessGroups);
[$bindValues, $subQuery] = $this->createMultipleBindQuery($accessGroupIds, ':ag_id_');
$statement = $this->db->prepare(
$this->translateDbName(
<<<SQL
SELECT contact.*
FROM `:db`.notification notif
INNER JOIN `:db`.notification_user_relation nur
ON nur.notification_id = notif.id
INNER JOIN (
SELECT /* Finds associated users in ACL group rules */
contact.contact_id, contact.contact_alias, contact.contact_name,
contact.contact_email, contact.contact_admin, contact.contact_activate
FROM `:db`.`contact`
INNER JOIN `:db`.`acl_group_contacts_relations` acl_c_rel
ON acl_c_rel.contact_contact_id = contact.contact_id
WHERE contact.contact_register = '1'
AND acl_c_rel.acl_group_id IN ({$subQuery})
UNION
SELECT /* Finds users belonging to associated contact groups in ACL group rules */
contact.contact_id, contact.contact_alias, contact.contact_name,
contact.contact_email, contact.contact_admin, contact.contact_activate
FROM `:db`.`contact`
INNER JOIN `:db`.`contactgroup_contact_relation` c_cg_rel
ON c_cg_rel.contact_contact_id = contact.contact_id
INNER JOIN `:db`.`acl_group_contactgroups_relations` acl_cg_rel
ON acl_cg_rel.cg_cg_id = c_cg_rel.contactgroup_cg_id
WHERE contact.contact_register = '1'
AND acl_cg_rel.acl_group_id IN ({$subQuery})
UNION
SELECT /* Finds users belonging to the same contact groups as the user */
contact2.contact_id, contact2.contact_alias, contact2.contact_name,
contact2.contact_email, contact2.contact_admin, contact.contact_activate
FROM `:db`.`contact`
INNER JOIN `:db`.`contactgroup_contact_relation` c_cg_rel
ON c_cg_rel.contact_contact_id = contact.contact_id
INNER JOIN `:db`.`contactgroup_contact_relation` c_cg_rel2
ON c_cg_rel2.contactgroup_cg_id = c_cg_rel.contactgroup_cg_id
INNER JOIN `:db`.`contact` contact2
ON contact2.contact_id = c_cg_rel2.contact_contact_id
WHERE c_cg_rel.contact_contact_id = :user_id
AND contact.contact_register = '1'
AND contact2.contact_register = '1'
GROUP BY contact2.contact_id
) as contact
ON contact.contact_id = nur.user_id
WHERE notif.id = :notification_id
SQL
)
);
$statement->bindValue(':notification_id', $notificationId, \PDO::PARAM_INT);
$statement->bindValue(':user_id', $user->getId(), \PDO::PARAM_INT);
foreach ($bindValues as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->execute();
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$users = [];
foreach ($statement as $result) {
/**
* @var array{
* contact_id: int,
* contact_name: string,
* contact_email: string,
* contact_alias: string
* } $result
*/
$users[] = new Contact(
$result['contact_id'],
$result['contact_name'],
$result['contact_email'],
$result['contact_alias'],
);
}
return $users;
}
public function findUsersByContactGroupIds(int ...$contactGroupIds): array
{
if ($contactGroupIds === []) {
return [];
}
[$bindValues, $subQuery] = $this->createMultipleBindQuery($contactGroupIds, ':id_');
$statement = $this->db->prepare(
$this->translateDbName(
<<<SQL
SELECT DISTINCT c.contact_id, c.contact_name, c.contact_email, c.contact_alias
FROM `:db`.contactgroup_contact_relation cgcr
INNER JOIN `:db`.contactgroup cg
ON cg.cg_id=cgcr.contactgroup_cg_id
INNER JOIN `:db`.contact c
ON c.contact_id=cgcr.contact_contact_id
WHERE cg.cg_id IN ({$subQuery})
ORDER BY c.contact_name ASC
SQL
)
);
foreach ($bindValues as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->execute();
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$users = [];
foreach ($statement as $result) {
/**
* @var array{
* contact_id: int,
* contact_name: string,
* contact_email: string,
* contact_alias: string
* } $result
*/
$users[$result['contact_id']] = new Contact(
$result['contact_id'],
$result['contact_name'],
$result['contact_email'],
$result['contact_alias'],
);
}
return $users;
}
/**
* @inheritDoc
*/
public function findContactGroupsByNotificationId(int $notificationId): array
{
$statement = $this->db->prepare(
$this->translateDbName(
<<<'SQL'
SELECT contactgroup_id, contactgroup.cg_name, contactgroup.cg_alias
FROM `:db`.notification_contactgroup_relation
INNER JOIN `:db`.contactgroup
ON cg_id = contactgroup_id
WHERE notification_id = :notificationId
ORDER BY contactgroup.cg_name ASC
SQL
)
);
$statement->bindValue(':notificationId', $notificationId, \PDO::PARAM_INT);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
$contactGroups = [];
/**
* @var array{contactgroup_id:int, cg_name:string, cg_alias:string} $result
*/
foreach ($statement as $result) {
$contactGroups[] = new ContactGroup(
$result['contactgroup_id'],
$result['cg_name'],
$result['cg_alias']
);
}
return $contactGroups;
}
/**
* @inheritDoc
*/
public function countContactsByNotificationIds(array $notificationIds): array
{
[$bindValues, $subQuery] = $this->createMultipleBindQuery($notificationIds, ':id_');
$statement = $this->db->prepare(
$this->translateDbName(
<<<SQL
SELECT result.id, COUNT(result.contact_id)
FROM (
SELECT notif.id, contact.contact_id
FROM `:db`.contact
LEFT JOIN `:db`.notification_user_relation nur
ON nur.user_id = contact.contact_id
INNER JOIN `:db`.notification notif
ON notif.id = nur.notification_id
WHERE notif.id IN ({$subQuery})
) AS result
GROUP BY result.id
SQL
)
);
foreach ($bindValues as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->execute();
return $statement->fetchAll(\PDO::FETCH_KEY_PAIR) ?: [];
}
/**
* @inheritDoc
*/
public function countContactsByNotificationIdsAndAccessGroup(
array $notificationIds,
ContactInterface $user,
array $accessGroups,
): array {
$accessGroupIds = array_map(fn (AccessGroup $accessGroup) => $accessGroup->getId(), $accessGroups);
[$accessGroupBindValues, $accessGroupSubQuery] = $this->createMultipleBindQuery($accessGroupIds, ':ag_id_');
[$notificationBindValues, $notificationSubQuery] = $this->createMultipleBindQuery($notificationIds, ':notif_id_');
$statement = $this->db->prepare(
$this->translateDbName(
<<<SQL
SELECT result.id, COUNT(DISTINCT result.contact_id)
FROM (
SELECT notif.id, contact.contact_id
FROM `:db`.notification notif
INNER JOIN `:db`.notification_user_relation nur
ON nur.notification_id = notif.id
INNER JOIN (
SELECT contact.contact_id, contact.contact_alias, contact.contact_name,
contact.contact_email, contact.contact_admin, contact.contact_activate
FROM `:db`.`contact`
INNER JOIN `:db`.`acl_group_contacts_relations` acl_c_rel
ON acl_c_rel.contact_contact_id = contact.contact_id
AND acl_c_rel.acl_group_id IN ({$accessGroupSubQuery})
WHERE contact.contact_register = '1'
UNION ALL
SELECT contact.contact_id, contact.contact_alias, contact.contact_name,
contact.contact_email, contact.contact_admin, contact.contact_activate
FROM `:db`.`contact`
JOIN `:db`.`contactgroup_contact_relation` c_cg_rel
ON c_cg_rel.contact_contact_id = contact.contact_id
JOIN `:db`.`acl_group_contactgroups_relations` acl_cg_rel
ON acl_cg_rel.cg_cg_id = c_cg_rel.contactgroup_cg_id
AND acl_cg_rel.acl_group_id IN ({$accessGroupSubQuery})
WHERE contact.contact_register = '1'
UNION ALL
SELECT contact2.contact_id, contact2.contact_alias, contact2.contact_name,
contact2.contact_email, contact2.contact_admin, contact.contact_activate
FROM `:db`.`contact`
INNER JOIN `:db`.`contactgroup_contact_relation` c_cg_rel
ON c_cg_rel.contact_contact_id = contact.contact_id
INNER JOIN `:db`.`contactgroup_contact_relation` c_cg_rel2
ON c_cg_rel2.contactgroup_cg_id = c_cg_rel.contactgroup_cg_id
INNER JOIN `:db`.`contact` contact2
ON contact2.contact_id = c_cg_rel2.contact_contact_id
WHERE c_cg_rel.contact_contact_id = :user_id
AND contact.contact_register = '1'
AND contact2.contact_register = '1'
GROUP BY contact2.contact_id
) as contact
ON contact.contact_id = nur.user_id
WHERE notif.id IN ({$notificationSubQuery})
) AS result
GROUP BY result.id
SQL
)
);
foreach ([...$accessGroupBindValues, ...$notificationBindValues] as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->bindValue(':user_id', $user->getId(), \PDO::PARAM_INT);
$statement->execute();
return $statement->fetchAll(\PDO::FETCH_KEY_PAIR) ?: [];
}
/**
* @inheritDoc
*/
public function findContactGroupsByNotificationIdAndAccessGroups(
int $notificationId,
ContactInterface $user,
array $accessGroups,
): array {
$accessGroupIds = array_map(fn (AccessGroup $accessGroup) => $accessGroup->getId(), $accessGroups);
[$bindValues, $subQuery] = $this->createMultipleBindQuery($accessGroupIds, ':ag_id_');
$statement = $this->db->prepare(
$this->translateDbName(
<<<SQL
SELECT cg_id, cg_name, cg_alias
FROM (
SELECT
cg_id, cg_name, cg_alias, cg_comment, cg_activate, cg_type
FROM `:db`.acl_group_contactgroups_relations gcgr
INNER JOIN `:db`.contactgroup cg
ON cg.cg_id = gcgr.cg_cg_id
WHERE gcgr.acl_group_id IN ({$subQuery})
AND cg_activate = '1'
GROUP BY cg_id, cg_name, cg_alias, cg_comment, cg_activate, cg_type
UNION
SELECT cg_id, cg_name, cg_alias, cg_comment, cg_activate, cg_type
FROM `:db`.contactgroup cg
INNER JOIN `:db`.contactgroup_contact_relation ccr
ON ccr.contactgroup_cg_id = cg.cg_id
INNER JOIN `:db`.contact c
ON c.contact_id = ccr.contact_contact_id
WHERE ccr.contact_contact_id = :user_id
AND cg.cg_activate = '1'
AND c.contact_register = '1'
) AS cg
INNER JOIN `:db`.notification_contactgroup_relation ncr
ON ncr.contactgroup_id = cg.cg_id
WHERE ncr.notification_id = :notificationId
ORDER BY cg_name ASC
SQL
)
);
$statement->bindValue(':notificationId', $notificationId, \PDO::PARAM_INT);
$statement->bindValue(':user_id', $user->getId(), \PDO::PARAM_INT);
foreach ($bindValues as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->execute();
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$contactGroups = [];
/**
* @var array{cg_id:int,cg_name:string,cg_alias:string} $result
*/
foreach ($statement as $result) {
$contactGroups[] = new ContactGroup($result['cg_id'], $result['cg_name'], $result['cg_alias']);
}
return $contactGroups;
}
/**
* {@inheritDoc}
*/
public function exists(int $notificationId): bool
{
$this->info('Check existence of notification configuration with ID #' . $notificationId);
$request = $this->translateDbName('SELECT 1 FROM `:db`.notification WHERE id = :notificationId');
$statement = $this->db->prepare($request);
$statement->bindValue(':notificationId', $notificationId, \PDO::PARAM_INT);
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* {@inheritDoc}
*/
public function existsByName(TrimmedString $notificationName): bool
{
$this->info('Check existence of notification configuration with name ' . $notificationName);
$request = $this->translateDbName('SELECT 1 FROM `:db`.notification WHERE name = :notificationName');
$statement = $this->db->prepare($request);
$statement->bindValue(':notificationName', $notificationName, \PDO::PARAM_STR);
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* {@inheritDoc}
*/
public function findAll(?RequestParametersInterface $requestParameters): array
{
$sqlTranslator = $requestParameters ? new SqlRequestParametersTranslator($requestParameters) : null;
$sqlTranslator?->getRequestParameters()->setConcordanceStrictMode(
RequestParameters::CONCORDANCE_MODE_STRICT
);
$sqlTranslator?->setConcordanceArray([
'id' => 'id',
'name' => 'name',
'is_activated' => 'is_activated',
'timeperiod.id' => 'timeperiod_id',
]);
$query = $this->buildFindAllQuery($sqlTranslator);
$statement = $this->db->prepare($query);
$sqlTranslator?->bindSearchValues($statement);
$statement->execute();
$sqlTranslator?->calculateNumberOfRows($this->db);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$notifications = [];
/**
* @var array{
* id: int,
* name: string,
* timeperiod_id: int,
* tp_name: string,
* is_activated: int
* } $notificationData
*/
foreach ($statement as $notificationData) {
$notifications[] = new Notification(
$notificationData['id'],
$notificationData['name'],
new TimePeriod($notificationData['timeperiod_id'], $notificationData['tp_name']),
(bool) $notificationData['is_activated'],
);
}
return $notifications;
}
/**
* @inheritDoc
*/
public function findNotificationChannelsByNotificationIds(array $notificationIds): array
{
[$bindValues, $subQuery] = $this->createMultipleBindQuery($notificationIds, ':id_');
$statement = $this->db->prepare(
$this->translateDbName(
<<<SQL
SELECT notification_id, channel
FROM `:db`.notification_message
WHERE notification_id IN ({$subQuery})
SQL
)
);
foreach ($bindValues as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->execute();
$result = $statement->fetchAll(\PDO::FETCH_ASSOC);
$notificationsChannels = [];
foreach ($result as $notificationData) {
$notificationsChannels[(int) $notificationData['notification_id']][] = Channel::from($notificationData['channel']);
}
return $notificationsChannels;
}
/**
* @inheritDoc
*/
public function findLastNotificationDependencyIdsByHostGroup(int $hostGroupId): array
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
SELECT count(dependency_dep_id) AS nb_dependency , dependency_dep_id AS id
FROM dependency_hostgroupParent_relation
WHERE dependency_dep_id IN
(SELECT dependency_dep_id FROM dependency_hostgroupParent_relation
WHERE hostgroup_hg_id = :hostGroupId)
GROUP BY dependency_dep_id
SQL
));
$statement->bindValue(':hostGroupId', $hostGroupId, \PDO::PARAM_INT);
$statement->execute();
$lastDependencyIds = [];
foreach ($statement->fetchAll(\PDO::FETCH_ASSOC) as $result) {
/**
* @var array{id:int,nb_dependency:int} $result
*/
if ($result['nb_dependency'] === 1) {
$lastDependencyIds[] = $result['id'];
}
}
return $lastDependencyIds;
}
/**
* Build Query for findAll with research parameters.
*
* @param SqlRequestParametersTranslator|null $sqlTranslator
*
* @return string
*/
private function buildFindAllQuery(?SqlRequestParametersTranslator $sqlTranslator): string
{
$query = $this->translateDbName(
<<<'SQL_WRAP'
SELECT SQL_CALC_FOUND_ROWS id, name, timeperiod_id, tp_name, is_activated
FROM `:db`.notification
INNER JOIN timeperiod ON timeperiod_id = tp_id
SQL_WRAP
);
if ($sqlTranslator === null) {
return $query;
}
$sqlTranslator->setConcordanceArray([
'name' => 'notification.name',
]);
$searchQuery = $sqlTranslator->translateSearchParameterToSql();
$query .= ! is_null($searchQuery) ? $searchQuery : '';
$paginationQuery = $sqlTranslator->translatePaginationToSql();
$query .= $paginationQuery;
return $query;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Infrastructure/Repository/DbNotifiableResourceFactory.php | centreon/src/Core/Notification/Infrastructure/Repository/DbNotifiableResourceFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Infrastructure\Repository;
use Core\Notification\Application\Converter\{NotificationHostEventConverter, NotificationServiceEventConverter};
use Core\Notification\Domain\Model\{HostEvent, NotifiableHost, NotifiableResource, NotifiableService};
class DbNotifiableResourceFactory
{
public const NO_HOST_EVENTS = 0;
public const NO_SERVICE_EVENTS = 0;
/**
* @param iterable<int,array{
* notification_id: int,
* host_id: int,
* host_name: string,
* host_alias: string|null,
* host_events: int,
* service_id: int,
* service_name: string,
* service_alias: string,
* service_events: int,
* included_service_events: int
* }> $records
*
* @throws \Throwable
*
* @return \Generator<NotifiableResource>
*/
public static function createFromRecords(iterable $records): \Generator
{
$currentNotificationId = 0;
$currentRecords = [];
foreach ($records as $record) {
if ($currentNotificationId === 0) {
$currentNotificationId = $record['notification_id'];
$currentRecords[] = $record;
continue;
}
if ($currentNotificationId === $record['notification_id']) {
$currentRecords[] = $record;
continue;
}
yield self::createNotifiableResourceFromRecord($currentNotificationId, $currentRecords);
$currentRecords = [];
$currentRecords[] = $record;
$currentNotificationId = $record['notification_id'];
}
if ($currentRecords !== []) {
yield self::createNotifiableResourceFromRecord($currentNotificationId, $currentRecords);
}
}
/**
* @param int $notificationId
* @param array<int,array{
* notification_id: int,
* host_id: int,
* host_name: string,
* host_alias: string|null,
* host_events: int,
* service_id: int,
* service_name: string,
* service_alias: string,
* service_events: int,
* included_service_events: int
* }> $records
*
* @throws \Throwable
*
* @return NotifiableResource
*/
private static function createNotifiableResourceFromRecord(int $notificationId, array $records): NotifiableResource
{
$notificationHosts = [];
$currentHostId = 0;
$currentRecords = [];
$currentHostEvents = [];
$index = 0;
foreach ($records as $record) {
if ($currentHostId === 0) {
$currentHostId = $record['host_id'];
$currentRecords[] = $record;
$index++;
continue;
}
if ($currentHostId === $record['host_id']) {
$currentRecords[] = $record;
$index++;
continue;
}
if ($currentRecords[$index - 1] !== self::NO_HOST_EVENTS) {
$currentHostEvents = NotificationHostEventConverter::fromBitFlags(
(int) $currentRecords[$index - 1]['host_events']
);
}
$notificationHosts[] = self::createNotificationHostFromRecord(
$currentHostId,
$currentRecords[$index - 1]['host_name'],
$currentRecords[$index - 1]['host_alias'],
$currentHostEvents,
$currentRecords
);
$currentRecords = [];
$index = 1;
$currentRecords[] = $record;
$currentHostId = $record['host_id'];
$currentHostEvents = [];
}
if ($currentRecords[$index - 1]['host_events'] !== self::NO_HOST_EVENTS) {
$currentHostEvents = NotificationHostEventConverter::fromBitFlags(
(int) $currentRecords[$index - 1]['host_events']
);
}
$notificationHosts[] = self::createNotificationHostFromRecord(
$currentHostId,
$currentRecords[$index - 1]['host_name'],
$currentRecords[$index - 1]['host_alias'],
$currentHostEvents,
$currentRecords
);
return new NotifiableResource($notificationId, $notificationHosts);
}
/**
* @param int $hostId
* @param string $hostName
* @param string|null $hostAlias
* @param array<HostEvent> $hostEvents
* @param array<int,array{
* notification_id: int,
* host_id: int,
* host_name: string,
* host_alias: string|null,
* host_events: int,
* service_id: int,
* service_name: string,
* service_alias: string,
* service_events: int,
* included_service_events: int
* }> $records
*
* @throws \Throwable
*
* @return NotifiableHost
*/
private static function createNotificationHostFromRecord(
int $hostId,
string $hostName,
?string $hostAlias,
array $hostEvents,
array $records,
): NotifiableHost {
$notificationServices = [];
$currentServiceEvents = [];
foreach ($records as $record) {
if ($record['service_events'] !== self::NO_SERVICE_EVENTS) {
$currentServiceEvents = NotificationServiceEventConverter::fromBitFlags(
(int) $record['service_events']
);
}
if ($record['included_service_events'] !== self::NO_SERVICE_EVENTS) {
$currentServiceEvents = NotificationServiceEventConverter::fromBitFlags(
(int) $record['included_service_events']
);
}
if ($currentServiceEvents === []) {
continue;
}
// Do not create a metaservice with generated virtual service name (i.e. 'meta_1')
if (\str_contains($record['service_name'], 'meta_')) {
continue;
}
$notificationServices[] = new NotifiableService(
(int) $record['service_id'],
$record['service_name'],
$record['service_alias'],
$currentServiceEvents
);
}
$notificationServices = \array_unique($notificationServices, SORT_REGULAR);
return new NotifiableHost($hostId, $hostName, $hostAlias, $hostEvents, $notificationServices);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Infrastructure/Repository/DbServiceGroupResourceRepository.php | centreon/src/Core/Notification/Infrastructure/Repository/DbServiceGroupResourceRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Infrastructure\Repository;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait;
use Core\Notification\Application\Converter\NotificationServiceEventConverter;
use Core\Notification\Application\Repository\NotificationResourceRepositoryInterface;
use Core\Notification\Domain\Model\ConfigurationResource;
use Core\Notification\Domain\Model\NotificationResource;
use Core\Notification\Domain\Model\ServiceEvent;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Utility\SqlConcatenator;
class DbServiceGroupResourceRepository extends AbstractRepositoryRDB implements NotificationResourceRepositoryInterface
{
use LoggerTrait;
use SqlMultipleBindTrait;
private const RESOURCE_TYPE = NotificationResource::TYPE_SERVICE_GROUP;
private const EVENT_ENUM = ServiceEvent::class;
private const EVENT_ENUM_CONVERTER = NotificationServiceEventConverter::class;
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function supportResourceType(string $type): bool
{
return mb_strtolower($type) === self::RESOURCE_TYPE;
}
/**
* @inheritDoc
*/
public function eventEnum(): string
{
return self::EVENT_ENUM;
}
/**
* @inheritDoc
*/
public function eventEnumConverter(): string
{
return self::EVENT_ENUM_CONVERTER;
}
/**
* @inheritDoc
*/
public function resourceType(): string
{
return self::RESOURCE_TYPE;
}
/**
* @inheritDoc
*/
public function exist(array $resourceIds): array
{
$this->info(
'Check if resource IDs exist with accessGroups',
['resource_type' => self::RESOURCE_TYPE, 'resource_ids' => $resourceIds]
);
if ($resourceIds === []) {
return [];
}
$concatenator = $this->getConcatenatorForExistRequest()
->appendWhere(
<<<'SQL'
sg.sg_id IN (:resourceIds)
SQL
)->storeBindValueMultiple(':resourceIds', $resourceIds, \PDO::PARAM_INT);
$statement = $this->db->prepare($this->translateDbName($concatenator->concatAll()));
$concatenator->bindValuesToStatement($statement);
$statement->execute();
return $statement->fetchAll(\PDO::FETCH_COLUMN, 0);
}
/**
* @inheritDoc
*/
public function existByAccessGroups(array $resourceIds, array $accessGroups): array
{
$this->info(
'Check if resource IDs exist with accessGroups',
[
'resource_type' => self::RESOURCE_TYPE,
'resource_ids' => $resourceIds,
'access_groups' => $accessGroups,
]
);
if ($resourceIds === []) {
return [];
}
$accessGroupIds = array_map(
static fn (AccessGroup $accessGroup) => $accessGroup->getId(),
$accessGroups
);
$concatenator = $this->getConcatenatorForExistRequest($accessGroupIds)
->appendWhere(
<<<'SQL'
sg.sg_id IN (:resourceIds)
SQL
)->storeBindValueMultiple(':resourceIds', $resourceIds, \PDO::PARAM_INT);
$statement = $this->db->prepare($this->translateDbName($concatenator->concatAll()));
$concatenator->bindValuesToStatement($statement);
$statement->execute();
return $statement->fetchAll(\PDO::FETCH_COLUMN, 0);
}
/**
* @inheritDoc
*/
public function findByNotificationId(int $notificationId): ?NotificationResource
{
$this->info(
'Find resource with accessGroups',
[
'resource_type' => self::RESOURCE_TYPE,
'notification_id' => $notificationId,
]
);
$eventResults = $this->retrieveEvents($notificationId);
if ($eventResults === null) {
return null;
}
$concatenator = $this->getConcatenatorForFindRequest()
->appendWhere(
<<<'SQL'
WHERE notification_id = :notificationId
SQL
)->storeBindValue(':notificationId', $notificationId, \PDO::PARAM_INT);
$statement = $this->db->prepare($this->translateDbName($concatenator->concatAll()));
$concatenator->bindValuesToStatement($statement);
$statement->execute();
$resources = array_map(
(fn ($data) => new ConfigurationResource($data['sg_id'], $data['sg_name'])),
$statement->fetchAll(\PDO::FETCH_ASSOC)
);
return new NotificationResource(
self::RESOURCE_TYPE,
self::EVENT_ENUM,
$resources,
(self::EVENT_ENUM_CONVERTER)::fromBitFlags($eventResults),
);
}
/**
* @inheritDoc
*/
public function findByNotificationIdAndAccessGroups(
int $notificationId,
array $accessGroups,
): ?NotificationResource {
if ($accessGroups === []) {
return null;
}
$this->info(
'Find resource with accessGroups',
[
'resource_type' => self::RESOURCE_TYPE,
'notification_id' => $notificationId,
'access_group' => $accessGroups,
]
);
$eventResults = $this->retrieveEvents($notificationId);
if ($eventResults === null) {
return null;
}
$accessGroupIds = array_map(
static fn (AccessGroup $accessGroup) => $accessGroup->getId(),
$accessGroups
);
$concatenator = $this->getConcatenatorForFindRequest($accessGroupIds)
->appendWhere(
<<<'SQL'
WHERE notification_id = :notificationId
SQL
)->storeBindValue(':notificationId', $notificationId, \PDO::PARAM_INT);
$statement = $this->db->prepare($this->translateDbName($concatenator->concatAll()));
$concatenator->bindValuesToStatement($statement);
$statement->execute();
$resources = array_map(
(fn ($data) => new ConfigurationResource($data['sg_id'], $data['sg_name'])),
$statement->fetchAll(\PDO::FETCH_ASSOC)
);
return new NotificationResource(
self::RESOURCE_TYPE,
self::EVENT_ENUM,
$resources,
(self::EVENT_ENUM_CONVERTER)::fromBitFlags($eventResults),
);
}
/**
* @inheritDoc
*/
public function add(int $notificationId, NotificationResource $resource): void
{
$this->info(
'Add resource',
[
'resource_type' => self::RESOURCE_TYPE,
'notification_id' => $notificationId,
'resource' => $resource,
]
);
$alreadyInTransaction = $this->db->inTransaction();
if (! $alreadyInTransaction) {
$this->db->beginTransaction();
}
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
UPDATE `:db`.notification
SET servicegroup_events = :events
WHERE id = :notificationId
SQL
));
$statement->bindValue(
':events',
(self::EVENT_ENUM_CONVERTER)::toBitFlags($resource->getEvents()),
\PDO::PARAM_INT
);
$statement->bindValue(':notificationId', $notificationId, \PDO::PARAM_INT);
$statement->execute();
$subQuery = [];
$bindElem = [];
foreach ($resource->getResources() as $key => $resourceElem) {
$subQuery[] = "(:notificationId, :resource_{$key})";
$bindElem[":resource_{$key}"] = $resourceElem->getId();
}
$statement = $this->db->prepare($this->translateDbName(
'INSERT INTO `:db`.notification_sg_relation (notification_id, sg_id) VALUES ' . implode(', ', $subQuery)
));
$statement->bindValue(':notificationId', $notificationId, \PDO::PARAM_INT);
foreach ($bindElem as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->execute();
if (! $alreadyInTransaction) {
$this->db->commit();
}
}
/**
* @inheritDoc
*/
public function countResourcesByNotificationIdsAndAccessGroups(
array $notificationIds,
array $accessGroups,
): array {
$accessGroupIds = array_map(
static fn (AccessGroup $accessGroup) => $accessGroup->getId(),
$accessGroups
);
[$bindNotificationValues, $subNotificationQuery] = $this->createMultipleBindQuery($notificationIds, ':nid_');
[$bindAccessGroupValues, $subAccessGroupQuery] = $this->createMultipleBindQuery($accessGroupIds, ':aid_');
$request = <<<SQL
SELECT
notification_id, COUNT(DISTINCT rel.sg_id)
FROM `:db`.notification_sg_relation rel
INNER JOIN `:db`.acl_resources_sg_relations arsr
ON rel.sg_id = arsr.sg_id
INNER JOIN `:db`.acl_resources res
ON arsr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_res_group_relations argr
ON res.acl_res_id = argr.acl_res_id
INNER JOIN `:db`.acl_groups ag
ON argr.acl_group_id = ag.acl_group_id
WHERE ag.acl_group_id IN ({$subAccessGroupQuery})
AND notification_id IN ({$subNotificationQuery})
GROUP BY notification_id
SQL;
$statement = $this->db->prepare($this->translateDbName($request));
foreach (array_merge($bindNotificationValues, $bindAccessGroupValues) as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->execute();
$result = $statement->fetchAll(\PDO::FETCH_KEY_PAIR);
return $result ?: [];
}
/**
* @inheritDoc
*/
public function countResourcesByNotificationIds(array $notificationIds): array
{
$concatenator = $this->getConcatenatorForFindResourcesCountQuery([])
->storeBindValueMultiple(':notification_ids', $notificationIds, \PDO::PARAM_INT)
->appendWhere(
<<<'SQL'
WHERE notification_id IN (:notification_ids)
SQL
);
$statement = $this->db->prepare($this->translateDbName($concatenator->concatAll()));
$concatenator->bindValuesToStatement($statement);
$statement->execute();
$result = $statement->fetchAll(\PDO::FETCH_KEY_PAIR);
return $result ?: [];
}
/**
* @inheritDoc
*/
public function deleteByNotificationIdAndResourcesId(int $notificationId, array $resourcesIds): void
{
$resetEventStatement = $this->db->prepare($this->translateDbName(
<<<'SQL'
UPDATE `:db`.notification SET
servicegroup_events = 0
WHERE id = :notificationId
SQL
));
$resetEventStatement->bindValue(':notificationId', $notificationId, \PDO::PARAM_INT);
$resetEventStatement->execute();
$bindValues = [];
foreach ($resourcesIds as $resourceId) {
$bindValues[':resource_id' . $resourceId] = $resourceId;
}
$serviceGroupsIds = implode(', ', array_keys($bindValues));
$deleteStatement = $this->db->prepare($this->translateDbName(
<<<SQL
DELETE FROM `:db`.notification_sg_relation
WHERE sg_id IN ({$serviceGroupsIds})
AND notification_id = :notificationId
SQL
));
foreach ($bindValues as $token => $resourceId) {
$deleteStatement->bindValue($token, $resourceId, \PDO::PARAM_INT);
}
$deleteStatement->bindValue(':notificationId', $notificationId, \PDO::PARAM_INT);
$deleteStatement->execute();
}
/**
* @inheritDoc
*/
public function deleteAllByNotification(int $notificationId): void
{
$resetEventStatement = $this->db->prepare($this->translateDbName(
<<<'SQL'
UPDATE `:db`.notification SET
servicegroup_events = 0
WHERE id = :notificationId
SQL
));
$resetEventStatement->bindValue(':notificationId', $notificationId, \PDO::PARAM_INT);
$resetEventStatement->execute();
$deleteStatement = $this->db->prepare($this->translateDbName(
<<<'SQL'
DELETE FROM `:db`.notification_sg_relation
WHERE notification_id = :notificationId
SQL
));
$deleteStatement->bindValue(':notificationId', $notificationId, \PDO::PARAM_INT);
$deleteStatement->execute();
}
/**
* Retrieve events by Notification Id.
*
* @param int $notificationId
*
* @return int|null
*/
private function retrieveEvents(int $notificationId): ?int
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
SELECT servicegroup_events
FROM `:db`.notification
WHERE id = :notificationId
SQL
));
$statement->bindValue(':notificationId', $notificationId, \PDO::PARAM_INT);
$statement->execute();
$result = $statement->fetchColumn();
return $result === false ? null : (int) $result;
}
/**
* @param int[] $accessGroupIds
*
* @return SqlConcatenator
*/
private function getConcatenatorForExistRequest(array $accessGroupIds = []): SqlConcatenator
{
$concatenator = (new SqlConcatenator())
->defineSelect(
<<<'SQL'
SELECT
sg.sg_id
SQL
)
->defineFrom(
<<<'SQL'
FROM
`:db`.`servicegroup` sg
SQL
);
if ($accessGroupIds !== []) {
$concatenator->appendJoins(
<<<'SQL'
INNER JOIN `:db`.acl_resources_sg_relations arsr
ON sg.sg_id = arsr.sg_id
INNER JOIN `:db`.acl_resources res
ON arsr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_res_group_relations argr
ON res.acl_res_id = argr.acl_res_id
INNER JOIN `:db`.acl_groups ag
ON argr.acl_group_id = ag.acl_group_id
SQL
)->appendWhere(
<<<'SQL'
WHERE ag.acl_group_id IN (:accessGroupIds)
SQL
)
->storeBindValueMultiple(':accessGroupIds', $accessGroupIds, \PDO::PARAM_INT);
}
return $concatenator;
}
/**
* @param int[] $accessGroupIds
*
* @return SqlConcatenator
*/
private function getConcatenatorForFindRequest(array $accessGroupIds = []): SqlConcatenator
{
$concatenator = (new SqlConcatenator())
->defineSelect(
<<<'SQL'
SELECT DISTINCT
rel.sg_id, sg.sg_name
SQL
)->defineFrom(
<<<'SQL'
FROM
`:db`.notification_sg_relation rel
SQL
)->appendJoins(
<<<'SQL'
INNER JOIN `:db`.servicegroup sg
ON sg.sg_id = rel.sg_id
SQL
);
if ($accessGroupIds !== []) {
$concatenator->appendJoins(
<<<'SQL'
INNER JOIN `:db`.acl_resources_sg_relations arsr
ON rel.sg_id = arsr.sg_id
INNER JOIN `:db`.acl_resources res
ON arsr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_res_group_relations argr
ON res.acl_res_id = argr.acl_res_id
INNER JOIN `:db`.acl_groups ag
ON argr.acl_group_id = ag.acl_group_id
SQL
)->appendWhere(
<<<'SQL'
WHERE ag.acl_group_id IN (:accessGroupIds)
SQL
)->storeBindValueMultiple(':accessGroupIds', $accessGroupIds, \PDO::PARAM_INT);
}
return $concatenator;
}
/**
* @param int[] $accessGroupIds
*
* @return SqlConcatenator
*/
private function getConcatenatorForFindResourcesCountQuery(array $accessGroupIds): SqlConcatenator
{
$concatenator = (new SqlConcatenator())
->defineSelect(
<<<'SQL'
SELECT
notification_id, COUNT(DISTINCT rel.sg_id)
SQL
)->defineFrom(
<<<'SQL'
FROM
`:db`.notification_sg_relation rel
SQL
)->defineGroupBy(
<<<'SQL'
GROUP BY notification_id
SQL
);
if ($accessGroupIds !== []) {
$concatenator->appendJoins(
<<<'SQL'
INNER JOIN `:db`.acl_resources_sg_relations arsr
ON rel.sg_id = arsr.sg_id
INNER JOIN `:db`.acl_resources res
ON arsr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_res_group_relations argr
ON res.acl_res_id = argr.acl_res_id
INNER JOIN `:db`.acl_groups ag
ON argr.acl_group_id = ag.acl_group_id
SQL
)->appendWhere(
<<<'SQL'
WHERE ag.acl_group_id IN (:accessGroupIds)
SQL
)->storeBindValueMultiple(':accessGroupIds', $accessGroupIds, \PDO::PARAM_INT);
}
return $concatenator;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Infrastructure/Repository/HostGroupRequestProvider.php | centreon/src/Core/Notification/Infrastructure/Repository/HostGroupRequestProvider.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Infrastructure\Repository;
use Core\Notification\Application\Repository\NotifiableResourceRequestProviderInterface;
class HostGroupRequestProvider implements NotifiableResourceRequestProviderInterface
{
/**
* @inheritDoc
*/
public function getNotifiableResourceSubRequest(): string
{
return <<<'SQL'
SELECT n.`id` AS `notification_id`,
h.`host_id` AS `host_id`,
h.`host_name` AS `host_name`,
h.`host_alias` AS `host_alias`,
n.`hostgroup_events` AS `host_events`,
hsr.`service_service_id` AS `service_id`,
s.`service_description` AS `service_name`,
s.`service_alias` AS `service_alias`,
0 AS `service_events`,
n.`included_service_events`
FROM `:db`.`host` h
INNER JOIN `:db`.`hostgroup_relation` hgr ON hgr.`host_host_id` = h.`host_id`
INNER JOIN `:db`.`host_service_relation` hsr ON hsr.`host_host_id` = h.`host_id`
INNER JOIN `:db`.`notification_hg_relation` nhgr ON nhgr.`hg_id` = hgr.`hostgroup_hg_id`
INNER JOIN `:db`.`notification` n ON n.`id` = nhgr.`notification_id`
INNER JOIN `:db`.`service` s ON s.`service_id` = hsr.`service_service_id`
WHERE n.`is_activated` = 1
SQL;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Infrastructure/Repository/DbWriteNotificationRepository.php | centreon/src/Core/Notification/Infrastructure/Repository/DbWriteNotificationRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Infrastructure\Repository;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Notification\Application\Repository\WriteNotificationRepositoryInterface;
use Core\Notification\Domain\Model\NewNotification;
use Core\Notification\Domain\Model\Notification;
class DbWriteNotificationRepository extends AbstractRepositoryRDB implements WriteNotificationRepositoryInterface
{
use LoggerTrait;
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* {@inheritDoc}
*/
public function addNewNotification(NewNotification $notification): int
{
$this->debug('Add notification configuration', ['notification' => $notification]);
$request = $this->translateDbName(
'INSERT INTO `:db`.notification
(name, timeperiod_id, is_activated) VALUES
(:name, :timeperiodId, :isActivated)'
);
$statement = $this->db->prepare($request);
$statement->bindValue(':name', $notification->getName(), \PDO::PARAM_STR);
$statement->bindValue(':timeperiodId', $notification->getTimePeriod()->getId(), \PDO::PARAM_INT);
$statement->bindValue(':isActivated', $notification->isActivated(), \PDO::PARAM_BOOL);
$statement->execute();
return (int) $this->db->lastInsertId();
}
/**
* @inheritDoc
*/
public function addMessagesToNotification(int $notificationId, array $messages): void
{
$this->debug('Add notification messages', ['notification_id' => $notificationId, 'messages' => $messages]);
if ($messages === []) {
return;
}
$queryBinding = [];
$bindedValues = [];
foreach ($messages as $key => $message) {
$queryBinding[] = "(:notificationId, :channel_{$key}, :subject_{$key}, :message_{$key},"
. " :formatted_message_{$key})";
$bindedValues[":channel_{$key}"] = $message->getChannel()->value;
$bindedValues[":subject_{$key}"] = $message->getSubject();
$bindedValues[":message_{$key}"] = $message->getRawMessage();
$bindedValues[":formatted_message_{$key}"] = $message->getFormattedMessage();
}
$request = $this->translateDbName(
'INSERT INTO `:db`.notification_message
(notification_id, channel, subject, message, formatted_message) VALUES '
. implode(', ', $queryBinding)
);
$statement = $this->db->prepare($request);
$statement->bindValue(':notificationId', $notificationId, \PDO::PARAM_INT);
foreach ($bindedValues as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_STR);
}
$statement->execute();
}
/**
* @inheritDoc
*/
public function addUsersToNotification(int $notificationId, array $userIds): void
{
$this->debug('Add users to notification', ['notification_id' => $notificationId, 'users' => $userIds]);
if ($userIds === []) {
return;
}
$queryBinding = [];
$bindedValues = [];
foreach ($userIds as $key => $user) {
$queryBinding[] = "(:notificationId, :userId_{$key})";
$bindedValues[":userId_{$key}"] = $user;
}
$request = $this->translateDbName(
'INSERT INTO `:db`.notification_user_relation
(notification_id, user_id) VALUES '
. implode(', ', $queryBinding)
);
$statement = $this->db->prepare($request);
$statement->bindValue(':notificationId', $notificationId, \PDO::PARAM_INT);
foreach ($bindedValues as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->execute();
}
/**
* @inheritDoc
*/
public function addContactGroupsToNotification(int $notificationId, array $contactGroupIds): void
{
if ($contactGroupIds === []) {
return;
}
$queryBinding = [];
$bindedValues = [];
foreach ($contactGroupIds as $key => $contactgroupId) {
$queryBinding[] = "(:notificationId, :contactgroupId_{$key})";
$bindedValues[":contactgroupId_{$key}"] = $contactgroupId;
}
$request = $this->translateDbName(
'INSERT INTO `:db`.notification_contactgroup_relation
(notification_id, contactgroup_id) VALUES '
. implode(', ', $queryBinding)
);
$statement = $this->db->prepare($request);
$statement->bindValue(':notificationId', $notificationId, \PDO::PARAM_INT);
foreach ($bindedValues as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->execute();
}
/**
* @inheritDoc
*/
public function updateNotification(Notification $notification): void
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
UPDATE notification
SET
name = :name,
timeperiod_id = :timeperiodId,
is_activated = :isActivated
WHERE
id = :notificationId
SQL
));
$statement->bindValue(':name', $notification->getName(), \PDO::PARAM_STR);
$statement->bindValue(':timeperiodId', $notification->getTimePeriod()->getId(), \PDO::PARAM_INT);
$statement->bindValue(':isActivated', $notification->isActivated(), \PDO::PARAM_BOOL);
$statement->bindValue(':notificationId', $notification->getId(), \PDO::PARAM_INT);
$statement->execute();
}
/**
* @inheritDoc
*/
public function deleteNotificationMessages(int $notificationId): void
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
DELETE FROM `:db`.notification_message
WHERE notification_id = :notificationId
SQL
));
$statement->bindValue(':notificationId', $notificationId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @inheritDoc
*/
public function deleteUsersFromNotification(int $notificationId): void
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
DELETE FROM `:db`.notification_user_relation
WHERE notification_id = :notificationId
SQL
));
$statement->bindValue(':notificationId', $notificationId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @inheritDoc
*/
public function deleteContactGroupsFromNotification(int $notificationId): void
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
DELETE FROM `:db`.notification_contactgroup_relation
WHERE notification_id = :notificationId
SQL
));
$statement->bindValue(':notificationId', $notificationId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @inheritDoc
*/
public function deleteContactGroupsByNotificationAndContactGroupIds(
int $notificationId,
array $contactGroupsIds,
): void {
if ($contactGroupsIds === []) {
return;
}
$bindValues = [];
foreach ($contactGroupsIds as $contactGroupId) {
$bindValues[':contactgroup_' . $contactGroupId] = $contactGroupId;
}
$bindToken = implode(', ', array_keys($bindValues));
$statement = $this->db->prepare($this->translateDbName(
<<<SQL
DELETE FROM `:db`.notification_contactgroup_relation
WHERE notification_id = :notificationId
AND contactgroup_id IN ({$bindToken})
SQL
));
$statement->bindValue(':notificationId', $notificationId, \PDO::PARAM_INT);
foreach ($bindValues as $token => $value) {
$statement->bindValue($token, $value, \PDO::PARAM_INT);
}
$statement->execute();
}
/**
* @inheritDoc
*/
public function deleteNotification(int $notificationId): int
{
$request = <<<'SQL'
DELETE FROM `:db`.`notification`
WHERE `id` = :notification_id
SQL;
$statement = $this->db->prepare($this->translateDbName($request));
$statement->bindValue(':notification_id', $notificationId, \PDO::PARAM_INT);
$statement->execute();
return $statement->rowCount();
}
/**
* @inheritDoc
*/
public function deleteDependencies(array $lastDependencyIds): void
{
if ($lastDependencyIds === []) {
return;
}
$bindValues = [];
foreach ($lastDependencyIds as $lastDependencyId) {
$bindValues[':lastDependencyId_' . $lastDependencyId] = $lastDependencyId;
}
$dependeciesAsString = implode(', ', array_keys($bindValues));
$statement = $this->db->prepare($this->translateDbName(
<<<SQL
DELETE FROM `:db`.dependency
WHERE dep_id IN ({$dependeciesAsString})
SQL
));
foreach ($bindValues as $token => $lastDependencyId) {
$statement->bindValue($token, $lastDependencyId, \PDO::PARAM_INT);
}
$statement->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Infrastructure/Repository/DbHostGroupResourceRepository.php | centreon/src/Core/Notification/Infrastructure/Repository/DbHostGroupResourceRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Infrastructure\Repository;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait;
use Core\Notification\Application\Converter\NotificationHostEventConverter;
use Core\Notification\Application\Converter\NotificationServiceEventConverter;
use Core\Notification\Application\Repository\NotificationResourceRepositoryInterface;
use Core\Notification\Domain\Model\ConfigurationResource;
use Core\Notification\Domain\Model\HostEvent;
use Core\Notification\Domain\Model\NotificationResource;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Utility\SqlConcatenator;
class DbHostGroupResourceRepository extends AbstractRepositoryRDB implements NotificationResourceRepositoryInterface
{
use LoggerTrait;
use SqlMultipleBindTrait;
private const RESOURCE_TYPE = NotificationResource::TYPE_HOST_GROUP;
private const EVENT_ENUM = HostEvent::class;
private const EVENT_ENUM_CONVERTER = NotificationHostEventConverter::class;
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function supportResourceType(string $type): bool
{
return mb_strtolower($type) === self::RESOURCE_TYPE;
}
/**
* @inheritDoc
*/
public function eventEnum(): string
{
return self::EVENT_ENUM;
}
/**
* @inheritDoc
*/
public function eventEnumConverter(): string
{
return self::EVENT_ENUM_CONVERTER;
}
/**
* @inheritDoc
*/
public function resourceType(): string
{
return self::RESOURCE_TYPE;
}
/**
* @inheritDoc
*/
public function exist(array $resourceIds): array
{
$this->info(
'Check if resource IDs exist',
['resource_type' => self::RESOURCE_TYPE, 'resource_ids' => $resourceIds]
);
if ($resourceIds === []) {
return [];
}
$concatenator = $this->getConcatenatorForExistRequest()
->appendWhere(
<<<'SQL'
hg.hg_id IN (:resourceIds)
SQL
)->storeBindValueMultiple(':resourceIds', $resourceIds, \PDO::PARAM_INT);
$statement = $this->db->prepare($this->translateDbName($concatenator->concatAll()));
$concatenator->bindValuesToStatement($statement);
$statement->execute();
return $statement->fetchAll(\PDO::FETCH_COLUMN, 0);
}
/**
* @inheritDoc
*/
public function existByAccessGroups(array $resourceIds, array $accessGroups): array
{
$this->info(
'Check if resource IDs exist with accessGroups',
[
'resource_type' => self::RESOURCE_TYPE,
'resource_ids' => $resourceIds,
'access_groups' => $accessGroups,
]
);
if ($accessGroups === [] || $resourceIds === []) {
return [];
}
$accessGroupIds = array_map(
static fn (AccessGroup $accessGroup) => $accessGroup->getId(),
$accessGroups
);
$concatenator = $this->getConcatenatorForExistRequest($accessGroupIds)
->appendWhere(
<<<'SQL'
hg.hg_id IN (:resourceIds)
SQL
)->storeBindValueMultiple(':resourceIds', $resourceIds, \PDO::PARAM_INT);
$statement = $this->db->prepare($this->translateDbName($concatenator->concatAll()));
$concatenator->bindValuesToStatement($statement);
$statement->execute();
return $statement->fetchAll(\PDO::FETCH_COLUMN, 0);
}
/**
* @inheritDoc
*/
public function findByNotificationId(int $notificationId): ?NotificationResource
{
$this->info(
'Find resource with accessGroups',
[
'resource_type' => self::RESOURCE_TYPE,
'notification_id' => $notificationId,
]
);
[$hostgroupEvents, $includedServiceEvents] = $this->retrieveEvents($notificationId);
$concatenator = $this->getConcatenatorForFindRequest()
->appendWhere(
<<<'SQL'
WHERE notification_id = :notificationId
SQL
)->storeBindValue(':notificationId', $notificationId, \PDO::PARAM_INT);
$statement = $this->db->prepare($this->translateDbName($concatenator->concatAll()));
$concatenator->bindValuesToStatement($statement);
$statement->execute();
$resources = array_map(
(fn ($data) => new ConfigurationResource($data['hg_id'], $data['hg_name'])),
$statement->fetchAll(\PDO::FETCH_ASSOC)
);
return new NotificationResource(
self::RESOURCE_TYPE,
self::EVENT_ENUM,
$resources,
NotificationHostEventConverter::fromBitFlags($hostgroupEvents),
NotificationServiceEventConverter::fromBitFlags($includedServiceEvents),
);
}
/**
* @inheritDoc
*/
public function findByNotificationIdAndAccessGroups(
int $notificationId,
array $accessGroups,
): ?NotificationResource {
if ($accessGroups === []) {
return null;
}
$this->info(
'Find resource with accessGroups',
[
'resource_type' => self::RESOURCE_TYPE,
'notification_id' => $notificationId,
'access_group' => $accessGroups,
]
);
[$hostgroupEvents, $includedServiceEvents] = $this->retrieveEvents($notificationId);
$accessGroupIds = array_map(
static fn (AccessGroup $accessGroup) => $accessGroup->getId(),
$accessGroups
);
$concatenator = $this->getConcatenatorForFindRequest($accessGroupIds)
->appendWhere(
<<<'SQL'
WHERE notification_id = :notificationId
SQL
)->storeBindValue(':notificationId', $notificationId, \PDO::PARAM_INT);
$statement = $this->db->prepare($this->translateDbName($concatenator->concatAll()));
$concatenator->bindValuesToStatement($statement);
$statement->execute();
$resources = array_map(
(fn ($data) => new ConfigurationResource($data['hg_id'], $data['hg_name'])),
$statement->fetchAll(\PDO::FETCH_ASSOC)
);
return new NotificationResource(
self::RESOURCE_TYPE,
self::EVENT_ENUM,
$resources,
NotificationHostEventConverter::fromBitFlags($hostgroupEvents),
NotificationServiceEventConverter::fromBitFlags($includedServiceEvents),
);
}
/**
* @inheritDoc
*/
public function add(int $notificationId, NotificationResource $resource): void
{
$this->info(
'Add resource',
[
'resource_type' => self::RESOURCE_TYPE,
'notification_id' => $notificationId,
'resource' => $resource,
]
);
$alreadyInTransaction = $this->db->inTransaction();
if (! $alreadyInTransaction) {
$this->db->beginTransaction();
}
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
UPDATE `:db`.notification SET
hostgroup_events = :events,
included_service_events = :serviceEvents
WHERE id = :notificationId
SQL
));
$statement->bindValue(
':events',
(self::EVENT_ENUM_CONVERTER)::toBitFlags($resource->getEvents()),
\PDO::PARAM_INT
);
$statement->bindValue(':notificationId', $notificationId, \PDO::PARAM_INT);
$statement->bindValue(
':serviceEvents',
method_exists($resource, 'getServiceEvents')
? NotificationServiceEventConverter::toBitFlags($resource->getServiceEvents())
: 0,
\PDO::PARAM_INT
);
$statement->execute();
$subQuery = [];
$bindElem = [];
foreach ($resource->getResources() as $key => $resourceElem) {
$subQuery[] = "(:notificationId, :resource_{$key})";
$bindElem[":resource_{$key}"] = $resourceElem->getId();
}
$statement = $this->db->prepare($this->translateDbName(
'INSERT INTO `:db`.notification_hg_relation (notification_id, hg_id) VALUES ' . implode(', ', $subQuery)
));
$statement->bindValue(':notificationId', $notificationId, \PDO::PARAM_INT);
foreach ($bindElem as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->execute();
if (! $alreadyInTransaction) {
$this->db->commit();
}
}
/**
* @inheritDoc
*/
public function countResourcesByNotificationIdsAndAccessGroups(
array $notificationIds,
array $accessGroups,
): array {
$accessGroupIds = array_map(
static fn (AccessGroup $accessGroup) => $accessGroup->getId(),
$accessGroups
);
[$bindNotificationValues, $subNotificationQuery] = $this->createMultipleBindQuery($notificationIds, ':nid_');
[$bindAccessGroupValues, $subAccessGroupQuery] = $this->createMultipleBindQuery($accessGroupIds, ':aid_');
$statement = $this->db->prepare(
$this->translateDbName(
<<<SQL
SELECT notification_id, COUNT(DISTINCT rel.hg_id)
FROM `:db`.notification_hg_relation rel
INNER JOIN `:db`.acl_resources_hg_relations arhr
ON rel.hg_id = arhr.hg_hg_id
INNER JOIN `:db`.acl_resources res
ON arhr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_res_group_relations argr
ON res.acl_res_id = argr.acl_res_id
INNER JOIN `:db`.acl_groups ag
ON argr.acl_group_id = ag.acl_group_id
WHERE ag.acl_group_id IN ({$subAccessGroupQuery})
AND notification_id IN ({$subNotificationQuery})
GROUP BY notification_id
SQL
)
);
foreach ([...$bindNotificationValues, ...$bindAccessGroupValues] as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->execute();
$result = $statement->fetchAll(\PDO::FETCH_KEY_PAIR);
return $result ?: [];
}
/**
* @inheritDoc
*/
public function countResourcesByNotificationIds(array $notificationIds): array
{
[$bindNotificationValues, $subNotificationQuery] = $this->createMultipleBindQuery($notificationIds, ':id_');
$statement = $this->db->prepare(
$this->translateDbName(
<<<SQL
SELECT notification_id, COUNT(DISTINCT rel.hg_id)
FROM `:db`.notification_hg_relation rel
WHERE notification_id IN ({$subNotificationQuery})
GROUP BY notification_id
SQL
)
);
foreach ($bindNotificationValues as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->execute();
$result = $statement->fetchAll(\PDO::FETCH_KEY_PAIR);
return $result ?: [];
}
/**
* @inheritDoc
*/
public function deleteByNotificationIdAndResourcesId(int $notificationId, array $resourcesIds): void
{
$resetEventStatement = $this->db->prepare($this->translateDbName(
<<<'SQL'
UPDATE `:db`.notification SET
hostgroup_events = 0,
included_service_events = 0
WHERE id = :notificationId
SQL
));
$resetEventStatement->bindValue(':notificationId', $notificationId, \PDO::PARAM_INT);
$resetEventStatement->execute();
$bindValues = [];
foreach ($resourcesIds as $resourceId) {
$bindValues[':resource_id' . $resourceId] = $resourceId;
}
$hostGroupsIds = implode(', ', array_keys($bindValues));
$deleteStatement = $this->db->prepare($this->translateDbName(
<<<SQL
DELETE FROM `:db`.notification_hg_relation
WHERE hg_id IN ({$hostGroupsIds})
AND notification_id = :notificationId
SQL
));
foreach ($bindValues as $token => $resourceId) {
$deleteStatement->bindValue($token, $resourceId, \PDO::PARAM_INT);
}
$deleteStatement->bindValue(':notificationId', $notificationId, \PDO::PARAM_INT);
$deleteStatement->execute();
}
/**
* @inheritDoc
*/
public function deleteAllByNotification(int $notificationId): void
{
$resetEventStatement = $this->db->prepare($this->translateDbName(
<<<'SQL'
UPDATE `:db`.notification SET
hostgroup_events = 0,
included_service_events = 0
WHERE id = :notificationId
SQL
));
$resetEventStatement->bindValue(':notificationId', $notificationId, \PDO::PARAM_INT);
$resetEventStatement->execute();
$deleteStatement = $this->db->prepare($this->translateDbName(
<<<'SQL'
DELETE FROM `:db`.notification_hg_relation
WHERE notification_id = :notificationId
SQL
));
$deleteStatement->bindValue(':notificationId', $notificationId, \PDO::PARAM_INT);
$deleteStatement->execute();
}
/**
* @param int $notificationId
*
* @return int[]
*/
private function retrieveEvents(int $notificationId): array
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
SELECT
hostgroup_events,
included_service_events
FROM `:db`.notification
WHERE id = :notificationId
SQL
));
$statement->bindValue(':notificationId', $notificationId, \PDO::PARAM_INT);
$statement->execute();
/** @var array<string,int> */
$result = $statement->fetch(\PDO::FETCH_ASSOC);
return $result ? [$result['hostgroup_events'], $result['included_service_events']] : [0, 0];
}
/**
* @param int[] $accessGroupIds
*
* @return SqlConcatenator
*/
private function getConcatenatorForExistRequest(array $accessGroupIds = []): SqlConcatenator
{
$concatenator = (new SqlConcatenator())
->defineSelect(
<<<'SQL'
SELECT
hg.hg_id
SQL
)->defineFrom(
<<<'SQL'
FROM
`:db`.`hostgroup` hg
SQL
);
if ($accessGroupIds !== []) {
$concatenator->appendJoins(
<<<'SQL'
INNER JOIN `:db`.acl_resources_hg_relations arhr
ON hg.hg_id = arhr.hg_hg_id
INNER JOIN `:db`.acl_resources res
ON arhr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_res_group_relations argr
ON res.acl_res_id = argr.acl_res_id
INNER JOIN `:db`.acl_groups ag
ON argr.acl_group_id = ag.acl_group_id
SQL
)->appendWhere(
<<<'SQL'
WHERE ag.acl_group_id IN (:accessGroupIds)
SQL
)->storeBindValueMultiple(':accessGroupIds', $accessGroupIds, \PDO::PARAM_INT);
}
return $concatenator;
}
/**
* @param int[] $accessGroupIds
*
* @return SqlConcatenator
*/
private function getConcatenatorForFindRequest(array $accessGroupIds = []): SqlConcatenator
{
$concatenator = (new SqlConcatenator())
->defineSelect(
<<<'SQL'
SELECT DISTINCT
rel.hg_id, hg.hg_name
SQL
)->defineFrom(
<<<'SQL'
FROM
`:db`.notification_hg_relation rel
SQL
)->appendJoins(
<<<'SQL'
INNER JOIN `:db`.hostgroup hg
ON rel.hg_id = hg.hg_id
SQL
);
if ($accessGroupIds !== []) {
$concatenator->appendJoins(
<<<'SQL'
INNER JOIN `:db`.acl_resources_hg_relations arhr
ON rel.hg_id = arhr.hg_hg_id
INNER JOIN `:db`.acl_resources res
ON arhr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_res_group_relations argr
ON res.acl_res_id = argr.acl_res_id
INNER JOIN `:db`.acl_groups ag
ON argr.acl_group_id = ag.acl_group_id
SQL
)->appendWhere(
<<<'SQL'
WHERE ag.acl_group_id IN (:accessGroupIds)
SQL
)->storeBindValueMultiple(':accessGroupIds', $accessGroupIds, \PDO::PARAM_INT);
}
return $concatenator;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Infrastructure/Repository/MetaServiceRequestProvider.php | centreon/src/Core/Notification/Infrastructure/Repository/MetaServiceRequestProvider.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Infrastructure\Repository;
use Core\Notification\Application\Repository\NotifiableResourceRequestProviderInterface;
class MetaServiceRequestProvider implements NotifiableResourceRequestProviderInterface
{
/**
* @inheritDoc
*/
public function getNotifiableResourceSubRequest(): string
{
return <<<'SQL'
SELECT n.`id` AS `notification_id`,
hsr.`host_host_id` AS `host_id`,
h.`host_name` AS `host_name`,
h.`host_alias` AS `host_alias`,
0 AS `host_events`,
s.`service_id` AS `service_id`,
ms.`meta_name` AS `service_name`,
s.`service_alias` AS `service_alias`,
n.`servicegroup_events` AS `service_events`,
0 AS `included_service_events`
FROM `:db`.`meta_service` ms
INNER JOIN `:db`.`service` s ON s.`service_description` = CONCAT('meta_', CAST(ms.`meta_id` AS CHAR))
INNER JOIN `:db`.`host_service_relation` hsr ON hsr.`service_service_id` = s.`service_id`
INNER JOIN `:db`.`host` h ON h.`host_id` = hsr.`host_host_id`
INNER JOIN `:db`.`servicegroup_relation` sgr ON sgr.`service_service_id` = s.`service_id`
INNER JOIN `:db`.`notification_sg_relation` nsgr ON nsgr.`sg_id` = sgr.`servicegroup_sg_id`
INNER JOIN `:db`.`notification` n ON n.`id` = nsgr.`notification_id`
WHERE n.`is_activated` = 1
SQL;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Infrastructure/Repository/NotificationResourceRepositoryProvider.php | centreon/src/Core/Notification/Infrastructure/Repository/NotificationResourceRepositoryProvider.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Infrastructure\Repository;
use Core\Notification\Application\Exception\NotificationException;
use Core\Notification\Application\Repository\NotificationResourceRepositoryInterface;
use Core\Notification\Application\Repository\NotificationResourceRepositoryProviderInterface;
class NotificationResourceRepositoryProvider implements NotificationResourceRepositoryProviderInterface
{
/** @var non-empty-array<NotificationResourceRepositoryInterface> */
private array $repositories;
/**
* @param NotificationResourceRepositoryInterface[] $repositories
*
* @throws \InvalidArgumentException
*/
public function __construct(
iterable $repositories,
) {
$reposAsArray = is_array($repositories) ? $repositories : iterator_to_array($repositories);
if ($reposAsArray === []) {
throw new \InvalidArgumentException('There must be at least one notification resource provider');
}
$this->repositories = $reposAsArray;
}
/**
* Return the repository matching the provided type.
*
* @param string $type
*
* @throws \Throwable
*
* @return NotificationResourceRepositoryInterface
*/
public function getRepository(string $type): NotificationResourceRepositoryInterface
{
foreach ($this->repositories as $provider) {
if ($provider->supportResourceType($type)) {
return $provider;
}
}
throw NotificationException::invalidResourceType();
}
/**
* Return all resource repositories.
*
* @throws \Throwable
*
* @return non-empty-array<NotificationResourceRepositoryInterface>
*/
public function getRepositories(): array
{
return $this->repositories;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Infrastructure/Repository/DbReadNotifiableResourceRepository.php | centreon/src/Core/Notification/Infrastructure/Repository/DbReadNotifiableResourceRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Infrastructure\Repository;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Notification\Application\Repository\NotifiableResourceRequestProviderInterface;
use Core\Notification\Application\Repository\ReadNotifiableResourceRepositoryInterface as RepositoryInterface;
class DbReadNotifiableResourceRepository extends AbstractRepositoryRDB implements RepositoryInterface
{
use LoggerTrait;
/** @var NotifiableResourceRequestProviderInterface[] */
private array $notifiableResourceRequestProviders;
/**
* @param DatabaseConnection $db
* @param NotifiableResourceRequestProviderInterface[] $notifiableResourceRequestProviders
*/
public function __construct(DatabaseConnection $db, iterable $notifiableResourceRequestProviders)
{
$this->db = $db;
$requestProvidersAsArray = \is_array($notifiableResourceRequestProviders)
? $notifiableResourceRequestProviders
: \iterator_to_array($notifiableResourceRequestProviders);
if ($requestProvidersAsArray === []) {
throw new \InvalidArgumentException('There must be at least one notifiable resource request provider');
}
$this->notifiableResourceRequestProviders = $requestProvidersAsArray;
}
/**
* @inheritDoc
*/
public function findAllForActivatedNotifications(): \Generator
{
$providerSubRequests = $this->getRequestsFromProviders();
$request = <<<SQL
{$providerSubRequests}
ORDER BY `notification_id`, `host_id`, `service_id`;
SQL;
$statement = $this->db->prepare($this->translateDbName($request));
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
/**
* @var iterable<int,array{
* notification_id: int,
* host_id: int,
* host_name: string,
* host_alias: string|null,
* host_events: int,
* service_id: int,
* service_name: string,
* service_alias: string,
* service_events: int,
* included_service_events: int
* }> $statement
*/
yield from DbNotifiableResourceFactory::createFromRecords($statement);
}
/**
* @return string
*/
private function getRequestsFromProviders(): string
{
$requests = \array_map(
fn (NotifiableResourceRequestProviderInterface $provider) => $provider->getNotifiableResourceSubRequest(),
$this->notifiableResourceRequestProviders
);
return \implode(' UNION ', $requests);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Infrastructure/API/FindNotification/FindNotificationPresenter.php | centreon/src/Core/Notification/Infrastructure/API/FindNotification/FindNotificationPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Infrastructure\API\FindNotification;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Notification\Application\Converter\NotificationHostEventConverter;
use Core\Notification\Application\Converter\NotificationServiceEventConverter;
use Core\Notification\Application\UseCase\FindNotification\FindNotificationPresenterInterface;
use Core\Notification\Application\UseCase\FindNotification\FindNotificationResponse;
use Core\Notification\Domain\Model\HostEvent;
use Core\Notification\Domain\Model\NotificationResource;
use Core\Notification\Domain\Model\ServiceEvent;
/**
* @phpstan-import-type _Resource from FindNotificationResponse
*/
class FindNotificationPresenter extends AbstractPresenter implements FindNotificationPresenterInterface
{
public function presentResponse(FindNotificationResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
$this->present([
'id' => $response->id,
'name' => $response->name,
'timeperiod' => [
'id' => $response->timeperiodId,
'name' => $response->timeperiodName,
],
'is_activated' => $response->isActivated,
'messages' => $response->messages,
'users' => $response->users,
'contactgroups' => $response->contactGroups,
'resources' => $this->formatResource($response->resources),
]);
}
}
/**
* format Resources.
*
* @param array<_Resource> $resources
*
* @return array<array{
* type: string,
* events: int,
* ids: array<array{id: int, name: string}>,
* extra?: array{
* event_services: int
* }
* }>
*/
private function formatResource(array $resources): array
{
// We must use another array carrier in order to keep the input immutable for phpstan.
$formatted = [];
foreach ($resources as $index => $resource) {
if ($resource['type'] === NotificationResource::TYPE_HOST_GROUP) {
/** @var array<HostEvent> $events */
$events = $resource['events'];
$eventBitFlags = NotificationHostEventConverter::toBitFlags($events);
} else {
/** @var array<ServiceEvent> $events */
$events = $resource['events'];
$eventBitFlags = NotificationServiceEventConverter::toBitFlags($events);
}
$formatted[$index] = [
'type' => $resource['type'],
'events' => $eventBitFlags,
'ids' => $resource['ids'],
];
if (array_key_exists('extra', $resource)) {
$formatted[$index]['extra']['event_services'] = NotificationServiceEventConverter::toBitFlags(
$resource['extra']['event_services']
);
}
}
return $formatted;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Infrastructure/API/FindNotification/FindNotificationController.php | centreon/src/Core/Notification/Infrastructure/API/FindNotification/FindNotificationController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Infrastructure\API\FindNotification;
use Centreon\Application\Controller\AbstractController;
use Core\Notification\Application\UseCase\FindNotification\FindNotification;
use Symfony\Component\HttpFoundation\Response;
final class FindNotificationController extends AbstractController
{
/**
* @param int $notificationId
* @param FindNotification $useCase
* @param FindNotificationPresenter $presenter
*
* @return Response
*/
public function __invoke(int $notificationId, FindNotification $useCase, FindNotificationPresenter $presenter): Response
{
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($notificationId, $presenter);
return $presenter->show();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Infrastructure/API/DeleteNotification/DeleteNotificationPresenter.php | centreon/src/Core/Notification/Infrastructure/API/DeleteNotification/DeleteNotificationPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Infrastructure\API\DeleteNotification;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Notification\Application\UseCase\DeleteNotification\DeleteNotificationPresenterInterface;
final class DeleteNotificationPresenter extends AbstractPresenter implements DeleteNotificationPresenterInterface
{
/**
* @inheritDoc
*/
public function presentResponse(NoContentResponse|ResponseStatusInterface $data): void
{
if ($data instanceof NoContentResponse) {
$this->present($data);
} else {
$this->setResponseStatus($data);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Infrastructure/API/DeleteNotification/DeleteNotificationController.php | centreon/src/Core/Notification/Infrastructure/API/DeleteNotification/DeleteNotificationController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Infrastructure\API\DeleteNotification;
use Centreon\Application\Controller\AbstractController;
use Core\Notification\Application\UseCase\DeleteNotification\DeleteNotification;
use Symfony\Component\HttpFoundation\Response;
final class DeleteNotificationController extends AbstractController
{
/**
* @param int $notificationId
* @param DeleteNotification $useCase
* @param DeleteNotificationPresenter $presenter
*
* @return Response
*/
public function __invoke(
int $notificationId,
DeleteNotification $useCase,
DeleteNotificationPresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($notificationId, $presenter);
return $presenter->show();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Infrastructure/API/FindNotifiableRule/FindNotifiableRulePresenter.php | centreon/src/Core/Notification/Infrastructure/API/FindNotifiableRule/FindNotifiableRulePresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Infrastructure\API\FindNotifiableRule;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Notification\Application\UseCase\FindNotifiableRule\FindNotifiableRulePresenterInterface;
use Core\Notification\Application\UseCase\FindNotifiableRule\FindNotifiableRuleResponse;
use Core\Notification\Application\UseCase\FindNotifiableRule\Response\ContactDto;
final class FindNotifiableRulePresenter extends AbstractPresenter implements FindNotifiableRulePresenterInterface
{
public function presentResponse(FindNotifiableRuleResponse|ResponseStatusInterface $data): void
{
if ($data instanceof FindNotifiableRuleResponse) {
$this->present([
'notification_id' => $data->notificationId,
'channels' => [
'email' => $data->channels->email === null ? null : [
'subject' => $data->channels->email->subject,
'formatted_message' => $data->channels->email->formattedMessage,
'contacts' => array_map(
static fn (ContactDto $contact) => [
'email_address' => $contact->emailAddress,
'full_name' => $contact->fullName,
],
$data->channels->email->contacts
),
],
'slack' => $data->channels->slack === null ? null : [
'slack_channel' => $data->channels->slack->slackChannel,
'message' => $data->channels->slack->message,
],
'sms' => $data->channels->sms === null ? null : [
'phone_number' => $data->channels->sms->phoneNumber,
'message' => $data->channels->sms->message,
],
],
]);
} else {
$this->setResponseStatus($data);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Infrastructure/API/FindNotifiableRule/FindNotifiableRuleController.php | centreon/src/Core/Notification/Infrastructure/API/FindNotifiableRule/FindNotifiableRuleController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Infrastructure\API\FindNotifiableRule;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Notification\Application\UseCase\FindNotifiableRule\FindNotifiableRule;
use Core\Notification\Application\UseCase\FindNotifiableRule\FindNotifiableRulePresenterInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class FindNotifiableRuleController extends AbstractController
{
use LoggerTrait;
/**
* @param int $notificationId
* @param FindNotifiableRule $useCase
* @param FindNotifiableRulePresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
int $notificationId,
FindNotifiableRule $useCase,
FindNotifiableRulePresenterInterface $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($notificationId, $presenter);
return $presenter->show();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Infrastructure/API/FindNotifiableResources/FindNotifiableResourcesPresenter.php | centreon/src/Core/Notification/Infrastructure/API/FindNotifiableResources/FindNotifiableResourcesPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Infrastructure\API\FindNotifiableResources;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Notification\Application\UseCase\FindNotifiableResources\{
FindNotifiableResourcesPresenterInterface as PresenterInterface,
FindNotifiableResourcesResponse
};
class FindNotifiableResourcesPresenter extends AbstractPresenter implements PresenterInterface
{
/**
* @inheritDoc
*/
public function presentResponse(FindNotifiableResourcesResponse|ResponseStatusInterface $response): void
{
if ($response instanceof FindNotifiableResourcesResponse) {
$result = [];
foreach ($response->notifiableResources as $notifiableResource) {
$result[] = [
'notification_id' => $notifiableResource->notificationId,
'hosts' => $notifiableResource->hosts,
];
}
$this->present([
'uid' => $response->uid,
'result' => $result,
]);
} else {
$this->setResponseStatus($response);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Infrastructure/API/FindNotifiableResources/FindNotifiableResourcesController.php | centreon/src/Core/Notification/Infrastructure/API/FindNotifiableResources/FindNotifiableResourcesController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Infrastructure\API\FindNotifiableResources;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Notification\Application\UseCase\FindNotifiableResources\FindNotifiableResources;
use Symfony\Component\HttpFoundation\{Request, Response};
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class FindNotifiableResourcesController extends AbstractController
{
use LoggerTrait;
/**
* @param FindNotifiableResources $useCase
* @param FindNotifiableResourcesPresenter $presenter
* @param Request $request
*
* @throws AccessDeniedException|\Throwable
*
* @return Response
*/
public function __invoke(
Request $request,
FindNotifiableResources $useCase,
FindNotifiableResourcesPresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
$requestUid = $request->headers->get('X-Notifiable-Resources-UID', null);
if (! \is_string($requestUid)) {
$presenter->presentResponse(new InvalidArgumentResponse('Missing header'));
$this->error(
'Missing header "X-Notifiable-Resources-UID"',
['X-Notifiable-Resources-UID' => $requestUid]
);
} else {
$useCase($presenter, $requestUid);
}
return $presenter->show();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Infrastructure/API/AddNotification/AddNotificationController.php | centreon/src/Core/Notification/Infrastructure/API/AddNotification/AddNotificationController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Infrastructure\API\AddNotification;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Notification\Application\UseCase\AddNotification\AddNotification;
use Core\Notification\Application\UseCase\AddNotification\AddNotificationRequest;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class AddNotificationController extends AbstractController
{
use LoggerTrait;
/**
* @param Request $request
* @param AddNotification $useCase
* @param AddNotificationPresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
Request $request,
AddNotification $useCase,
AddNotificationPresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
try {
/** @var array{
* name: string,
* timeperiod_id: int,
* users: int[],
* contactgroups: int[],
* resources: array<array{
* type:string,
* ids:int[],
* events:int,
* extra?:array{event_services?: int}
* }>,
* messages: array<array{
* channel:string,
* subject:string,
* message:string,
* formatted_message:string
* }>,
* is_activated?: bool,
* } $data
*/
$data = $this->validateAndRetrieveDataSent($request, __DIR__ . '/AddNotificationSchema.json');
} catch (\InvalidArgumentException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
return $presenter->show();
}
$notificationRequest = $this->createRequestDto($data);
$useCase($notificationRequest, $presenter);
return $presenter->show();
}
/**
* @param array{
* name: string,
* timeperiod_id: int,
* users: int[],
* contactgroups: int[],
* resources: array<array{
* type:string,
* ids:int[],
* events:int,
* extra?:array{event_services?: int}
* }>,
* messages: array<array{
* channel:string,
* subject:string,
* message:string,
* formatted_message:string
* }>,
* is_activated?: bool,
* } $data
*
* @return AddNotificationRequest
*/
private function createRequestDto(array $data): AddNotificationRequest
{
$notificationRequest = new AddNotificationRequest();
$notificationRequest->name = $data['name'];
$notificationRequest->timePeriodId = $data['timeperiod_id'];
$notificationRequest->isActivated = $data['is_activated'] ?? true;
$notificationRequest->users = $data['users'];
$notificationRequest->contactGroups = $data['contactgroups'];
foreach ($data['messages'] as $messageData) {
$notificationRequest->messages[] = [
'channel' => $messageData['channel'],
'subject' => $messageData['subject'],
'message' => $messageData['message'],
'formatted_message' => $messageData['formatted_message'],
];
}
foreach ($data['resources'] as $resourceData) {
$notificationRequest->resources[] = [
'type' => $resourceData['type'],
'ids' => $resourceData['ids'],
'events' => $resourceData['events'],
'includeServiceEvents' => $resourceData['extra']['event_services']
?? 0,
];
}
return $notificationRequest;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Infrastructure/API/AddNotification/AddNotificationPresenter.php | centreon/src/Core/Notification/Infrastructure/API/AddNotification/AddNotificationPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Infrastructure\API\AddNotification;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\CreatedResponse;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Notification\Application\UseCase\AddNotification\AddNotificationResponse;
class AddNotificationPresenter extends AbstractPresenter
{
use LoggerTrait;
public function __construct(
PresenterFormatterInterface $presenterFormatter,
) {
parent::__construct($presenterFormatter);
}
/**
* @inheritDoc
*/
public function present(mixed $data): void
{
if (
$data instanceof CreatedResponse
&& $data->getPayload() instanceof AddNotificationResponse
) {
$payload = $data->getPayload();
$data->setPayload([
'id' => $payload->id,
'name' => $payload->name,
'timeperiod' => $payload->timeperiod,
'users' => $payload->users,
'contactgroups' => $payload->contactGroups,
'resources' => $payload->resources,
'messages' => $payload->messages,
'is_activated' => $payload->isActivated,
]);
}
parent::present($data);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Infrastructure/API/DeleteNotifications/DeleteNotificationsController.php | centreon/src/Core/Notification/Infrastructure/API/DeleteNotifications/DeleteNotificationsController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Infrastructure\API\DeleteNotifications;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Notification\Application\UseCase\DeleteNotifications\{DeleteNotifications, DeleteNotificationsRequest};
use Symfony\Component\HttpFoundation\{Request, Response};
final class DeleteNotificationsController extends AbstractController
{
use LoggerTrait;
/**
* @param Request $request
* @param DeleteNotifications $useCase
* @param DeleteNotificationsPresenter $presenter
*
* @return Response
*/
public function __invoke(
Request $request,
DeleteNotifications $useCase,
DeleteNotificationsPresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
try {
/**
* @var array{
* ids: int[]
* } $data
*/
$data = $this->validateAndRetrieveDataSent($request, __DIR__ . '/DeleteNotificationsSchema.json');
} catch (\InvalidArgumentException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
return $presenter->show();
}
$requestDto = $this->createRequestDto($data);
$useCase($requestDto, $presenter);
return $presenter->show();
}
/**
* @param array{
* ids: int[]
* } $data
*
* @return DeleteNotificationsRequest
*/
private function createRequestDto(array $data): DeleteNotificationsRequest
{
$requestDto = new DeleteNotificationsRequest();
$requestDto->ids = $data['ids'];
return $requestDto;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Infrastructure/API/DeleteNotifications/DeleteNotificationsPresenter.php | centreon/src/Core/Notification/Infrastructure/API/DeleteNotifications/DeleteNotificationsPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Infrastructure\API\DeleteNotifications;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\{AbstractPresenter, ResponseStatusInterface};
use Core\Infrastructure\Common\Api\Router;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Notification\Application\UseCase\DeleteNotifications\{
DeleteNotificationsPresenterInterface,
DeleteNotificationsResponse,
DeleteNotificationsStatusResponse
};
use Core\Notification\Domain\Model\ResponseCode;
use Symfony\Component\HttpFoundation\Response;
final class DeleteNotificationsPresenter extends AbstractPresenter implements DeleteNotificationsPresenterInterface
{
use LoggerTrait;
private const ROUTE_NAME = 'DeleteNotification';
/**
* @param PresenterFormatterInterface $presenterFormatter
* @param Router $router
*/
public function __construct(
protected PresenterFormatterInterface $presenterFormatter,
private readonly Router $router,
) {
parent::__construct($presenterFormatter);
}
/**
* @inheritDoc
*/
public function presentResponse(DeleteNotificationsResponse|ResponseStatusInterface $response): void
{
if ($response instanceof DeleteNotificationsResponse) {
$multiStatusResponse = [
'results' => array_map(fn (DeleteNotificationsStatusResponse $notificationDto) => [
'href' => $this->getDeletedNotificationHref($notificationDto->id),
'status' => $this->enumToIntConverter($notificationDto->status),
'message' => $notificationDto->message,
], $response->results),
];
$this->present($multiStatusResponse);
} else {
$this->setResponseStatus($response);
}
}
/**
* @param ResponseCode $code
*
* @return int
*/
private function enumToIntConverter(ResponseCode $code): int
{
return match ($code) {
ResponseCode::OK => Response::HTTP_NO_CONTENT,
ResponseCode::NotFound => Response::HTTP_NOT_FOUND,
ResponseCode::Error => Response::HTTP_INTERNAL_SERVER_ERROR,
};
}
/**
* @param int $id
*
* @return string|null
*/
private function getDeletedNotificationHref(int $id): ?string
{
try {
return $this->router->generate(self::ROUTE_NAME, ['notificationId' => $id]);
} catch (\Throwable $ex) {
$this->error('Impossible to generate the deleted entity route', [
'message' => $ex->getMessage(),
'trace' => $ex->getTraceAsString(),
'route' => self::ROUTE_NAME,
'payload' => $id,
]);
return null;
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Infrastructure/API/PartialUpdateNotification/PartialUpdateNotificationController.php | centreon/src/Core/Notification/Infrastructure/API/PartialUpdateNotification/PartialUpdateNotificationController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Infrastructure\API\PartialUpdateNotification;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\{ErrorResponse, InvalidArgumentResponse};
use Core\Notification\Application\Exception\NotificationException;
use Core\Notification\Application\UseCase\PartialUpdateNotification\{
PartialUpdateNotification,
PartialUpdateNotificationRequest
};
use Symfony\Component\HttpFoundation\{Request, Response};
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class PartialUpdateNotificationController extends AbstractController
{
use LoggerTrait;
/**
* @param Request $request
* @param PartialUpdateNotification $useCase
* @param PartialUpdateNotificationPresenter $presenter
* @param int $notificationId
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
Request $request,
PartialUpdateNotification $useCase,
PartialUpdateNotificationPresenter $presenter,
int $notificationId,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
try {
/**
* @var array{
* is_activated?: bool
* } $data
*/
$data = $this->validateAndRetrieveDataSent($request, __DIR__ . '/PartialUpdateNotificationSchema.json');
$requestDto = new PartialUpdateNotificationRequest();
if (\array_key_exists('is_activated', $data)) {
$requestDto->isActivated = $data['is_activated'];
}
$useCase($requestDto, $presenter, $notificationId);
} catch (\InvalidArgumentException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(
new ErrorResponse(NotificationException::errorWhilePartiallyUpdatingObject())
);
}
return $presenter->show();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Infrastructure/API/PartialUpdateNotification/PartialUpdateNotificationPresenter.php | centreon/src/Core/Notification/Infrastructure/API/PartialUpdateNotification/PartialUpdateNotificationPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Infrastructure\API\PartialUpdateNotification;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Notification\Application\UseCase\PartialUpdateNotification\{
PartialUpdateNotificationPresenterInterface as PresenterInterface
};
final class PartialUpdateNotificationPresenter extends AbstractPresenter implements PresenterInterface
{
/**
* @inheritDoc
*/
public function presentResponse(ResponseStatusInterface $response): void
{
$this->setResponseStatus($response);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Infrastructure/API/FindNotifications/FindNotificationsController.php | centreon/src/Core/Notification/Infrastructure/API/FindNotifications/FindNotificationsController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Infrastructure\API\FindNotifications;
use Centreon\Application\Controller\AbstractController;
use Core\Notification\Application\UseCase\FindNotifications\FindNotifications;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class FindNotificationsController extends AbstractController
{
/**
* @param FindNotifications $useCase
* @param FindNotificationsPresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(FindNotifications $useCase, FindNotificationsPresenter $presenter): Response
{
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($presenter);
return $presenter->show();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Infrastructure/API/FindNotifications/FindNotificationsPresenter.php | centreon/src/Core/Notification/Infrastructure/API/FindNotifications/FindNotificationsPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Infrastructure\API\FindNotifications;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Notification\Application\UseCase\FindNotifications\FindNotificationsPresenterInterface;
use Core\Notification\Application\UseCase\FindNotifications\FindNotificationsResponse;
use Core\Notification\Domain\Model\Channel;
class FindNotificationsPresenter extends AbstractPresenter implements FindNotificationsPresenterInterface
{
public function __construct(
private readonly RequestParametersInterface $requestParameters,
protected PresenterFormatterInterface $presenterFormatter,
) {
parent::__construct($presenterFormatter);
}
/**
* @param FindNotificationsResponse|ResponseStatusInterface $response
*/
public function presentResponse(FindNotificationsResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
$this->present(
[
'result' => array_map(static fn ($notificationDto) => [
'id' => $notificationDto->id,
'is_activated' => $notificationDto->isActivated,
'name' => $notificationDto->name,
'user_count' => $notificationDto->usersCount,
'channels' => self::convertNotificationChannelToString(
$notificationDto->notificationChannels
),
'resources' => $notificationDto->resources,
'timeperiod' => [
'id' => $notificationDto->timeperiodId,
'name' => $notificationDto->timeperiodName,
],
], $response->notifications),
'meta' => $this->requestParameters->toArray(),
]
);
}
}
/**
* Convert NotificationChannel Enum values to string values.
*
* @param Channel[] $notificationChannels
*
* @return string[]
*/
private static function convertNotificationChannelToString(array $notificationChannels): array
{
$notificationChannelsToString = [];
foreach ($notificationChannels as $notificationChannel) {
$notificationChannelsToString[] = $notificationChannel->value;
}
return $notificationChannelsToString;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Notification/Infrastructure/API/UpdateNotification/UpdateNotificationController.php | centreon/src/Core/Notification/Infrastructure/API/UpdateNotification/UpdateNotificationController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Infrastructure\API\UpdateNotification;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Notification\Application\UseCase\UpdateNotification\UpdateNotification;
use Core\Notification\Application\UseCase\UpdateNotification\UpdateNotificationRequest;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* @phpstan-type _RequestArray array{
* name: string,
* timeperiod_id: int,
* users: int[],
* contactgroups: int[],
* resources: array<array{
* type: string,
* ids: int[],
* events: int,
* extra?: array{event_services?: int}
* }>,
* messages: array<array{
* channel: string,
* subject: string,
* message: string,
* formatted_message: string,
* }>,
* is_activated?: bool,
* }
*/
final class UpdateNotificationController extends AbstractController
{
use LoggerTrait;
public function __invoke(
int $notificationId,
Request $request,
UpdateNotification $useCase,
UpdateNotificationPresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
try {
/** @var _RequestArray $dataSent */
$dataSent = $this->validateAndRetrieveDataSent($request, __DIR__ . '/UpdateNotificationSchema.json');
$updateNotificationRequest = $this->createUpdateNotificationRequest($notificationId, $dataSent);
$useCase($updateNotificationRequest, $presenter);
} catch (\InvalidArgumentException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
}
return $presenter->show();
}
/**
* Create DTO.
*
* @param int $notificationId
* @param _RequestArray $dataSent
*
* @return UpdateNotificationRequest
*/
public function createUpdateNotificationRequest(int $notificationId, array $dataSent): UpdateNotificationRequest
{
$request = new UpdateNotificationRequest();
$request->id = $notificationId;
$request->name = $dataSent['name'];
$request->users = $dataSent['users'];
$request->contactGroups = $dataSent['contactgroups'];
foreach ($dataSent['messages'] as $messageData) {
$request->messages[] = [
'channel' => $messageData['channel'],
'subject' => $messageData['subject'],
'message' => $messageData['message'],
'formatted_message' => $messageData['formatted_message'],
];
}
foreach ($dataSent['resources'] as $resourceData) {
$request->resources[] = [
'type' => $resourceData['type'],
'ids' => $resourceData['ids'],
'events' => $resourceData['events'],
'includeServiceEvents' => $resourceData['extra']['event_services']
?? 0,
];
}
$request->timePeriodId = $dataSent['timeperiod_id'];
$request->isActivated = $dataSent['is_activated'] ?? true;
return $request;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.