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/Dashboard/Infrastructure/API/ShareDashboard/ShareDashboardController.php | centreon/src/Core/Dashboard/Infrastructure/API/ShareDashboard/ShareDashboardController.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\Dashboard\Infrastructure\API\ShareDashboard;
use Centreon\Application\Controller\AbstractController;
use Core\Dashboard\Application\UseCase\ShareDashboard\ShareDashboard;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\MapRequestPayload;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted(
'dashboard_access_editor',
null,
'You do not have sufficient rights to share a dashboard'
)]
final class ShareDashboardController extends AbstractController
{
public function __invoke(
int $dashboardId,
ShareDashboard $useCase,
Request $request,
#[MapRequestPayload] ShareDashboardInput $mappedRequest,
): Response {
$request = ShareDashboardRequestTransformer::transform($mappedRequest);
$request->dashboardId = $dashboardId;
return $this->createResponse($useCase($request));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Infrastructure/API/ShareDashboard/ShareDashboardInput.php | centreon/src/Core/Dashboard/Infrastructure/API/ShareDashboard/ShareDashboardInput.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\Dashboard\Infrastructure\API\ShareDashboard;
use Symfony\Component\Validator\Constraints as Assert;
final readonly class ShareDashboardInput
{
/**
* @param array<array{id: int, role: string}> $contacts
* @param array<array{id: int, role: string}> $contactGroups
*/
public function __construct(
#[Assert\All([
new Assert\Collection([
'id' => [
new Assert\NotBlank(),
new Assert\Type('integer'),
],
'role' => [
new Assert\NotBlank(),
new Assert\Choice([
'choices' => ['editor', 'viewer'],
'message' => 'Role provided for contact is not valid. Valid roles are: editor, viewer',
]),
],
]),
])]
public array $contacts = [],
#[Assert\All([
new Assert\Collection([
'id' => [
new Assert\NotBlank(),
new Assert\Type('integer'),
],
'role' => [
new Assert\NotBlank(),
new Assert\Choice([
'choices' => ['editor', 'viewer'],
'message' => 'Role provided for contact group is not valid. Valid roles are: editor, viewer',
]),
],
]),
])]
public array $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/Dashboard/Infrastructure/API/DeleteDashboardFromFavorites/DeleteDashboardFromFavoritesController.php | centreon/src/Core/Dashboard/Infrastructure/API/DeleteDashboardFromFavorites/DeleteDashboardFromFavoritesController.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\Dashboard\Infrastructure\API\DeleteDashboardFromFavorites;
use Centreon\Application\Controller\AbstractController;
use Core\Dashboard\Application\UseCase\DeleteDashboardFromFavorites\DeleteDashboardFromFavorites;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted(
'dashboard_access',
null,
'You do not have sufficient rights to remove the dashboard from favorites'
)]
final class DeleteDashboardFromFavoritesController extends AbstractController
{
/**
* @param int $dashboardId
* @param DeleteDashboardFromFavorites $useCase
* @return Response
*/
public function __invoke(
int $dashboardId,
DeleteDashboardFromFavorites $useCase,
): Response {
return $this->createResponse($useCase($dashboardId));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Infrastructure/API/FindDashboards/FindDashboardsPresenter.php | centreon/src/Core/Dashboard/Infrastructure/API/FindDashboards/FindDashboardsPresenter.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\Dashboard\Infrastructure\API\FindDashboards;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Dashboard\Application\UseCase\FindDashboards\FindDashboardsPresenterInterface;
use Core\Dashboard\Application\UseCase\FindDashboards\FindDashboardsResponse;
use Core\Dashboard\Application\UseCase\FindDashboards\Response\ThumbnailResponseDto;
use Core\Dashboard\Application\UseCase\FindDashboards\Response\UserResponseDto;
use Core\Dashboard\Domain\Model\Role\DashboardSharingRole;
use Core\Dashboard\Infrastructure\Model\DashboardSharingRoleConverter;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Infrastructure\Common\Presenter\PresenterTrait;
final class FindDashboardsPresenter extends DefaultPresenter implements FindDashboardsPresenterInterface
{
use PresenterTrait;
public function __construct(
protected RequestParametersInterface $requestParameters,
PresenterFormatterInterface $presenterFormatter,
) {
parent::__construct($presenterFormatter);
}
public function presentResponse(FindDashboardsResponse|ResponseStatusInterface $data): void
{
if ($data instanceof FindDashboardsResponse) {
$result = [];
foreach ($data->dashboards as $dashboard) {
$result[] = [
'id' => $dashboard->id,
'name' => $dashboard->name,
'description' => $dashboard->description,
'created_by' => $this->userToOptionalArray($dashboard->createdBy),
'updated_by' => $this->userToOptionalArray($dashboard->updatedBy),
'created_at' => $this->formatDateToIso8601($dashboard->createdAt),
'updated_at' => $this->formatDateToIso8601($dashboard->updatedAt),
'own_role' => DashboardSharingRoleConverter::toString($dashboard->ownRole),
'shares' => $this->formatShares($dashboard->shares),
'thumbnail' => $this->formatThumbnail($dashboard->thumbnail),
'is_favorite' => $dashboard->isFavorite,
];
}
$this->present([
'result' => $result,
'meta' => $this->requestParameters->toArray(),
]);
} else {
$this->setResponseStatus($data);
}
}
/**
* @param ?UserResponseDto $dto
*
* @return null|array{id: int, name: string}
*/
private function userToOptionalArray(?UserResponseDto $dto): ?array
{
return $dto ? [
'id' => $dto->id,
'name' => $dto->name,
] : null;
}
/**
* @param null|ThumbnailResponseDto $dto
*
* @return null|array{id:int, name:string, directory:string}
*/
private function formatThumbnail(?ThumbnailResponseDto $dto): ?array
{
return $dto
? [
'id' => $dto->id,
'name' => $dto->name,
'directory' => $dto->directory,
]
: null;
}
/**
* @param array{
* contacts: array<int, array{
* id: int,
* name: string,
* email: string,
* role: DashboardSharingRole
* }>,
* contact_groups: array<int, array{
* id: int,
* name: string,
* role: DashboardSharingRole
* }>
* } $shares
*
* @return array{
* contacts: array<int, array{
* id: int,
* name: string,
* email: string,
* role: string
* }>,
* contact_groups: array<int, array{
* id: int,
* name: string,
* role: string
* }>
* }
*/
private function formatShares(array $shares): array
{
$formattedShares = ['contacts' => [], 'contact_groups' => []];
foreach ($shares['contacts'] as $contact) {
$formattedShares['contacts'][] = [
'id' => $contact['id'],
'name' => $contact['name'],
'email' => $contact['email'],
'role' => DashboardSharingRoleConverter::toString($contact['role']),
];
}
foreach ($shares['contact_groups'] as $contactGroup) {
$formattedShares['contact_groups'][] = [
'id' => $contactGroup['id'],
'name' => $contactGroup['name'],
'role' => DashboardSharingRoleConverter::toString($contactGroup['role']),
];
}
return $formattedShares;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Infrastructure/API/FindDashboards/FindDashboardsController.php | centreon/src/Core/Dashboard/Infrastructure/API/FindDashboards/FindDashboardsController.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\Dashboard\Infrastructure\API\FindDashboards;
use Centreon\Application\Controller\AbstractController;
use Core\Dashboard\Application\UseCase\FindDashboards\FindDashboards;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted(
'dashboard_access',
null,
'You are not allowed to set dashboard as favorites'
)]
final class FindDashboardsController extends AbstractController
{
/**
* @param FindDashboards $useCase
* @param FindDashboardsPresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
FindDashboards $useCase,
FindDashboardsPresenter $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/Dashboard/Infrastructure/API/FindMetricsTop/FindMetricsTopController.php | centreon/src/Core/Dashboard/Infrastructure/API/FindMetricsTop/FindMetricsTopController.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\Dashboard\Infrastructure\API\FindMetricsTop;
use Centreon\Application\Controller\AbstractController;
use Core\Dashboard\Application\UseCase\FindMetricsTop\FindMetricsTop;
use Core\Dashboard\Application\UseCase\FindMetricsTop\FindMetricsTopRequest;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\MapQueryString;
final class FindMetricsTopController extends AbstractController
{
/**
* @param FindMetricsTop $useCase
* @param FindMetricsTopPresenter $presenter
* @param FindMetricsTopRequest $request
*
* @return Response
*/
public function __invoke(
FindMetricsTop $useCase,
FindMetricsTopPresenter $presenter,
#[MapQueryString(validationFailedStatusCode: Response::HTTP_UNPROCESSABLE_ENTITY)] FindMetricsTopRequest $request,
): Response {
$this->denyAccessUnlessGrantedForApiRealtime();
$useCase($presenter, $request);
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/Dashboard/Infrastructure/API/FindMetricsTop/FindMetricsTopPresenter.php | centreon/src/Core/Dashboard/Infrastructure/API/FindMetricsTop/FindMetricsTopPresenter.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\Dashboard\Infrastructure\API\FindMetricsTop;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Common\Infrastructure\ExceptionLogger\ExceptionLogger;
use Core\Dashboard\Application\UseCase\FindMetricsTop\FindMetricsTopPresenterInterface;
use Core\Dashboard\Application\UseCase\FindMetricsTop\FindMetricsTopResponse;
use Core\Dashboard\Application\UseCase\FindMetricsTop\Response\MetricInformationDto;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
class FindMetricsTopPresenter extends AbstractPresenter implements FindMetricsTopPresenterInterface
{
public function __construct(protected PresenterFormatterInterface $presenterFormatter)
{
parent::__construct($presenterFormatter);
}
/**
* @param FindMetricsTopResponse|ResponseStatusInterface $response
*/
public function presentResponse(FindMetricsTopResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
if ($response instanceof ErrorResponse && ! is_null($response->getException())) {
ExceptionLogger::create()->log($response->getException());
}
$this->setResponseStatus($response);
return;
}
$this->present(
[
'name' => $response->metricName,
'unit' => $response->metricUnit,
'resources' => self::formatResource($response->resourceMetrics),
]
);
}
/**
* @param MetricInformationDto[] $resourceMetrics
*
* @return array<array<string,int|string|float|null>>
*/
private static function formatResource(array $resourceMetrics): array
{
return array_map(fn (MetricInformationDto $metricInformation) => [
'id' => $metricInformation->serviceId,
'name' => $metricInformation->resourceName,
'parent_name' => (bool) preg_match('/^\_Module\_Meta$/', $metricInformation->parentName)
? '' : $metricInformation->parentName,
'uuid' => 'h' . $metricInformation->parentId . '-s' . $metricInformation->serviceId,
'current_value' => $metricInformation->currentValue,
'warning_high_threshold' => $metricInformation->warningHighThreshold,
'critical_high_threshold' => $metricInformation->criticalHighThreshold,
'warning_low_threshold' => $metricInformation->warningLowThreshold,
'critical_low_threshold' => $metricInformation->criticalLowThreshold,
'min' => $metricInformation->minimumValue,
'max' => $metricInformation->maximumValue,
], $resourceMetrics);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Infrastructure/API/FindSingleMetric/FindSingleMetricController.php | centreon/src/Core/Dashboard/Infrastructure/API/FindSingleMetric/FindSingleMetricController.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\Dashboard\Infrastructure\API\FindSingleMetric;
use Centreon\Application\Controller\AbstractController;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Dashboard\Application\UseCase\FindSingleMetric\FindSingleMetric;
use Core\Dashboard\Application\UseCase\FindSingleMetric\FindSingleMetricRequest;
use Core\Security\Infrastructure\Voters\ApiRealtimeVoter;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[Route(
path: '/monitoring/hosts/{hostId}/services/{serviceId}/metrics/{metricName}',
name: 'FindSingleMetric',
methods: ['GET'],
requirements: [
'hostId' => '\d+',
'serviceId' => '\d+',
'metricName' => '.+',
],
condition: "request.attributes.get('version') >= 25.07"
)]
#[IsGranted(
ApiRealtimeVoter::ROLE_API_REALTIME,
null,
'You are not allowed to retrieve metrics in real-time',
Response::HTTP_FORBIDDEN
)]
final class FindSingleMetricController extends AbstractController
{
/**
* @param int $hostId
* @param int $serviceId
* @param string $metricName
* @param FindSingleMetric $useCase
* @param FindSingleMetricPresenter $presenter
*
* @return Response
*/
public function __invoke(
int $hostId,
int $serviceId,
string $metricName,
FindSingleMetric $useCase,
FindSingleMetricPresenter $presenter,
): Response {
try {
$request = new FindSingleMetricRequest(
hostId: $hostId,
serviceId: $serviceId,
metricName: $metricName
);
} catch (\InvalidArgumentException $e) {
$presenter->presentResponse(new InvalidArgumentResponse(
'Invalid parameters provided : ' . $e->getMessage(),
[
'host_id' => $hostId,
'service_id' => $serviceId,
'metric_name' => $metricName,
]
));
return $presenter->show();
}
$useCase($request, $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/Dashboard/Infrastructure/API/FindSingleMetric/FindSingleMetricPresenter.php | centreon/src/Core/Dashboard/Infrastructure/API/FindSingleMetric/FindSingleMetricPresenter.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\Dashboard\Infrastructure\API\FindSingleMetric;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Common\Infrastructure\ExceptionLogger\ExceptionLogger;
use Core\Dashboard\Application\UseCase\FindSingleMetric\FindSingleMetricPresenterInterface;
use Core\Dashboard\Application\UseCase\FindSingleMetric\FindSingleMetricResponse;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
final class FindSingleMetricPresenter extends AbstractPresenter implements FindSingleMetricPresenterInterface
{
public function __construct(
protected PresenterFormatterInterface $presenterFormatter,
private readonly ExceptionLogger $exceptionLogger,
) {
parent::__construct($presenterFormatter);
}
public function presentResponse(FindSingleMetricResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
if (($response instanceof ErrorResponse) && ! is_null($response->getException())) {
$this->exceptionLogger->log($response->getException());
}
$this->setResponseStatus($response);
return;
}
$this->present([
'metrics' => [
[
'metric_id' => $response->id,
'name' => $response->name,
'unit' => $response->unit,
'current_value' => $response->currentValue,
'warning_high_threshold' => $response->warningHighThreshold,
'warning_low_threshold' => $response->warningLowThreshold,
'critical_high_threshold' => $response->criticalHighThreshold,
'critical_low_threshold' => $response->criticalLowThreshold,
],
],
]);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Infrastructure/API/FindSingleMetaMetric/FindSingleMetaMetricController.php | centreon/src/Core/Dashboard/Infrastructure/API/FindSingleMetaMetric/FindSingleMetaMetricController.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\Dashboard\Infrastructure\API\FindSingleMetaMetric;
use Centreon\Application\Controller\AbstractController;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Dashboard\Application\UseCase\FindSingleMetaMetric\FindSingleMetaMetric;
use Core\Dashboard\Application\UseCase\FindSingleMetaMetric\FindSingleMetaMetricRequest;
use Core\Security\Infrastructure\Voters\ApiRealtimeVoter;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[Route(
path: '/monitoring/metaservice/{metaServiceId}/metrics/{metricName}',
name: 'FindSingleMetaMetric',
methods: ['GET'],
requirements: [
'metaServiceId' => '\d+',
'metricName' => '.+',
],
condition: "request.attributes.get('version') >= 25.07"
)]
#[IsGranted(
ApiRealtimeVoter::ROLE_API_REALTIME,
null,
'You are not allowed to retrieve metrics in real-time',
Response::HTTP_FORBIDDEN
)]
final class FindSingleMetaMetricController extends AbstractController
{
/**
* @param int $metaServiceId
* @param string $metricName
* @param FindSingleMetaMetric $useCase
* @param FindSingleMetaMetricPresenter $presenter
*
* @return Response
*/
public function __invoke(
int $metaServiceId,
string $metricName,
FindSingleMetaMetric $useCase,
FindSingleMetaMetricPresenter $presenter,
): Response {
try {
$request = new FindSingleMetaMetricRequest(
metaServiceId: $metaServiceId,
metricName: $metricName
);
} catch (\InvalidArgumentException $e) {
$presenter->presentResponse(new InvalidArgumentResponse(
'Invalid parameters provided : ' . $e->getMessage(),
[
'metaServiceId' => $metaServiceId,
'metricName' => $metricName,
]
));
return $presenter->show();
}
$useCase($request, $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/Dashboard/Infrastructure/API/FindSingleMetaMetric/FindSingleMetaMetricPresenter.php | centreon/src/Core/Dashboard/Infrastructure/API/FindSingleMetaMetric/FindSingleMetaMetricPresenter.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\Dashboard\Infrastructure\API\FindSingleMetaMetric;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Common\Infrastructure\ExceptionLogger\ExceptionLogger;
use Core\Dashboard\Application\UseCase\FindSingleMetaMetric\FindSingleMetaMetricPresenterInterface;
use Core\Dashboard\Application\UseCase\FindSingleMetaMetric\FindSingleMetaMetricResponse;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
final class FindSingleMetaMetricPresenter extends AbstractPresenter implements FindSingleMetaMetricPresenterInterface
{
public function __construct(
protected PresenterFormatterInterface $presenterFormatter,
private readonly ExceptionLogger $exceptionLogger,
) {
parent::__construct($presenterFormatter);
}
public function presentResponse(FindSingleMetaMetricResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
if (($response instanceof ErrorResponse) && ! is_null($response->getException())) {
$this->exceptionLogger->log($response->getException());
}
$this->setResponseStatus($response);
return;
}
$this->present([
'metrics' => [
[
'metric_id' => $response->id,
'name' => $response->name,
'unit' => $response->unit,
'current_value' => $response->currentValue,
'warning_high_threshold' => $response->warningHighThreshold,
'warning_low_threshold' => $response->warningLowThreshold,
'critical_high_threshold' => $response->criticalHighThreshold,
'critical_low_threshold' => $response->criticalLowThreshold,
],
],
]);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Infrastructure/API/AddDashboard/AddDashboardPresenter.php | centreon/src/Core/Dashboard/Infrastructure/API/AddDashboard/AddDashboardPresenter.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\Dashboard\Infrastructure\API\AddDashboard;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\CreatedResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Dashboard\Application\UseCase\AddDashboard\AddDashboardPresenterInterface;
use Core\Dashboard\Application\UseCase\AddDashboard\AddDashboardResponse;
use Core\Dashboard\Domain\Model\Refresh\RefreshType;
use Core\Dashboard\Infrastructure\Model\DashboardSharingRoleConverter;
use Core\Dashboard\Infrastructure\Model\RefreshTypeConverter;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Api\Router;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Infrastructure\Common\Presenter\PresenterTrait;
final class AddDashboardPresenter extends DefaultPresenter implements AddDashboardPresenterInterface
{
use PresenterTrait;
use LoggerTrait;
private const ROUTE_NAME = 'FindDashboard';
private const ROUTE_DASHBOARD_ID = 'dashboardId';
/**
* @param PresenterFormatterInterface $presenterFormatter
* @param Router $router
*/
public function __construct(
PresenterFormatterInterface $presenterFormatter,
readonly private Router $router,
) {
$this->presenterFormatter = $presenterFormatter;
parent::__construct($presenterFormatter);
}
public function presentResponse(AddDashboardResponse|ResponseStatusInterface $data): void
{
if ($data instanceof AddDashboardResponse) {
$this->present(
new CreatedResponse(
$data->id,
[
'id' => $data->id,
'name' => $data->name,
'description' => $data->description,
'created_by' => $data->createdBy,
'updated_by' => $data->updatedBy,
'created_at' => $this->formatDateToIso8601($data->createdAt),
'updated_at' => $this->formatDateToIso8601($data->updatedAt),
'own_role' => DashboardSharingRoleConverter::toString($data->ownRole),
'panels' => $data->panels,
'refresh' => $this->formatRefresh($data->refresh),
]
)
);
try {
$this->setResponseHeaders([
'Location' => $this->router->generate(self::ROUTE_NAME, [self::ROUTE_DASHBOARD_ID => $data->id]),
]);
} catch (\Throwable $ex) {
$this->error('Impossible to generate the location header', [
'message' => $ex->getMessage(),
'trace' => $ex->getTraceAsString(),
'route' => self::ROUTE_NAME,
'payload' => $data,
]);
}
} else {
$this->setResponseStatus($data);
}
}
/**
* @param array{type: RefreshType, interval: null|int} $refresh
*
* @return array{type: string, interval: null|int}
*/
private function formatRefresh(array $refresh): array
{
return [
'type' => RefreshTypeConverter::toString($refresh['type']),
'interval' => $refresh['interval'],
];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Infrastructure/API/AddDashboard/AddDashboardController.php | centreon/src/Core/Dashboard/Infrastructure/API/AddDashboard/AddDashboardController.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\Dashboard\Infrastructure\API\AddDashboard;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Dashboard\Application\UseCase\AddDashboard\AddDashboard;
use Core\Dashboard\Application\UseCase\AddDashboard\AddDashboardRequest;
use Core\Dashboard\Application\UseCase\AddDashboard\LayoutRequest;
use Core\Dashboard\Application\UseCase\AddDashboard\PanelRequest;
use Core\Dashboard\Infrastructure\Model\RefreshTypeConverter;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class AddDashboardController extends AbstractController
{
use LoggerTrait;
/**
* @param Request $request
* @param AddDashboard $useCase
* @param AddDashboardPresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
Request $request,
AddDashboard $useCase,
AddDashboardPresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
try {
$addDashboardRequest = $this->createAddDashboardRequest($request);
$useCase($addDashboardRequest, $presenter);
} 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($ex));
}
return $presenter->show();
}
private function createAddDashboardRequest(Request $request): AddDashboardRequest
{
/** @var array{
* name: string,
* description: ?string,
* panels: array<array{
* name: string,
* layout: array{
* x: int,
* y: int,
* width: int,
* height: int,
* min_width: int,
* min_height: int
* },
* widget_type: string,
* widget_settings: array<mixed>,
* }>,
* refresh: array{
* type: string,
* interval: int|null
* }
* } $dataSent
*/
$dataSent = $this->validateAndRetrieveDataSent($request, __DIR__ . '/AddDashboardSchema.json');
$addDashboardRequest = new AddDashboardRequest();
$addDashboardRequest->name = $dataSent['name'];
$addDashboardRequest->description = $dataSent['description'];
$addDashboardRequest->panels = [];
foreach ($dataSent['panels'] as $panelArray) {
$layout = new LayoutRequest();
$layout->xAxis = $panelArray['layout']['x'];
$layout->yAxis = $panelArray['layout']['y'];
$layout->width = $panelArray['layout']['width'];
$layout->height = $panelArray['layout']['height'];
$layout->minWidth = $panelArray['layout']['min_width'];
$layout->minHeight = $panelArray['layout']['min_height'];
$addDashboardRequestPanel = new PanelRequest($layout);
$addDashboardRequestPanel->name = $panelArray['name'];
$addDashboardRequestPanel->widgetType = $panelArray['widget_type'];
$addDashboardRequestPanel->widgetSettings = $panelArray['widget_settings'];
$addDashboardRequest->panels[] = $addDashboardRequestPanel;
}
$addDashboardRequest->refresh = [
'type' => RefreshTypeConverter::fromString($dataSent['refresh']['type']),
'interval' => $dataSent['refresh']['interval'],
];
return $addDashboardRequest;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Infrastructure/API/FindPerformanceMetricsData/FindPerformanceMetricsDataController.php | centreon/src/Core/Dashboard/Infrastructure/API/FindPerformanceMetricsData/FindPerformanceMetricsDataController.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\Dashboard\Infrastructure\API\FindPerformanceMetricsData;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Dashboard\Application\UseCase\FindPerformanceMetricsData\FindPerformanceMetricsData;
use Core\Dashboard\Application\UseCase\FindPerformanceMetricsData\FindPerformanceMetricsDataRequest;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\MapQueryString;
final class FindPerformanceMetricsDataController extends AbstractController
{
use LoggerTrait;
public function __invoke(
FindPerformanceMetricsData $useCase,
FindPerformanceMetricsDataPresenter $presenter,
#[MapQueryString(validationFailedStatusCode: Response::HTTP_UNPROCESSABLE_ENTITY)] FindPerformanceMetricsDataRequest $request,
): Response {
$this->denyAccessUnlessGrantedForApiRealtime();
$useCase($presenter, $request->toDto());
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/Dashboard/Infrastructure/API/FindPerformanceMetricsData/FindPerformanceMetricsDataPresenter.php | centreon/src/Core/Dashboard/Infrastructure/API/FindPerformanceMetricsData/FindPerformanceMetricsDataPresenter.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\Dashboard\Infrastructure\API\FindPerformanceMetricsData;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Dashboard\Application\UseCase\FindPerformanceMetricsData\FindPerformanceMetricsDataPresenterInterface;
use Core\Dashboard\Application\UseCase\FindPerformanceMetricsData\FindPerformanceMetricsDataResponse;
use Core\Infrastructure\Common\Presenter\JsonFormatter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Infrastructure\Common\Presenter\PresenterTrait;
use Core\Metric\Domain\Model\MetricInformation\MetricInformation;
use Symfony\Component\HttpFoundation\JsonResponse;
use function array_map;
class FindPerformanceMetricsDataPresenter extends AbstractPresenter implements FindPerformanceMetricsDataPresenterInterface
{
use PresenterTrait;
public function __construct(
protected PresenterFormatterInterface $presenterFormatter,
) {
parent::__construct($presenterFormatter);
if ($presenterFormatter instanceof JsonFormatter) {
$presenterFormatter->setEncodingOptions(JsonResponse::DEFAULT_ENCODING_OPTIONS | JSON_PRESERVE_ZERO_FRACTION);
}
}
public function presentResponse(FindPerformanceMetricsDataResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
$this->present([
'base' => $response->base,
'metrics' => array_map($this->formatMetricInformation(...), $response->metricsInformation),
'times' => array_map(fn ($date) => $this->formatDateToIso8601($date), $response->times),
]);
}
}
/**
* Format Metric information to array.
*
* @param MetricInformation $metricInformation
*
* @return array{
* metric_id: int,
* metric: string,
* metric_legend: string,
* unit: string,
* min: float|null,
* max: float|null,
* ds_data: array{
* ds_color_line: string,
* ds_color_area: string|null,
* ds_filled: bool,
* ds_invert: bool,
* ds_legend: string|null,
* ds_stack: bool,
* ds_order: int|null,
* ds_transparency: float|null,
* ds_color_line_mode: int
* },
* legend: string,
* stack: int<0,1>,
* warning_high_threshold: float|null,
* critical_high_threshold: float|null,
* warning_low_threshold: float|null,
* critical_low_threshold: float|null,
* ds_order: int,
* data: array<float|null>,
* last_value: float|null,
* minimum_value: float|null,
* maximum_value: float|null,
* average_value: float|null,
* }
*/
private function formatMetricInformation(MetricInformation $metricInformation): array
{
$generalInformation = $metricInformation->getGeneralInformation();
$dataSource = $metricInformation->getDataSource();
$thresholdInformation = $metricInformation->getThresholdInformation();
$realTimeDataInformation = $metricInformation->getRealTimeDataInformation();
return [
'metric_id' => $generalInformation->getId(),
'metric' => $generalInformation->getName(),
'metric_legend' => $generalInformation->getAlias(),
'host_name' => $generalInformation->getHostName(),
'service_name' => $generalInformation->getServiceName(),
'unit' => $generalInformation->getUnit(),
'min' => $realTimeDataInformation->getMinimumValueLimit(),
'max' => $realTimeDataInformation->getMaximumValueLimit(),
'ds_data' => [
'ds_color_line' => $dataSource->getLineColor(),
'ds_color_area' => $dataSource->getColorArea(),
'ds_filled' => $dataSource->isFilled(),
'ds_invert' => $dataSource->isInverted(),
'ds_legend' => $dataSource->getLegend(),
'ds_stack' => $dataSource->isStacked(),
'ds_order' => $dataSource->getOrder(),
'ds_transparency' => $dataSource->getTransparency(),
'ds_color_line_mode' => $dataSource->getColorMode(),
],
'legend' => $generalInformation->getLegend(),
'stack' => (int) $generalInformation->isStacked(),
'warning_high_threshold' => $thresholdInformation->getWarningThreshold(),
'critical_high_threshold' => $thresholdInformation->getCriticalThreshold(),
'warning_low_threshold' => $thresholdInformation->getWarningLowThreshold(),
'critical_low_threshold' => $thresholdInformation->getCriticalLowThreshold(),
'ds_order' => $generalInformation->getStackingOrder(),
'data' => $realTimeDataInformation->getValues(),
'last_value' => $realTimeDataInformation->getLastValue(),
'minimum_value' => $realTimeDataInformation->getMinimumValue(),
'maximum_value' => $realTimeDataInformation->getMaximumValue(),
'average_value' => $realTimeDataInformation->getAverageValue(),
];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Infrastructure/API/FindFavoriteDashboards/FindFavoriteDashboardsController.php | centreon/src/Core/Dashboard/Infrastructure/API/FindFavoriteDashboards/FindFavoriteDashboardsController.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\Dashboard\Infrastructure\API\FindFavoriteDashboards;
use Centreon\Application\Controller\AbstractController;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Dashboard\Application\UseCase\FindFavoriteDashboards\FindFavoriteDashboards;
use Core\Infrastructure\Common\Api\StandardPresenter;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted(
'dashboard_access',
null,
'You do not have sufficient rights to list the dashboards'
)]
final class FindFavoriteDashboardsController extends AbstractController
{
public function __invoke(
FindFavoriteDashboards $useCase,
StandardPresenter $presenter,
): Response {
$response = $useCase();
if ($response instanceof ResponseStatusInterface) {
return $this->createResponse($response);
}
return JsonResponse::fromJsonString(
$presenter->present($response, ['groups' => ['FavoriteDashboards:Read']])
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Infrastructure/API/FindDashboardContactGroups/FindDashboardContactGroupsController.php | centreon/src/Core/Dashboard/Infrastructure/API/FindDashboardContactGroups/FindDashboardContactGroupsController.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\Dashboard\Infrastructure\API\FindDashboardContactGroups;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Dashboard\Application\UseCase\FindDashboardContactGroups\FindDashboardContactGroups;
use Core\Infrastructure\Common\Api\StandardPresenter;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted(
'dashboard_access_editor',
null,
'You do not have sufficient rights to list contacts allowed to access dashboards'
)]
final class FindDashboardContactGroupsController extends AbstractController
{
use LoggerTrait;
/**
* @param FindDashboardContactGroups $useCase
* @param StandardPresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
FindDashboardContactGroups $useCase,
StandardPresenter $presenter,
): Response {
$response = $useCase();
if ($response instanceof ResponseStatusInterface) {
return $this->createResponse($response);
}
return JsonResponse::fromJsonString(
$presenter->present($response, ['groups' => ['FindDashboardContactGroups:Read']])
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Infrastructure/API/AddDashboardThumbnail/AddDashboardThumbnailPresenter.php | centreon/src/Core/Dashboard/Infrastructure/API/AddDashboardThumbnail/AddDashboardThumbnailPresenter.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\Dashboard\Infrastructure\API\AddDashboardThumbnail;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Dashboard\Application\UseCase\AddDashboardThumbnail\AddDashboardThumbnailPresenterInterface;
final class AddDashboardThumbnailPresenter extends AbstractPresenter implements AddDashboardThumbnailPresenterInterface
{
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/Dashboard/Infrastructure/API/FindPerformanceMetrics/FindPerformanceMetricsController.php | centreon/src/Core/Dashboard/Infrastructure/API/FindPerformanceMetrics/FindPerformanceMetricsController.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\Dashboard\Infrastructure\API\FindPerformanceMetrics;
use Centreon\Application\Controller\AbstractController;
use Core\Dashboard\Application\UseCase\FindPerformanceMetrics\FindPerformanceMetrics;
use Symfony\Component\HttpFoundation\Response;
final class FindPerformanceMetricsController extends AbstractController
{
public function __invoke(FindPerformanceMetrics $useCase, FindPerformanceMetricsPresenter $presenter): Response
{
$this->denyAccessUnlessGrantedForApiRealtime();
$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/Dashboard/Infrastructure/API/FindPerformanceMetrics/FindPerformanceMetricsPresenter.php | centreon/src/Core/Dashboard/Infrastructure/API/FindPerformanceMetrics/FindPerformanceMetricsPresenter.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\Dashboard\Infrastructure\API\FindPerformanceMetrics;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Common\Infrastructure\ExceptionLogger\ExceptionLogger;
use Core\Dashboard\Application\UseCase\FindPerformanceMetrics\FindPerformanceMetricsPresenterInterface;
use Core\Dashboard\Application\UseCase\FindPerformanceMetrics\FindPerformanceMetricsResponse;
use Core\Dashboard\Application\UseCase\FindPerformanceMetrics\ResourceMetricDto;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
class FindPerformanceMetricsPresenter extends AbstractPresenter implements FindPerformanceMetricsPresenterInterface
{
public function __construct(
private RequestParametersInterface $requestParameters,
protected PresenterFormatterInterface $presenterFormatter,
) {
parent::__construct($presenterFormatter);
}
public function presentResponse(FindPerformanceMetricsResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
if ($response instanceof ErrorResponse && ! is_null($response->getException())) {
ExceptionLogger::create()->log($response->getException());
}
$this->setResponseStatus($response);
return;
}
$this->present([
'result' => array_map(fn (ResourceMetricDto $resourceMetric) => [
'id' => $resourceMetric->serviceId,
'name' => $resourceMetric->resourceName,
'parent_name' => $resourceMetric->parentName,
'uuid' => 'h' . $resourceMetric->parentId . '-s' . $resourceMetric->serviceId,
'metrics' => $resourceMetric->metrics,
], $response->resourceMetrics),
'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/Dashboard/Infrastructure/API/FindDashboardContacts/FindDashboardContactsController.php | centreon/src/Core/Dashboard/Infrastructure/API/FindDashboardContacts/FindDashboardContactsController.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\Dashboard\Infrastructure\API\FindDashboardContacts;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Dashboard\Application\UseCase\FindDashboardContacts\FindDashboardContacts;
use Core\Infrastructure\Common\Api\StandardPresenter;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Attribute\IsGranted;
use Symfony\Component\Serializer\Exception\ExceptionInterface;
#[IsGranted(
'dashboard_access_editor',
null,
'You do not have sufficient rights to list the dashboard contacts'
)]
final class FindDashboardContactsController extends AbstractController
{
use LoggerTrait;
/**
* @param FindDashboardContacts $useCase
* @param StandardPresenter $presenter
* @throws ExceptionInterface
* @return Response
*/
public function __invoke(
FindDashboardContacts $useCase,
StandardPresenter $presenter,
): Response {
$response = $useCase();
if ($response instanceof ResponseStatusInterface) {
return $this->createResponse($response);
}
return JsonResponse::fromJsonString(
$presenter->present($response, ['groups' => ['FindDashboardContacts:Read']])
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Infrastructure/API/DeleteContactDashboardShare/DeleteContactDashboardSharePresenter.php | centreon/src/Core/Dashboard/Infrastructure/API/DeleteContactDashboardShare/DeleteContactDashboardSharePresenter.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\Dashboard\Infrastructure\API\DeleteContactDashboardShare;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Dashboard\Application\UseCase\DeleteContactDashboardShare\DeleteContactDashboardSharePresenterInterface;
final class DeleteContactDashboardSharePresenter extends AbstractPresenter implements DeleteContactDashboardSharePresenterInterface
{
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/Dashboard/Infrastructure/API/DeleteContactDashboardShare/DeleteContactDashboardShareController.php | centreon/src/Core/Dashboard/Infrastructure/API/DeleteContactDashboardShare/DeleteContactDashboardShareController.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\Dashboard\Infrastructure\API\DeleteContactDashboardShare;
use Centreon\Application\Controller\AbstractController;
use Core\Dashboard\Application\UseCase\DeleteContactDashboardShare\DeleteContactDashboardShare;
use Core\Dashboard\Application\UseCase\DeleteContactDashboardShare\DeleteContactDashboardSharePresenterInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class DeleteContactDashboardShareController extends AbstractController
{
/**
* @param int $dashboardId
* @param int $contactId
* @param DeleteContactDashboardShare $useCase
* @param DeleteContactDashboardSharePresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
int $dashboardId,
int $contactId,
DeleteContactDashboardShare $useCase,
DeleteContactDashboardSharePresenterInterface $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($dashboardId, $contactId, $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/Dashboard/Infrastructure/API/AddDashboardToFavorites/AddDashboardToFavoritesInput.php | centreon/src/Core/Dashboard/Infrastructure/API/AddDashboardToFavorites/AddDashboardToFavoritesInput.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\Dashboard\Infrastructure\API\AddDashboardToFavorites;
use Symfony\Component\Validator\Constraints as Assert;
final class AddDashboardToFavoritesInput
{
/**
* @param int $dashboardId
*/
public function __construct(
#[Assert\NotNull]
#[Assert\Type('integer')]
public readonly mixed $dashboardId,
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Infrastructure/API/AddDashboardToFavorites/AddDashboardToFavoritesRequestTransformer.php | centreon/src/Core/Dashboard/Infrastructure/API/AddDashboardToFavorites/AddDashboardToFavoritesRequestTransformer.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\Dashboard\Infrastructure\API\AddDashboardToFavorites;
use Core\Dashboard\Application\UseCase\AddDashboardToFavorites\AddDashboardToFavoritesRequest;
abstract readonly class AddDashboardToFavoritesRequestTransformer
{
/**
* @param AddDashboardToFavoritesInput $input
* @return AddDashboardToFavoritesRequest
*/
public static function transform(AddDashboardToFavoritesInput $input): AddDashboardToFavoritesRequest
{
return new AddDashboardToFavoritesRequest(dashboardId: (int) $input->dashboardId);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Infrastructure/API/AddDashboardToFavorites/AddDashboardToFavoritesController.php | centreon/src/Core/Dashboard/Infrastructure/API/AddDashboardToFavorites/AddDashboardToFavoritesController.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\Dashboard\Infrastructure\API\AddDashboardToFavorites;
use Centreon\Application\Controller\AbstractController;
use Core\Dashboard\Application\UseCase\AddDashboardToFavorites\AddDashboardToFavorites;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\MapRequestPayload;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted(
'dashboard_access',
null,
'You do not have sufficient rights to add the dashboard as favorite'
)]
final class AddDashboardToFavoritesController extends AbstractController
{
/**
* @param AddDashboardToFavorites $useCase
* @param AddDashboardToFavoritesInput $input
* @return Response
*/
public function __invoke(
AddDashboardToFavorites $useCase,
#[MapRequestPayload] AddDashboardToFavoritesInput $input,
): Response {
return $this->createResponse(
$useCase(
AddDashboardToFavoritesRequestTransformer::transform($input),
)
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Infrastructure/API/DeleteContactGroupDashboardShare/DeleteContactGroupDashboardSharePresenter.php | centreon/src/Core/Dashboard/Infrastructure/API/DeleteContactGroupDashboardShare/DeleteContactGroupDashboardSharePresenter.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\Dashboard\Infrastructure\API\DeleteContactGroupDashboardShare;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Dashboard\Application\UseCase\DeleteContactGroupDashboardShare\DeleteContactGroupDashboardSharePresenterInterface;
final class DeleteContactGroupDashboardSharePresenter extends AbstractPresenter implements DeleteContactGroupDashboardSharePresenterInterface
{
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/Dashboard/Infrastructure/API/DeleteContactGroupDashboardShare/DeleteContactGroupDashboardShareController.php | centreon/src/Core/Dashboard/Infrastructure/API/DeleteContactGroupDashboardShare/DeleteContactGroupDashboardShareController.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\Dashboard\Infrastructure\API\DeleteContactGroupDashboardShare;
use Centreon\Application\Controller\AbstractController;
use Core\Dashboard\Application\UseCase\DeleteContactGroupDashboardShare\DeleteContactGroupDashboardShare;
use Core\Dashboard\Application\UseCase\DeleteContactGroupDashboardShare\DeleteContactGroupDashboardSharePresenterInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class DeleteContactGroupDashboardShareController extends AbstractController
{
/**
* @param int $dashboardId
* @param int $contactGroupId
* @param DeleteContactGroupDashboardShare $useCase
* @param DeleteContactGroupDashboardSharePresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
int $dashboardId,
int $contactGroupId,
DeleteContactGroupDashboardShare $useCase,
DeleteContactGroupDashboardSharePresenterInterface $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($dashboardId, $contactGroupId, $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/Dashboard/Infrastructure/API/PartialUpdateDashboard/PartialUpdateDashboardInput.php | centreon/src/Core/Dashboard/Infrastructure/API/PartialUpdateDashboard/PartialUpdateDashboardInput.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\Dashboard\Infrastructure\API\PartialUpdateDashboard;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
use Symfony\Component\Validator\Exception\InvalidArgumentException;
use Symfony\Component\Validator\Exception\InvalidOptionsException;
use Symfony\Component\Validator\Exception\LogicException;
use Symfony\Component\Validator\Exception\MissingOptionsException;
final readonly class PartialUpdateDashboardInput
{
/**
* @param string|null $name
* @param string|null $description
* @param array{type: string, interval: int} $refresh
* @param array{id?: int, name: string, directory: string} $thumbnail
* @param array<array{
* id?: ?int,
* name: string,
* layout: array{
* x: int,
* y: int,
* width: int,
* height: int,
* min_width: int,
* min_height: int
* },
* widget_type: string,
* widget_settings: string,
*}> $panels
*
* @throws ConstraintDefinitionException
* @throws InvalidArgumentException
* @throws InvalidOptionsException
* @throws LogicException
* @throws MissingOptionsException
*/
public function __construct(
#[Assert\Type('string')]
#[Assert\Length(min: 1, max: 200)]
public mixed $name = null,
#[Assert\Type('string')]
public mixed $description = null,
#[Assert\Collection(
fields: [
'type' => [
new Assert\NotNull(),
new Assert\Type('string'),
new Assert\Choice(['global', 'manual']),
],
'interval' => new Assert\Optional([
new Assert\Type('numeric'),
new Assert\Positive(),
]),
]
)]
public mixed $refresh = null,
#[Assert\Collection(
fields: [
'id' => new Assert\Optional([
new Assert\Type('numeric'),
new Assert\Positive(),
]),
'name' => [
new Assert\NotNull(),
new Assert\Type('string'),
new Assert\Length(min: 1, max: 255),
],
'directory' => [
new Assert\NotNull(),
new Assert\Type('string'),
new Assert\Length(min: 1, max: 255),
],
],
)]
public mixed $thumbnail = null,
#[Assert\AtLeastOneOf([
new Assert\Count(max: 1),
new Assert\Sequentially([
new Assert\Type('array'),
new Assert\All(
new Assert\Collection(
fields: [
'id' => new Assert\Optional([
new Assert\When(
expression: 'value !== "null"',
constraints: [new Assert\Type('numeric'), new Assert\Positive()]
),
]),
'name' => [
new Assert\NotNull(),
new Assert\Type('string'),
],
'layout' => new Assert\Collection(
fields: [
'x' => [
new Assert\NotNull(),
new Assert\Type('numeric'),
],
'y' => [
new Assert\NotNull(),
new Assert\Type('numeric'),
],
'width' => [
new Assert\NotNull(),
new Assert\Type('numeric'),
],
'height' => [
new Assert\NotNull(),
new Assert\Type('numeric'),
],
'min_width' => [
new Assert\NotNull(),
new Assert\Type('numeric'),
],
'min_height' => [
new Assert\NotNull(),
new Assert\Type('numeric'),
],
]
),
'widget_type' => [
new Assert\NotNull(),
new Assert\Type('string'),
],
'widget_settings' => [
new Assert\NotNull(),
new Assert\Type('string'),
new Assert\Json(),
],
]
)
),
]),
])]
public mixed $panels = 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/Dashboard/Infrastructure/API/PartialUpdateDashboard/PartialUpdateDashboardController.php | centreon/src/Core/Dashboard/Infrastructure/API/PartialUpdateDashboard/PartialUpdateDashboardController.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\Dashboard\Infrastructure\API\PartialUpdateDashboard;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Common\Application\Type\NoValue;
use Core\Dashboard\Application\UseCase\PartialUpdateDashboard\PartialUpdateDashboard;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\MapRequestPayload;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\ConstraintViolationInterface;
use Symfony\Component\Validator\Exception\ValidationFailedException;
use Symfony\Component\Validator\Validator\ValidatorInterface;
final class PartialUpdateDashboardController extends AbstractController
{
use LoggerTrait;
public function __construct(private readonly ValidatorInterface $validator)
{
}
/**
* @param int $dashboardId
* @param Request $request
* @param PartialUpdateDashboardInput $mappedRequest
* @param PartialUpdateDashboard $useCase
* @param PartialUpdateDashboardPresenter $presenter
*
* @throws AccessDeniedException
* @return Response
*/
public function __invoke(
int $dashboardId,
Request $request,
#[MapRequestPayload] PartialUpdateDashboardInput $mappedRequest,
PartialUpdateDashboard $useCase,
PartialUpdateDashboardPresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
try {
$partialUpdateDashboardRequest = PartialUpdateDashboardRequestTransformer::transform($mappedRequest);
if (! $partialUpdateDashboardRequest->thumbnail instanceof NoValue) {
/** @var UploadedFile|null $thumbnail */
$thumbnail = $request->files->get('thumbnail_data', null);
$partialUpdateDashboardRequest->thumbnail->content = $this->validateAndRetrieveThumbnailContent(
$thumbnail,
);
}
$useCase($dashboardId, $partialUpdateDashboardRequest, $presenter);
} catch (\InvalidArgumentException $exception) {
$this->error($exception->getMessage(), ['trace' => $exception->getTraceAsString()]);
$presenter->setResponseStatus(new InvalidArgumentResponse($exception));
} catch (\Throwable $exception) {
$this->error($exception->getMessage(), ['trace' => $exception->getTraceAsString()]);
$presenter->setResponseStatus(new ErrorResponse($exception));
}
return $presenter->show();
}
/**
* @param null|UploadedFile $thumbnail
* @throws HttpException
* @throws FileException
* @return string
*/
private function validateAndRetrieveThumbnailContent(?UploadedFile $thumbnail): string
{
// Dashboard use case we do only allow png files.
$errors = $this->validator->validate(
$thumbnail,
[
new Assert\NotBlank(),
new Assert\Image([
'mimeTypes' => ['image/png'],
]),
]
);
if (count($errors) > 0) {
throw new HttpException(
Response::HTTP_UNPROCESSABLE_ENTITY,
implode(
"\n",
array_map(
static fn (ConstraintViolationInterface $exception) => $exception->getMessage(),
iterator_to_array($errors),
),
),
new ValidationFailedException($thumbnail, $errors),
);
}
// at this point we are sure that $thumbnail is not null
/**
* @var UploadedFile $thumbnail
*/
return $thumbnail->getContent();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Infrastructure/API/PartialUpdateDashboard/PartialUpdateDashboardPresenter.php | centreon/src/Core/Dashboard/Infrastructure/API/PartialUpdateDashboard/PartialUpdateDashboardPresenter.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\Dashboard\Infrastructure\API\PartialUpdateDashboard;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Dashboard\Application\UseCase\PartialUpdateDashboard\PartialUpdateDashboardPresenterInterface;
use Core\Infrastructure\Common\Api\DefaultPresenter;
final class PartialUpdateDashboardPresenter extends DefaultPresenter implements PartialUpdateDashboardPresenterInterface
{
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/Dashboard/Infrastructure/API/PartialUpdateDashboard/PartialUpdateDashboardRequestTransformer.php | centreon/src/Core/Dashboard/Infrastructure/API/PartialUpdateDashboard/PartialUpdateDashboardRequestTransformer.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\Dashboard\Infrastructure\API\PartialUpdateDashboard;
use Core\Common\Application\Type\NoValue;
use Core\Dashboard\Application\UseCase\PartialUpdateDashboard\PartialUpdateDashboardRequest;
use Core\Dashboard\Application\UseCase\PartialUpdateDashboard\Request\PanelLayoutRequestDto;
use Core\Dashboard\Application\UseCase\PartialUpdateDashboard\Request\PanelRequestDto;
use Core\Dashboard\Application\UseCase\PartialUpdateDashboard\Request\RefreshRequestDto;
use Core\Dashboard\Application\UseCase\PartialUpdateDashboard\Request\ThumbnailRequestDto;
use Core\Dashboard\Infrastructure\Model\RefreshTypeConverter;
use InvalidArgumentException;
/**
* Class
*
* @class PartialUpdateDashboardTransformer
* @package Core\Dashboard\Infrastructure\API\PartialUpdateDashboard
*/
abstract readonly class PartialUpdateDashboardRequestTransformer
{
/**
* @param PartialUpdateDashboardInput $dashboardInputValidator
*
* @throws InvalidArgumentException
* @return PartialUpdateDashboardRequest
*/
public static function transform(
PartialUpdateDashboardInput $dashboardInputValidator,
): PartialUpdateDashboardRequest {
$name = empty($dashboardInputValidator->name) ? new NoValue() : $dashboardInputValidator->name;
$description = $dashboardInputValidator->description ?? new NoValue(
);
return new PartialUpdateDashboardRequest(
name: $name,
description: $description,
panels: self::createPanelDto($dashboardInputValidator),
refresh: self::createRefreshDto($dashboardInputValidator),
thumbnail: self::createThumbnailDto($dashboardInputValidator)
);
}
/**
* @param PartialUpdateDashboardInput $dashboardInputValidator
*
* @return ThumbnailRequestDto|NoValue
*/
private static function createThumbnailDto(
PartialUpdateDashboardInput $dashboardInputValidator,
): ThumbnailRequestDto|NoValue {
if ($dashboardInputValidator->thumbnail === null) {
return new NoValue();
}
return new ThumbnailRequestDto(
id: isset($dashboardInputValidator->thumbnail['id'])
? (int) $dashboardInputValidator->thumbnail['id'] : null,
directory: $dashboardInputValidator->thumbnail['directory'],
name: $dashboardInputValidator->thumbnail['name']
);
}
/**
* @param PartialUpdateDashboardInput $dashboardInputValidator
*
* @throws InvalidArgumentException
* @return RefreshRequestDto|NoValue
*/
private static function createRefreshDto(
PartialUpdateDashboardInput $dashboardInputValidator,
): RefreshRequestDto|NoValue {
if ($dashboardInputValidator->refresh === null) {
return new NoValue();
}
$refreshInterval = $dashboardInputValidator->refresh['interval']
? (int) $dashboardInputValidator->refresh['interval']
: $dashboardInputValidator->refresh['interval'];
return new RefreshRequestDto(
refreshType: RefreshTypeConverter::fromString($dashboardInputValidator->refresh['type']),
refreshInterval: $refreshInterval
);
}
/**
* @param PartialUpdateDashboardInput $dashboardInputValidator
*
* @return PanelRequestDto[]|NoValue
*/
private static function createPanelDto(
PartialUpdateDashboardInput $dashboardInputValidator,
): array|NoValue {
if ($dashboardInputValidator->panels === null) {
return new NoValue();
}
$panels = [];
// We can't send empty arrays in multipart/form-data.
// The panels[] sent is transformed as array{0: empty-string}
if (! is_array($dashboardInputValidator->panels[0])) {
return $panels;
}
foreach ($dashboardInputValidator->panels as $panel) {
$layout = $panel['layout'];
$panelLayoutRequestDto = new PanelLayoutRequestDto(
posX: (int) $layout['x'],
posY: (int) $layout['y'],
width: (int) $layout['width'],
height: (int) $layout['height'],
minWidth: (int) $layout['min_width'],
minHeight: (int) $layout['min_height'],
);
$panelId = $panel['id'] ?? null;
$panels[] = new PanelRequestDto(
id: $panelId ? (int) $panelId : $panelId,
name: $panel['name'],
layout: $panelLayoutRequestDto,
widgetType: $panel['widget_type'],
widgetSettings: ! is_array(
json_decode($panel['widget_settings'], true)
)
? [] : json_decode(
$panel['widget_settings'],
true
),
);
}
return $panels;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Infrastructure/API/FindDashboard/FindDashboardController.php | centreon/src/Core/Dashboard/Infrastructure/API/FindDashboard/FindDashboardController.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\Dashboard\Infrastructure\API\FindDashboard;
use Centreon\Application\Controller\AbstractController;
use Core\Dashboard\Application\UseCase\FindDashboard\FindDashboard;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted(
'dashboard_access',
null,
'You do not have sufficient rights to access the dashboard'
)]
final class FindDashboardController extends AbstractController
{
/**
* @param int $dashboardId
* @param FindDashboard $useCase
* @param FindDashboardPresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
int $dashboardId,
FindDashboard $useCase,
FindDashboardPresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($dashboardId, $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/Dashboard/Infrastructure/API/FindDashboard/FindDashboardPresenter.php | centreon/src/Core/Dashboard/Infrastructure/API/FindDashboard/FindDashboardPresenter.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\Dashboard\Infrastructure\API\FindDashboard;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Dashboard\Application\UseCase\FindDashboard\FindDashboardPresenterInterface;
use Core\Dashboard\Application\UseCase\FindDashboard\FindDashboardResponse;
use Core\Dashboard\Application\UseCase\FindDashboard\Response\PanelResponseDto;
use Core\Dashboard\Application\UseCase\FindDashboard\Response\RefreshResponseDto;
use Core\Dashboard\Application\UseCase\FindDashboard\Response\ThumbnailResponseDto;
use Core\Dashboard\Application\UseCase\FindDashboard\Response\UserResponseDto;
use Core\Dashboard\Domain\Model\Role\DashboardSharingRole;
use Core\Dashboard\Infrastructure\Model\DashboardSharingRoleConverter;
use Core\Dashboard\Infrastructure\Model\RefreshTypeConverter;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Presenter\PresenterTrait;
final class FindDashboardPresenter extends DefaultPresenter implements FindDashboardPresenterInterface
{
use PresenterTrait;
public function presentResponse(ResponseStatusInterface|FindDashboardResponse $data): void
{
if ($data instanceof FindDashboardResponse) {
$this->present([
'id' => $data->id,
'name' => $data->name,
'description' => $data->description,
'created_by' => $this->userToOptionalArray($data->createdBy),
'updated_by' => $this->userToOptionalArray($data->updatedBy),
'created_at' => $this->formatDateToIso8601($data->createdAt),
'updated_at' => $this->formatDateToIso8601($data->updatedAt),
'panels' => array_map($this->panelToArray(...), $data->panels),
'own_role' => DashboardSharingRoleConverter::toString($data->ownRole),
'refresh' => $this->globalRefreshToArray($data->refresh),
'shares' => $this->formatShares($data->shares),
'thumbnail' => $this->thumbnailToOptionalArray($data->thumbnail),
'is_favorite' => $data->isFavorite,
]);
} else {
$this->setResponseStatus($data);
}
}
/**
* @param null|ThumbnailResponseDto $dto
*
* @return null|array{id:int, name:string, directory:string}
*/
private function thumbnailToOptionalArray(?ThumbnailResponseDto $dto): ?array
{
return $dto
? [
'id' => $dto->id,
'name' => $dto->name,
'directory' => $dto->directory,
]
: null;
}
/**
* @param ?UserResponseDto $dto
*
* @return null|array<scalar>
*/
private function userToOptionalArray(?UserResponseDto $dto): ?array
{
return $dto ? [
'id' => $dto->id,
'name' => $dto->name,
] : null;
}
/**
* @param PanelResponseDto $panel
*
* @return array<mixed>
*/
private function panelToArray(PanelResponseDto $panel): array
{
return [
'id' => $panel->id,
'name' => $panel->name,
'layout' => [
'x' => $panel->layout->posX,
'y' => $panel->layout->posY,
'width' => $panel->layout->width,
'height' => $panel->layout->height,
'min_width' => $panel->layout->minWidth,
'min_height' => $panel->layout->minHeight,
],
'widget_type' => $panel->widgetType,
// Enforce stdClass in order to be sure that any array will be a JSON object "{...}"
'widget_settings' => (object) $panel->widgetSettings,
];
}
/**
* @param RefreshResponseDto $refresh
*
* @return array{
* type: string,
* interval: ?int,
* }
*/
private function globalRefreshToArray(RefreshResponseDto $refresh): array
{
return [
'type' => RefreshTypeConverter::toString($refresh->refreshType),
'interval' => $refresh->refreshInterval,
];
}
/**
* @param array{
* contacts: array<int, array{
* id: int,
* name: string,
* email: string,
* role: DashboardSharingRole
* }>,
* contact_groups: array<int, array{
* id: int,
* name: string,
* role: DashboardSharingRole
* }>
* } $shares
*
* @return array{
* contacts: array<int, array{
* id: int,
* name: string,
* email: string,
* role: string
* }>,
* contact_groups: array<int, array{
* id: int,
* name: string,
* role: string
* }>
* }
*/
private function formatShares(array $shares): array
{
$formattedShares = ['contacts' => [], 'contact_groups' => []];
foreach ($shares['contacts'] as $contact) {
$formattedShares['contacts'][] = [
'id' => $contact['id'],
'name' => $contact['name'],
'email' => $contact['email'],
'role' => DashboardSharingRoleConverter::toString($contact['role']),
];
}
foreach ($shares['contact_groups'] as $contactGroup) {
$formattedShares['contact_groups'][] = [
'id' => $contactGroup['id'],
'name' => $contactGroup['name'],
'role' => DashboardSharingRoleConverter::toString($contactGroup['role']),
];
}
return $formattedShares;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Infrastructure/API/DeleteDashboard/DeleteDashboardController.php | centreon/src/Core/Dashboard/Infrastructure/API/DeleteDashboard/DeleteDashboardController.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\Dashboard\Infrastructure\API\DeleteDashboard;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Dashboard\Application\UseCase\DeleteDashboard\DeleteDashboard;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class DeleteDashboardController extends AbstractController
{
use LoggerTrait;
/**
* @param int $dashboardId
* @param DeleteDashboard $useCase
* @param DeleteDashboardPresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
int $dashboardId,
DeleteDashboard $useCase,
DeleteDashboardPresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($dashboardId, $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/Dashboard/Infrastructure/API/DeleteDashboard/DeleteDashboardPresenter.php | centreon/src/Core/Dashboard/Infrastructure/API/DeleteDashboard/DeleteDashboardPresenter.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\Dashboard\Infrastructure\API\DeleteDashboard;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Dashboard\Application\UseCase\DeleteDashboard\DeleteDashboardPresenterInterface;
use Core\Infrastructure\Common\Api\DefaultPresenter;
final class DeleteDashboardPresenter extends DefaultPresenter implements DeleteDashboardPresenterInterface
{
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/Macro/Application/Repository/ReadHostMacroRepositoryInterface.php | centreon/src/Core/Macro/Application/Repository/ReadHostMacroRepositoryInterface.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\Macro\Application\Repository;
use Core\Macro\Domain\Model\Macro;
/**
* This interface is designed to read macros for both hosts and host templates.
*/
interface ReadHostMacroRepositoryInterface
{
/**
* Find macros by host (or host template) IDs.
*
* @param int[] $hostIds
*
* @throws \Throwable
*
* @return Macro[]
*/
public function findByHostIds(array $hostIds): array;
/**
* Find macros by host (or host template) ID.
*
* @param int $hostId
*
* @throws \Throwable
*
* @return Macro[]
*/
public function findByHostId(int $hostId): array;
/**
* Find password macros.
*
* @throws \Throwable
*
* @return Macro[]
*/
public function findPasswords(): 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/Macro/Application/Repository/ReadServiceMacroRepositoryInterface.php | centreon/src/Core/Macro/Application/Repository/ReadServiceMacroRepositoryInterface.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\Macro\Application\Repository;
use Core\Macro\Domain\Model\Macro;
/**
* This interface is designed to read macros for both services and service templates.
*/
interface ReadServiceMacroRepositoryInterface
{
/**
* Find macros by service (or service template) IDs.
*
* @param int ...$serviceIds
*
* @throws \Throwable
*
* @return Macro[]
*/
public function findByServiceIds(int ...$serviceIds): array;
/**
* Find password macros.
*
* @throws \Throwable
*
* @return Macro[]
*/
public function findPasswords(): array;
/**
* Find macros for services only.
*
* @param int $pollerId
*
* @return Macro[]
*/
public function findServicesMacrosWithEncryptionReady(int $pollerId): array;
/**
* Find macros for service templates only.
*
* @param int $pollerId
*
* @return Macro[]
*/
public function findServiceTemplatesMacrosWithEncryptionReady(int $pollerId): 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/Macro/Application/Repository/WriteServiceMacroRepositoryInterface.php | centreon/src/Core/Macro/Application/Repository/WriteServiceMacroRepositoryInterface.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\Macro\Application\Repository;
use Core\Macro\Domain\Model\Macro;
interface WriteServiceMacroRepositoryInterface
{
/**
* Add service's macros.
*
* @param Macro $macro
*
* @throws \Throwable
*/
public function add(Macro $macro): void;
/**
* Delete a service's macros.
*
* @param Macro $macro
*
* @throws \Throwable
*/
public function delete(Macro $macro): void;
/**
* Update a service's macros.
*
* @param Macro $macro
*
* @throws \Throwable
*/
public function update(Macro $macro): 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/Macro/Application/Repository/WriteHostMacroRepositoryInterface.php | centreon/src/Core/Macro/Application/Repository/WriteHostMacroRepositoryInterface.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\Macro\Application\Repository;
use Core\Macro\Domain\Model\Macro;
interface WriteHostMacroRepositoryInterface
{
/**
* Add host's macros.
*
* @param Macro $macro
*
* @throws \Throwable
*/
public function add(Macro $macro): void;
/**
* Update host's macros.
*
* @param Macro $macro
*
* @throws \Throwable
*/
public function update(Macro $macro): void;
/**
* Delete host's macros.
*
* @param Macro $macro
*
* @throws \Throwable
*/
public function delete(Macro $macro): 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/Macro/Domain/Model/Macro.php | centreon/src/Core/Macro/Domain/Model/Macro.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\Macro\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
class Macro
{
public const MAX_NAME_LENGTH = 255;
public const MAX_VALUE_LENGTH = 4096;
public const MAX_DESCRIPTION_LENGTH = 65535;
private string $shortName;
private bool $isPassword = false;
private string $description = '';
private int $order = 0;
private bool $shouldBeEncrypted = false;
/**
* @param int $id|null
* @param int $ownerId
* @param string $name
* @param string $value
*
* @throws AssertionFailedException
*/
public function __construct(
private readonly ?int $id,
private readonly int $ownerId,
private string $name,
private string $value,
) {
$this->shortName = (new \ReflectionClass($this))->getShortName();
if ($id !== null) {
Assertion::positiveInt($id, "{$this->shortName}::id");
}
Assertion::positiveInt($ownerId, "{$this->shortName}::ownerId");
Assertion::notEmptyString($this->name, "{$this->shortName}::name");
$this->name = mb_strtoupper($name);
Assertion::maxLength($this->name, self::MAX_NAME_LENGTH, "{$this->shortName}::name");
Assertion::maxLength($this->value, self::MAX_VALUE_LENGTH, "{$this->shortName}::value");
}
public function getId(): ?int
{
return $this->id;
}
public function getOwnerId(): int
{
return $this->ownerId;
}
public function getName(): string
{
return $this->name;
}
public function getValue(): string
{
return $this->value;
}
public function setValue(string $value): self
{
Assertion::maxLength($this->name, self::MAX_NAME_LENGTH, "{$this->shortName}::name");
Assertion::maxLength($this->value, self::MAX_VALUE_LENGTH, "{$this->shortName}::value");
$this->value = $value;
return $this;
}
public function isPassword(): bool
{
return $this->isPassword;
}
public function setIsPassword(bool $isPassword): void
{
$this->isPassword = $isPassword;
}
public function getDescription(): string
{
return $this->description;
}
/**
* @param string $description
*
* @throws AssertionFailedException
*/
public function setDescription(string $description): void
{
$description = trim($description);
Assertion::maxLength($description, self::MAX_DESCRIPTION_LENGTH, "{$this->shortName}::description");
$this->description = $description;
}
public function getOrder(): int
{
return $this->order;
}
/**
* @param int $order
*
* @throws AssertionFailedException
*/
public function setOrder(int $order): void
{
Assertion::min($order, 0, "{$this->shortName}::order");
$this->order = $order;
}
/**
* Return two arrays:
* - the first is an array of the direct macros
* - the second is an array of the inherited macros
* Both use the macro's name as key.
*
* @param Macro[] $macros
* @param int[] $inheritanceLine
* @param int $childId
*
* @return array{
* array<string,Macro>,
* array<string,Macro>
* }
*/
public static function resolveInheritance(array $macros, array $inheritanceLine, int $childId): array
{
/** @var array<string,Macro> $directMacros */
$directMacros = [];
foreach ($macros as $macro) {
if ($macro->getOwnerId() === $childId) {
$directMacros[$macro->getName()] = $macro;
}
}
/** @var array<string,Macro> $inheritedMacros */
$inheritedMacros = [];
foreach ($inheritanceLine as $parentId) {
foreach ($macros as $macro) {
if (
! isset($inheritedMacros[$macro->getName()])
&& $macro->getOwnerId() === $parentId
) {
$inheritedMacros[$macro->getName()] = $macro;
}
}
}
return [$directMacros, $inheritedMacros];
}
public function setShouldBeEncrypted(bool $shouldBeEncrypted): self
{
$this->shouldBeEncrypted = $shouldBeEncrypted;
return $this;
}
public function shouldBeEncrypted(): bool
{
return $this->shouldBeEncrypted;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Macro/Domain/Model/MacroManager.php | centreon/src/Core/Macro/Domain/Model/MacroManager.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\Macro\Domain\Model;
use Assert\AssertionFailedException;
use Core\CommandMacro\Domain\Model\CommandMacro;
/**
* This class provide methods to help manipulate macros linked to a host template.
*/
class MacroManager
{
/**
* Return an array with the macro's name as key.
*
* @param CommandMacro[] $macros
*
* @return array<string,CommandMacro>
*/
public static function resolveInheritanceForCommandMacro(array $macros): array
{
$commandMacros = [];
foreach ($macros as $macro) {
if (! isset($commandMacros[$macro->getName()])) {
$commandMacros[$macro->getName()] = $macro;
}
}
return $commandMacros;
}
/**
* Set the order of the direct macros.
*
* Note: Order of macros seems to be only used in UI legacy configuration forms for display purposes.
* It doesn't impact macros management.
*
* @param MacroDifference $macrosDiff
* @param array<string,Macro> $macros
* @param array<string,Macro> $directMacros
*
* @throws AssertionFailedException
*/
public static function setOrder(MacroDifference $macrosDiff, array $macros, array $directMacros): void
{
$order = 0;
foreach ($macros as $macroName => $macro) {
if (
isset($macrosDiff->addedMacros[$macroName])
|| isset($macrosDiff->updatedMacros[$macroName])
) {
$macro->setOrder($order);
++$order;
continue;
}
if (
isset($macrosDiff->unchangedMacros[$macroName], $directMacros[$macroName])
) {
if ($directMacros[$macroName]->getOrder() !== $order) {
// macro is the same but its order has changed
$macro->setOrder($order);
unset($macrosDiff->unchangedMacros[$macroName]);
$macrosDiff->updatedMacros[$macroName] = $macro;
}
++$order;
}
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Macro/Domain/Model/MacroDifference.php | centreon/src/Core/Macro/Domain/Model/MacroDifference.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\Macro\Domain\Model;
use Core\CommandMacro\Domain\Model\CommandMacro;
/**
* Compare $afterMacros to $directMacros, $inheritedHostMacros and $inheritedCommandMacros
* to determine witch afterMacros were added, updated, deleted or are unchanged.
*
* Require and return arrays with macro names as keys.
*/
final class MacroDifference
{
/** @var array<string,Macro> */
public array $removedMacros = [];
/** @var array<string,Macro> */
public array $addedMacros = [];
/** @var array<string,Macro> */
public array $unchangedMacros = [];
/** @var array<string,Macro> */
public array $updatedMacros = [];
/**
* @param array<string,Macro> $directMacros
* @param array<string,Macro> $inheritedHostMacros
* @param array<string,CommandMacro> $inheritedCommandMacros
* @param array<string,Macro> $afterMacros
*/
public function compute(
array $directMacros,
array $inheritedHostMacros,
array $inheritedCommandMacros,
array $afterMacros,
): void {
foreach ($afterMacros as $macro) {
if ($macro->getId() !== null) {
// Retrieve existing password value if not changed and id is provided
foreach ($directMacros as $existingMacro) {
if ($macro->getId() !== $existingMacro->getId()) {
continue;
}
if ($macro->isPassword() === true && $macro->getValue() === '') {
$macro->setValue($existingMacro->getValue());
}
break;
}
foreach ($inheritedHostMacros as $existingMacro) {
if ($macro->getId() !== $existingMacro->getId()) {
continue;
}
if ($macro->isPassword() === true && $macro->getValue() === '') {
$macro->setValue($existingMacro->getValue());
}
break;
}
}
// Keep computing by name for now as id matching is not reliable until all macros processes are migrated and id became mandatory in API
$this->computeByName(
$directMacros,
$inheritedHostMacros,
$inheritedCommandMacros,
$macro
);
}
$extraRemovedMacros = array_diff_key(
$directMacros,
$this->addedMacros,
$this->updatedMacros,
$this->unchangedMacros
);
$this->removedMacros = array_merge($this->removedMacros, $extraRemovedMacros);
}
/**
* @param array<string,Macro> $directMacros
* @param array<string,Macro> $inheritedHostMacros
* @param array<string,CommandMacro> $inheritedCommandMacros
* @param Macro $computedMacro
*/
private function computeByName(
array $directMacros,
array $inheritedHostMacros,
array $inheritedCommandMacros,
Macro $computedMacro,
): void {
$macroName = $computedMacro->getName();
// Check macros based on name correspondance
$directMacroMatch = $directMacros[$macroName] ?? null;
$inheritedMacroMatch = $inheritedHostMacros[$macroName] ?? null;
$commandMacroMatch = $inheritedCommandMacros[$macroName] ?? null;
if ($directMacroMatch && $inheritedMacroMatch) {
$macro = $this->addMacroId($computedMacro, $directMacroMatch->getId());
if ($this->isIdenticalToInheritedMacro($macro, $inheritedMacroMatch)) {
$this->removedMacros[$macroName] = $macro;
} elseif (! $this->isIdenticalToDirectMacro($macro, $directMacroMatch)) {
$this->updatedMacros[$macroName] = $macro;
} else {
$this->unchangedMacros[$macroName] = $macro;
}
return;
}
if ($directMacroMatch && $commandMacroMatch) {
$macro = $this->addMacroId($computedMacro, $directMacroMatch->getId());
if ($this->isIdenticalToCommandMacro($macro)) {
$this->removedMacros[$macroName] = $macro;
} elseif (! $this->isIdenticalToDirectMacro($macro, $directMacroMatch)) {
$this->updatedMacros[$macroName] = $macro;
} else {
$this->unchangedMacros[$macroName] = $macro;
}
return;
}
if ($directMacroMatch) {
$macro = $this->addMacroId($computedMacro, $directMacroMatch->getId());
if (! $this->isIdenticalToDirectMacro($macro, $directMacroMatch)) {
$this->updatedMacros[$macroName] = $macro;
} else {
$this->unchangedMacros[$macroName] = $macro;
}
return;
}
if ($inheritedMacroMatch) {
if (! $this->isIdenticalToInheritedMacro($computedMacro, $inheritedMacroMatch)) {
$this->addedMacros[$macroName] = $computedMacro;
} else {
$this->unchangedMacros[$macroName] = $computedMacro;
}
return;
}
if ($commandMacroMatch) {
if (! $this->isIdenticalToCommandMacro($computedMacro)) {
$this->addedMacros[$macroName] = $computedMacro;
} else {
$this->unchangedMacros[$macroName] = $computedMacro;
}
return;
}
// Macro doesn't match any previously known macros
$this->addedMacros[$macroName] = $computedMacro;
}
private function isIdenticalToInheritedMacro(Macro $macro, Macro $existingMacro): bool
{
return
$macro->getName() === $existingMacro->getName()
&& $macro->getValue() === $existingMacro->getValue()
&& $macro->isPassword() === $existingMacro->isPassword();
}
private function isIdenticalToCommandMacro(Macro $macro): bool
{
return $macro->getValue() === '' && $macro->isPassword() === false;
}
private function isIdenticalToDirectMacro(Macro $macro, Macro $existingMacro): bool
{
return $macro->getName() === $existingMacro->getName()
&& $macro->getValue() === $existingMacro->getValue()
&& $macro->isPassword() === $existingMacro->isPassword()
&& $macro->getDescription() === $existingMacro->getDescription();
}
private function addMacroId(Macro $oldMacro, ?int $id): Macro
{
$macro = new Macro(
id: $id,
ownerId: $oldMacro->getOwnerId(),
name: $oldMacro->getName(),
value: $oldMacro->getValue(),
);
$macro->setIsPassword($oldMacro->isPassword());
$macro->setDescription($oldMacro->getDescription());
return $macro;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Macro/Infrastructure/Repository/DbReadServiceMacroRepository.php | centreon/src/Core/Macro/Infrastructure/Repository/DbReadServiceMacroRepository.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\Macro\Infrastructure\Repository;
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Assert\AssertionFailedException;
use Core\Common\Infrastructure\Repository\DatabaseRepository;
use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait;
use Core\Macro\Application\Repository\ReadServiceMacroRepositoryInterface;
use Core\Macro\Domain\Model\Macro;
/**
* @phpstan-type _Macro array{
* svc_macro_id: int,
* svc_svc_id:int,
* svc_macro_name:string,
* svc_macro_value:string,
* is_password:int|null,
* description:string|null,
* macro_order:int,
* is_encryption_ready?:int
* }
*/
class DbReadServiceMacroRepository extends DatabaseRepository implements ReadServiceMacroRepositoryInterface
{
use SqlMultipleBindTrait;
/**
* @inheritDoc
*/
public function findByServiceIds(int ...$serviceIds): array
{
if ($serviceIds === []) {
return [];
}
[$bindValues, $serviceIdsAsString] = $this->createMultipleBindQuery($serviceIds, ':serviceId_');
$queryParams = QueryParameters::create([]);
foreach ($bindValues as $key => $value) {
/** @var int $value */
$queryParams->add($key, QueryParameter::int($key, $value));
}
$results = $this->connection->fetchAllAssociative(
$this->translateDbName(
<<<SQL
SELECT
m.svc_macro_id,
m.svc_macro_name,
m.svc_macro_value,
m.is_password,
m.svc_svc_id,
m.description,
m.macro_order
FROM `:db`.on_demand_macro_service m
WHERE m.svc_svc_id IN ({$serviceIdsAsString})
SQL
),
$queryParams
);
$macros = [];
foreach ($results as $result) {
/** @var _Macro $result */
$macros[] = $this->createMacro($result);
}
return $macros;
}
/**
* @inheritDoc
*/
public function findPasswords(): array
{
$results = $this->connection->fetchAllAssociative(
$this->translateDbName(
<<<'SQL'
SELECT
m.svc_macro_id,
m.svc_macro_name,
m.svc_macro_value,
m.is_password,
m.svc_svc_id,
m.description,
m.macro_order
FROM `:db`.on_demand_macro_service m
WHERE m.is_password = 1
SQL
)
);
$macros = [];
foreach ($results as $result) {
/** @var _Macro $result */
$macros[] = $this->createMacro($result);
}
return $macros;
}
/**
* @inheritDoc
*/
public function findServicesMacrosWithEncryptionReady(int $pollerId): array
{
$results = $this->connection->fetchAllAssociative(
$this->translateDbName(
<<<'SQL'
SELECT
odms.svc_macro_id,
odms.svc_svc_id,
odms.svc_macro_name,
odms.svc_macro_value,
odms.is_password,
odms.description,
odms.macro_order,
ns.is_encryption_ready
FROM on_demand_macro_service odms
INNER JOIN host_service_relation hsr
ON odms.svc_svc_id = hsr.service_service_id
INNER JOIN ns_host_relation nsr
ON hsr.host_host_id = nsr.host_host_id
INNER JOIN nagios_server ns
ON nsr.nagios_server_id = ns.id
WHERE ns.id = :pollerId
SQL
),
QueryParameters::create([QueryParameter::int('pollerId', $pollerId)])
);
$macros = [];
foreach ($results as $result) {
/** @var array{
* svc_macro_id:int,
* svc_svc_id:int,
* svc_macro_name:string,
* svc_macro_value:string,
* is_password:int|null,
* description:string|null,
* macro_order:int,
* is_encryption_ready:int
* } $result */
$macros[] = $this->createMacro($result);
}
return $macros;
}
/**
* @inheritDoc
*/
public function findServiceTemplatesMacrosWithEncryptionReady(int $pollerId): array
{
$results = $this->connection->fetchAllAssociative(
$this->translateDbName(
<<<'SQL'
SELECT
odms.svc_macro_id,
odms.svc_svc_id,
odms.svc_macro_name,
odms.svc_macro_value,
odms.is_password,
odms.description,
odms.macro_order,
ns.is_encryption_ready
FROM on_demand_macro_service odms
INNER JOIN service svc
ON odms.svc_svc_id = svc.service_template_model_stm_id
INNER JOIN host_service_relation hsr
ON svc.service_id = hsr.service_service_id
INNER JOIN ns_host_relation nsr
ON hsr.host_host_id = nsr.host_host_id
INNER JOIN nagios_server ns
ON nsr.nagios_server_id = ns.id
WHERE ns.id = :pollerId
SQL
),
QueryParameters::create([QueryParameter::int('pollerId', $pollerId)])
);
$macros = [];
foreach ($results as $result) {
/** @var array{
* svc_macro_id:int,
* svc_svc_id:int,
* svc_macro_name:string,
* svc_macro_value:string,
* is_password:int|null,
* description:string|null,
* macro_order:int,
* is_encryption_ready:int
* } $result */
$macros[] = $this->createMacro($result);
}
return $macros;
}
/**
* @param _Macro $data
*
* @throws AssertionFailedException
*
* @return Macro
*/
private function createMacro(array $data): Macro
{
preg_match('/^\$_SERVICE(?<macro_name>.*)\$$/', $data['svc_macro_name'], $matches);
$macroName = $matches['macro_name'] ?? '';
$macro = new Macro(
(int) $data['svc_macro_id'],
(int) $data['svc_svc_id'],
$macroName,
$data['svc_macro_value'],
);
$shouldBeEncrypted = array_key_exists('is_encryption_ready', $data)
&& (bool) $data['is_encryption_ready'];
$macro->setIsPassword($data['is_password'] === 1);
$macro->setDescription($data['description'] ?? '');
$macro->setOrder((int) $data['macro_order']);
$macro->setShouldBeEncrypted($shouldBeEncrypted);
return $macro;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Macro/Infrastructure/Repository/DbReadHostMacroRepository.php | centreon/src/Core/Macro/Infrastructure/Repository/DbReadHostMacroRepository.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\Macro\Infrastructure\Repository;
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Assert\AssertionFailedException;
use Centreon\Domain\Log\LoggerTrait;
use Core\Common\Infrastructure\Repository\DatabaseRepository;
use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait;
use Core\Macro\Application\Repository\ReadHostMacroRepositoryInterface;
use Core\Macro\Domain\Model\Macro;
class DbReadHostMacroRepository extends DatabaseRepository implements ReadHostMacroRepositoryInterface
{
use LoggerTrait;
use SqlMultipleBindTrait;
/**
* @inheritDoc
*/
public function findByHostIds(array $hostIds): array
{
$this->info('Get host macros', ['host_ids' => $hostIds]);
if ($hostIds === []) {
return [];
}
[$bindValues, $hostIdsAsString] = $this->createMultipleBindQuery($hostIds, ':hostId_');
$queryParams = QueryParameters::create([]);
foreach ($bindValues as $key => $value) {
/** @var int $value */
$queryParams->add($key, QueryParameter::int($key, $value));
}
$results = $this->connection->fetchAllAssociative(
$this->translateDbName(
<<<SQL
SELECT
m.host_macro_id,
m.host_macro_name,
m.host_macro_value,
m.is_password,
m.host_host_id,
m.description,
m.macro_order
FROM `:db`.on_demand_macro_host m
WHERE m.host_host_id IN ({$hostIdsAsString})
SQL
),
$queryParams
);
$macros = [];
foreach ($results as $result) {
/** @var array{
* host_macro_id:int,
* host_host_id:int,
* host_macro_name:string,
* host_macro_value:string,
* is_password:int|null,
* description:string|null,
* macro_order:int
* } $result */
$macros[] = $this->createHostMacroFromArray($result);
}
return $macros;
}
/**
* @inheritDoc
*/
public function findByHostId(int $hostId): array
{
$this->info('Get host macros for a host/host template', ['host_id' => $hostId]);
$results = $this->connection->fetchAllAssociative(
$this->translateDbName(
<<<'SQL'
SELECT
m.host_macro_id,
m.host_macro_name,
m.host_macro_value,
m.is_password,
m.host_host_id,
m.description,
m.macro_order
FROM `:db`.on_demand_macro_host m
WHERE m.host_host_id = :host_id
SQL
),
QueryParameters::create([QueryParameter::int('host_id', $hostId)])
);
$macros = [];
foreach ($results as $result) {
/** @var array{
* host_macro_id:int,
* host_host_id:int,
* host_macro_name:string,
* host_macro_value:string,
* is_password:int|null,
* description:string|null,
* macro_order:int
* } $result */
$macros[] = $this->createHostMacroFromArray($result);
}
return $macros;
}
/**
* @inheritDoc
*/
public function findPasswords(): array
{
$results = $this->connection->fetchAllAssociative($this->translateDbName(
<<<'SQL'
SELECT
m.host_macro_id,
m.host_macro_name,
m.host_macro_value,
m.is_password,
m.host_host_id,
m.description,
m.macro_order
FROM `:db`.on_demand_macro_host m
WHERE m.is_password = 1
SQL
));
$macros = [];
foreach ($results as $result) {
/** @var array{
* host_macro_id:int,
* host_host_id:int,
* host_macro_name:string,
* host_macro_value:string,
* is_password:int|null,
* description:string|null,
* macro_order:int
* } $result */
$macros[] = $this->createHostMacroFromArray($result);
}
return $macros;
}
/**
* @param array{
* host_macro_id:int,
* host_host_id:int,
* host_macro_name:string,
* host_macro_value:string,
* is_password:int|null,
* description:string|null,
* macro_order:int|null,
* is_encryption_ready?:int
* } $data
*
* @throws AssertionFailedException
*
* @return Macro
*/
private function createHostMacroFromArray(array $data): Macro
{
preg_match('/^\$_HOST(?<macro_name>.*)\$$/', $data['host_macro_name'], $matches);
$macroName = $matches['macro_name'] ?? '';
$macro = new Macro(
(int) $data['host_macro_id'],
(int) $data['host_host_id'],
$macroName,
$data['host_macro_value'],
);
$shouldBeEncrypted = array_key_exists('is_encryption_ready', $data)
&& (bool) $data['is_encryption_ready'];
$macro->setIsPassword((bool) $data['is_password']);
$macro->setDescription($data['description'] ?? '');
$macro->setOrder($data['macro_order'] ?? 0);
$macro->setShouldBeEncrypted($shouldBeEncrypted);
return $macro;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Macro/Infrastructure/Repository/DbWriteServiceMacroRepository.php | centreon/src/Core/Macro/Infrastructure/Repository/DbWriteServiceMacroRepository.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\Macro\Infrastructure\Repository;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Common\Infrastructure\Repository\RepositoryTrait;
use Core\Macro\Application\Repository\WriteServiceMacroRepositoryInterface;
use Core\Macro\Domain\Model\Macro;
class DbWriteServiceMacroRepository extends AbstractRepositoryRDB implements WriteServiceMacroRepositoryInterface
{
use RepositoryTrait;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function add(Macro $macro): void
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
INSERT INTO `:db`.`on_demand_macro_service`
(`svc_macro_name`, `svc_macro_value`, `is_password`, `description`, `svc_svc_id`, `macro_order`)
VALUES (:name, :value, :is_password, :description, :service_id, :order)
SQL
));
$statement->bindValue(':service_id', $macro->getOwnerId(), \PDO::PARAM_INT);
$statement->bindValue(':name', '$_SERVICE' . $macro->getName() . '$', \PDO::PARAM_STR);
$statement->bindValue(':value', $macro->getValue(), \PDO::PARAM_STR);
$statement->bindValue(':is_password', $macro->isPassword() ? '1' : null, \PDO::PARAM_INT);
$statement->bindValue(':description', $this->emptyStringAsNull($macro->getDescription()), \PDO::PARAM_STR);
$statement->bindValue(':order', $macro->getOrder(), \PDO::PARAM_INT);
$statement->execute();
}
/**
* @inheritDoc
*/
public function delete(Macro $macro): void
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
DELETE FROM `:db`.`on_demand_macro_service`
WHERE `svc_svc_id` = :service_id
AND `svc_macro_name` = :macro_name
SQL
));
$statement->bindValue(':service_id', $macro->getOwnerId(), \PDO::PARAM_INT);
$statement->bindValue(':macro_name', '$_SERVICE' . $macro->getName() . '$', \PDO::PARAM_STR);
$statement->execute();
}
/**
* @inheritDoc
*/
public function update(Macro $macro): void
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
UPDATE `:db`.`on_demand_macro_service`
SET `svc_macro_value` = :macro_value,
`is_password` = :is_password,
`description` = :macro_description,
`macro_order` = :macro_order
WHERE `svc_svc_id` = :service_id
AND `svc_macro_name` = :macro_name
SQL
));
$statement->bindValue(':service_id', $macro->getOwnerId(), \PDO::PARAM_INT);
$statement->bindValue(':macro_name', '$_SERVICE' . $macro->getName() . '$', \PDO::PARAM_STR);
$statement->bindValue(':macro_value', $macro->getValue(), \PDO::PARAM_STR);
$statement->bindValue(':is_password', $macro->isPassword() ? '1' : null, \PDO::PARAM_INT);
$statement->bindValue(':macro_order', $macro->getOrder(), \PDO::PARAM_INT);
$statement->bindValue(
':macro_description',
$this->emptyStringAsNull($macro->getDescription()),
\PDO::PARAM_STR
);
$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/Macro/Infrastructure/Repository/DbWriteHostMacroRepository.php | centreon/src/Core/Macro/Infrastructure/Repository/DbWriteHostMacroRepository.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\Macro\Infrastructure\Repository;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Common\Infrastructure\Repository\RepositoryTrait;
use Core\Macro\Application\Repository\WriteHostMacroRepositoryInterface;
use Core\Macro\Domain\Model\Macro;
class DbWriteHostMacroRepository extends AbstractRepositoryRDB implements WriteHostMacroRepositoryInterface
{
use LoggerTrait;
use RepositoryTrait;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function add(Macro $macro): void
{
$this->debug('Add host macro', ['macro' => $macro]);
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
INSERT INTO `:db`.`on_demand_macro_host`
(`host_macro_name`, `host_macro_value`, `is_password`, `description`, `host_host_id`, `macro_order`)
VALUES (:macroName, :macroValue, :isPassword, :macroDescription, :hostId, :macroOrder)
SQL
));
$statement->bindValue(':hostId', $macro->getOwnerId(), \PDO::PARAM_INT);
$statement->bindValue(':macroName', '$_HOST' . $macro->getName() . '$', \PDO::PARAM_STR);
$statement->bindValue(':macroValue', $macro->getValue(), \PDO::PARAM_STR);
$statement->bindValue(':isPassword', $macro->isPassword() ? '1' : null, \PDO::PARAM_INT);
$statement->bindValue(
':macroDescription',
$this->emptyStringAsNull($macro->getDescription()),
\PDO::PARAM_STR
);
$statement->bindValue(':macroOrder', $macro->getOrder(), \PDO::PARAM_INT);
$statement->execute();
}
/**
* @inheritDoc
*/
public function update(Macro $macro): void
{
$this->debug('Update host macro', ['macro' => $macro]);
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
UPDATE `:db`.`on_demand_macro_host`
SET
`host_macro_name` = :macroName,
`host_macro_value` = :macroValue,
`is_password` = :isPassword,
`description` = :macroDescription,
`macro_order` = :macroOrder
WHERE `host_host_id` = :hostId
AND `host_macro_id` = :macroId
SQL
));
$statement->bindValue(':hostId', $macro->getOwnerId(), \PDO::PARAM_INT);
$statement->bindValue(':macroId', $macro->getId(), \PDO::PARAM_INT);
$statement->bindValue(':macroName', '$_HOST' . $macro->getName() . '$', \PDO::PARAM_STR);
$statement->bindValue(':macroValue', $macro->getValue(), \PDO::PARAM_STR);
$statement->bindValue(':isPassword', $macro->isPassword() ? '1' : null, \PDO::PARAM_INT);
$statement->bindValue(
':macroDescription',
$this->emptyStringAsNull($macro->getDescription()),
\PDO::PARAM_STR
);
$statement->bindValue(':macroOrder', $macro->getOrder(), \PDO::PARAM_INT);
$statement->execute();
}
/**
* @inheritDoc
*/
public function delete(Macro $macro): void
{
$this->debug('Delete host macro', ['macro' => $macro]);
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
DELETE
FROM `:db`.`on_demand_macro_host`
WHERE
`host_host_id` = :hostId
AND `host_macro_id` = :macroId
SQL
));
$statement->bindValue(':hostId', $macro->getOwnerId(), \PDO::PARAM_INT);
$statement->bindValue(':macroId', $macro->getId(), \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/Host/Application/InheritanceManager.php | centreon/src/Core/Host/Application/InheritanceManager.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\Application;
use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface;
/**
* This class provide methods to help resolve and validate host inheritance.
*/
class InheritanceManager
{
public function __construct(
private readonly ReadHostTemplateRepositoryInterface $readHostTemplateRepository,
) {
}
/**
* Return an ordered line of inheritance for a host or host template.
* (This is a recursive method).
*
* @param int $hostId
* @param array<array{parent_id:int,child_id:int,order:int}> $parents
*
* @return int[]
*/
public static function findInheritanceLine(int $hostId, array $parents): array
{
$inheritanceLine = [];
$directParents = array_filter($parents, (fn ($row) => $row['child_id'] === $hostId));
usort(
$directParents,
(static fn (array $parentA, array $parentB): int => $parentA['order'] <=> $parentB['order'])
);
foreach ($directParents as $parent) {
$inheritanceLine = array_merge(
$inheritanceLine,
[$parent['parent_id']],
self::findInheritanceLine($parent['parent_id'], $parents)
);
}
return array_unique($inheritanceLine);
}
/**
* Return false if a circular inheritance is detected, true otherwise.
*
* @param int $hostId
* @param int[] $parents
*
* @return bool
*/
public function isValidInheritanceTree(int $hostId, array $parents): bool
{
foreach ($parents as $templateId) {
$ancestors = $this->readHostTemplateRepository->findParents($templateId);
if (in_array($hostId, array_column($ancestors, 'parent_id'), true)) {
return false;
}
}
return 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/Host/Application/UseCase/AddHost/AddHostResponse.php | centreon/src/Core/Host/Application/UseCase/AddHost/AddHostResponse.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\Application\UseCase\AddHost;
final class AddHostResponse
{
public int $id = 0;
public int $monitoringServerId = 0;
public string $name = '';
public string $address = '';
public ?string $snmpVersion = null;
public ?string $geoCoords = null;
public string $alias = '';
public string $snmpCommunity = '';
public string $noteUrl = '';
public string $note = '';
public string $actionUrl = '';
public string $iconAlternative = '';
public string $comment = '';
/** @var string[] */
public array $checkCommandArgs = [];
/** @var string[] */
public array $eventHandlerCommandArgs = [];
public int $activeCheckEnabled = 2;
public int $passiveCheckEnabled = 2;
public int $notificationEnabled = 2;
public int $freshnessChecked = 2;
public int $eventHandlerEnabled = 2;
public ?int $timezoneId = null;
public ?int $severityId = null;
public ?int $checkCommandId = null;
public ?int $checkTimeperiodId = null;
public ?int $notificationTimeperiodId = null;
public ?int $iconId = null;
public ?int $maxCheckAttempts = null;
public ?int $normalCheckInterval = null;
public ?int $retryCheckInterval = null;
public ?int $notificationOptions = null;
public ?int $notificationInterval = null;
public ?int $firstNotificationDelay = null;
public ?int $recoveryNotificationDelay = null;
public ?int $acknowledgementTimeout = null;
public ?int $freshnessThreshold = null;
public int $flapDetectionEnabled = 2;
public ?int $lowFlapThreshold = null;
public ?int $highFlapThreshold = null;
public ?int $eventHandlerCommandId = null;
/** @var array<array{id:int,name:string}> */
public array $categories = [];
/** @var array<array{id:int,name:string}> */
public array $groups = [];
/** @var array<array{id:int,name:string}> */
public array $templates = [];
/** @var array<array{id:int|null,name:string,value:null|string,isPassword:bool,description:string}> */
public array $macros = [];
public bool $addInheritedContactGroup = false;
public bool $addInheritedContact = false;
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/Host/Application/UseCase/AddHost/NewHostFactory.php | centreon/src/Core/Host/Application/UseCase/AddHost/NewHostFactory.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\Application\UseCase\AddHost;
use Core\Common\Application\Converter\YesNoDefaultConverter;
use Core\Domain\Common\GeoCoords;
use Core\Host\Application\Converter\HostEventConverter;
use Core\Host\Domain\Model\NewHost;
use Core\Host\Domain\Model\SnmpVersion;
final class NewHostFactory
{
/**
* @param AddHostRequest $dto
* @param int $inheritanceMode
*
* @throws \Assert\AssertionFailedException
* @throws \Throwable
*
* @return NewHost
*/
public static function create(AddHostRequest $dto, int $inheritanceMode): NewHost
{
return new NewHost(
name: $dto->name,
address: $dto->address,
monitoringServerId: $dto->monitoringServerId,
alias: $dto->alias,
snmpVersion: $dto->snmpVersion === ''
? null
: SnmpVersion::from($dto->snmpVersion),
snmpCommunity: $dto->snmpCommunity,
noteUrl: $dto->noteUrl,
note: $dto->note,
actionUrl: $dto->actionUrl,
iconId: $dto->iconId,
iconAlternative: $dto->iconAlternative,
comment: $dto->comment,
geoCoordinates: $dto->geoCoordinates === ''
? null
: GeoCoords::fromString($dto->geoCoordinates),
notificationOptions: $dto->notificationOptions === null
? []
: HostEventConverter::fromBitFlag($dto->notificationOptions),
checkCommandArgs: $dto->checkCommandArgs,
eventHandlerCommandArgs: $dto->eventHandlerCommandArgs,
timezoneId: $dto->timezoneId,
severityId: $dto->severityId,
checkCommandId: $dto->checkCommandId,
checkTimeperiodId: $dto->checkTimeperiodId,
notificationTimeperiodId: $dto->notificationTimeperiodId,
eventHandlerCommandId: $dto->eventHandlerCommandId,
maxCheckAttempts: $dto->maxCheckAttempts,
normalCheckInterval: $dto->normalCheckInterval,
retryCheckInterval: $dto->retryCheckInterval,
notificationInterval: $dto->notificationInterval,
firstNotificationDelay: $dto->firstNotificationDelay,
recoveryNotificationDelay: $dto->recoveryNotificationDelay,
acknowledgementTimeout: $dto->acknowledgementTimeout,
freshnessThreshold: $dto->freshnessThreshold,
lowFlapThreshold: $dto->lowFlapThreshold,
highFlapThreshold: $dto->highFlapThreshold,
activeCheckEnabled: YesNoDefaultConverter::fromScalar($dto->activeCheckEnabled),
passiveCheckEnabled: YesNoDefaultConverter::fromScalar($dto->passiveCheckEnabled),
notificationEnabled: YesNoDefaultConverter::fromScalar($dto->notificationEnabled),
freshnessChecked: YesNoDefaultConverter::fromScalar($dto->freshnessChecked),
flapDetectionEnabled: YesNoDefaultConverter::fromScalar($dto->flapDetectionEnabled),
eventHandlerEnabled: YesNoDefaultConverter::fromScalar($dto->eventHandlerEnabled),
addInheritedContactGroup: $inheritanceMode === 1 ? $dto->addInheritedContactGroup : false,
addInheritedContact: $inheritanceMode === 1 ? $dto->addInheritedContact : false,
isActivated: $dto->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/Host/Application/UseCase/AddHost/AddHostFactory.php | centreon/src/Core/Host/Application/UseCase/AddHost/AddHostFactory.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\Application\UseCase\AddHost;
use Core\Common\Application\Converter\YesNoDefaultConverter;
use Core\Host\Application\Converter\HostEventConverter;
use Core\Host\Domain\Model\Host;
use Core\HostCategory\Domain\Model\HostCategory;
use Core\HostGroup\Domain\Model\HostGroup;
use Core\Macro\Domain\Model\Macro;
final class AddHostFactory
{
/**
* @param Host $host
* @param HostCategory[] $hostCategories
* @param array<array{id:int,name:string}> $parentTemplates
* @param Macro[] $macros
* @param HostGroup[] $hostGroups
*
* @throws \Throwable
*
* @return AddHostResponse
*/
public static function createResponse(
Host $host,
array $hostCategories,
array $parentTemplates,
array $macros,
array $hostGroups,
): AddHostResponse {
$dto = new AddHostResponse();
$dto->id = $host->getId();
$dto->monitoringServerId = $host->getMonitoringServerId();
$dto->name = $host->getName();
$dto->address = $host->getAddress();
$dto->snmpVersion = $host->getSnmpVersion()?->value;
$dto->geoCoords = $host->getGeoCoordinates()?->__toString();
$dto->alias = $host->getAlias();
$dto->snmpCommunity = $host->getSnmpCommunity();
$dto->noteUrl = $host->getNoteUrl();
$dto->note = $host->getNote();
$dto->actionUrl = $host->getActionUrl();
$dto->iconId = $host->getIconId();
$dto->iconAlternative = $host->getIconAlternative();
$dto->comment = $host->getComment();
$dto->checkCommandArgs = $host->getCheckCommandArgs();
$dto->eventHandlerCommandArgs = $host->getEventHandlerCommandArgs();
$dto->activeCheckEnabled = YesNoDefaultConverter::toInt($host->getActiveCheckEnabled());
$dto->passiveCheckEnabled = YesNoDefaultConverter::toInt($host->getPassiveCheckEnabled());
$dto->notificationEnabled = YesNoDefaultConverter::toInt($host->getNotificationEnabled());
$dto->notificationOptions = HostEventConverter::toBitFlag($host->getNotificationOptions());
$dto->freshnessChecked = YesNoDefaultConverter::toInt($host->getFreshnessChecked());
$dto->flapDetectionEnabled = YesNoDefaultConverter::toInt($host->getFlapDetectionEnabled());
$dto->eventHandlerEnabled = YesNoDefaultConverter::toInt($host->getEventHandlerEnabled());
$dto->timezoneId = $host->getTimezoneId();
$dto->severityId = $host->getSeverityId();
$dto->checkCommandId = $host->getCheckCommandId();
$dto->checkTimeperiodId = $host->getCheckTimeperiodId();
$dto->eventHandlerCommandId = $host->getEventHandlerCommandId();
$dto->maxCheckAttempts = $host->getMaxCheckAttempts();
$dto->normalCheckInterval = $host->getNormalCheckInterval();
$dto->retryCheckInterval = $host->getRetryCheckInterval();
$dto->notificationInterval = $host->getNotificationInterval();
$dto->notificationTimeperiodId = $host->getNotificationTimeperiodId();
$dto->firstNotificationDelay = $host->getFirstNotificationDelay();
$dto->recoveryNotificationDelay = $host->getRecoveryNotificationDelay();
$dto->acknowledgementTimeout = $host->getAcknowledgementTimeout();
$dto->freshnessThreshold = $host->getFreshnessThreshold();
$dto->lowFlapThreshold = $host->getLowFlapThreshold();
$dto->highFlapThreshold = $host->getHighFlapThreshold();
$dto->addInheritedContactGroup = $host->addInheritedContactGroup();
$dto->addInheritedContact = $host->addInheritedContact();
$dto->isActivated = $host->isActivated();
$dto->categories = array_map(
fn (HostCategory $category) => ['id' => $category->getId(), 'name' => $category->getName()],
$hostCategories
);
$dto->groups = array_map(
fn (HostGroup $group) => ['id' => $group->getId(), 'name' => $group->getName()],
$hostGroups
);
$dto->templates = array_map(
fn ($template) => ['id' => $template['id'], 'name' => $template['name']],
$parentTemplates
);
$dto->macros = array_map(
static fn (Macro $macro): array => [
'id' => $macro->getId(),
'name' => $macro->getName(),
'value' => $macro->getValue(),
'isPassword' => $macro->isPassword(),
'description' => $macro->getDescription(),
],
$macros
);
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/Host/Application/UseCase/AddHost/AddHostPresenterInterface.php | centreon/src/Core/Host/Application/UseCase/AddHost/AddHostPresenterInterface.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\Application\UseCase\AddHost;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface AddHostPresenterInterface
{
public function presentResponse(AddHostResponse|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/Host/Application/UseCase/AddHost/AddHostRequest.php | centreon/src/Core/Host/Application/UseCase/AddHost/AddHostRequest.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\Application\UseCase\AddHost;
final class AddHostRequest
{
public string $name = '';
public string $address = '';
public int $monitoringServerId = 0;
public string $alias = '';
public string $snmpVersion = '';
public string $snmpCommunity = '';
public string $noteUrl = '';
public string $note = '';
public string $actionUrl = '';
public string $iconAlternative = '';
public string $comment = '';
public string $geoCoordinates = '';
/** @var string[] */
public array $checkCommandArgs = [];
/** @var string[] */
public array $eventHandlerCommandArgs = [];
public int $activeCheckEnabled = 2;
public int $passiveCheckEnabled = 2;
public int $notificationEnabled = 2;
public int $freshnessChecked = 2;
public int $flapDetectionEnabled = 2;
public int $eventHandlerEnabled = 2;
public ?int $timezoneId = null;
public ?int $severityId = null;
public ?int $checkCommandId = null;
public ?int $checkTimeperiodId = null;
public ?int $notificationTimeperiodId = null;
public ?int $eventHandlerCommandId = null;
public ?int $iconId = null;
public ?int $maxCheckAttempts = null;
public ?int $normalCheckInterval = null;
public ?int $retryCheckInterval = null;
public ?int $notificationOptions = null;
public ?int $notificationInterval = null;
public bool $addInheritedContactGroup = false;
public bool $addInheritedContact = false;
public ?int $firstNotificationDelay = null;
public ?int $recoveryNotificationDelay = null;
public ?int $acknowledgementTimeout = null;
public ?int $freshnessThreshold = null;
public ?int $lowFlapThreshold = null;
public ?int $highFlapThreshold = null;
/** @var int[] */
public array $categories = [];
/** @var int[] */
public array $groups = [];
/** @var int[] */
public array $templates = [];
/** @var array<array{id?:int|null,name:string,value:null|string,is_password:bool,description:null|string}> */
public array $macros = [];
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/Host/Application/UseCase/AddHost/AddHost.php | centreon/src/Core/Host/Application/UseCase/AddHost/AddHost.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\Application\UseCase\AddHost;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Option\OptionService;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Core\Application\Common\UseCase\ConflictResponse;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Command\Domain\Model\CommandType;
use Core\CommandMacro\Application\Repository\ReadCommandMacroRepositoryInterface;
use Core\CommandMacro\Domain\Model\CommandMacro;
use Core\CommandMacro\Domain\Model\CommandMacroType;
use Core\Common\Application\Repository\ReadVaultRepositoryInterface;
use Core\Common\Application\Repository\WriteVaultRepositoryInterface;
use Core\Common\Application\UseCase\VaultTrait;
use Core\Common\Infrastructure\Repository\AbstractVaultRepository;
use Core\Host\Application\Exception\HostException;
use Core\Host\Application\InheritanceManager;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
use Core\Host\Application\Repository\WriteHostRepositoryInterface;
use Core\Host\Application\Repository\WriteRealTimeHostRepositoryInterface;
use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface;
use Core\HostCategory\Application\Repository\WriteHostCategoryRepositoryInterface;
use Core\HostGroup\Application\Repository\ReadHostGroupRepositoryInterface;
use Core\HostGroup\Application\Repository\WriteHostGroupRepositoryInterface;
use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface;
use Core\Macro\Application\Repository\ReadHostMacroRepositoryInterface;
use Core\Macro\Application\Repository\WriteHostMacroRepositoryInterface;
use Core\Macro\Domain\Model\Macro;
use Core\Macro\Domain\Model\MacroDifference;
use Core\Macro\Domain\Model\MacroManager;
use Core\MonitoringServer\Application\Repository\WriteMonitoringServerRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\Vault\Domain\Model\VaultConfiguration;
final class AddHost
{
use LoggerTrait;
use VaultTrait;
public function __construct(
private readonly WriteHostRepositoryInterface $writeHostRepository,
private readonly ReadHostRepositoryInterface $readHostRepository,
private readonly WriteMonitoringServerRepositoryInterface $writeMonitoringServerRepository,
private readonly ReadHostTemplateRepositoryInterface $readHostTemplateRepository,
private readonly ReadHostCategoryRepositoryInterface $readHostCategoryRepository,
private readonly ReadHostGroupRepositoryInterface $readHostGroupRepository,
private readonly WriteHostCategoryRepositoryInterface $writeHostCategoryRepository,
private readonly WriteHostGroupRepositoryInterface $writeHostGroupRepository,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly ReadHostMacroRepositoryInterface $readHostMacroRepository,
private readonly ReadCommandMacroRepositoryInterface $readCommandMacroRepository,
private readonly WriteHostMacroRepositoryInterface $writeHostMacroRepository,
private readonly DataStorageEngineInterface $dataStorageEngine,
private readonly OptionService $optionService,
private readonly ContactInterface $user,
private readonly AddHostValidation $validation,
private readonly WriteVaultRepositoryInterface $writeVaultRepository,
private readonly ReadVaultRepositoryInterface $readVaultRepository,
private readonly WriteRealTimeHostRepositoryInterface $writeRealTimeHostRepository,
) {
$this->writeVaultRepository->setCustomPath(AbstractVaultRepository::HOST_VAULT_PATH);
}
/**
* @param AddHostRequest $request
* @param AddHostPresenterInterface $presenter
*/
public function __invoke(AddHostRequest $request, AddHostPresenterInterface $presenter): void
{
try {
if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_HOSTS_WRITE)) {
$this->error(
"User doesn't have sufficient rights to add a host",
['user_id' => $this->user->getId()]
);
$presenter->presentResponse(
new ForbiddenResponse(HostException::addNotAllowed()->getMessage())
);
return;
}
$accessGroups = [];
if (! $this->user->isAdmin()) {
$accessGroups = $this->readAccessGroupRepository->findByContact($this->user);
$this->validation->accessGroups = $accessGroups;
}
try {
$this->dataStorageEngine->startTransaction();
$hostId = $this->createHost($request);
$this->linkHostCategories($request, $hostId);
$this->linkHostGroups($request, $hostId);
$this->linkParentTemplates($request, $hostId);
$this->addMacros($request, $hostId);
if ($accessGroups !== []) {
$this->writeRealTimeHostRepository->addHostToResourceAcls($hostId, $accessGroups);
}
$this->writeMonitoringServerRepository->notifyConfigurationChange($request->monitoringServerId);
$this->dataStorageEngine->commitTransaction();
} catch (\Throwable $ex) {
$this->error("Rollback of 'Add Host' transaction.");
$this->dataStorageEngine->rollbackTransaction();
throw $ex;
}
$presenter->presentResponse(
$this->createResponse($hostId, $request->templates)
);
} catch (AssertionFailedException|\ValueError $ex) {
$presenter->presentResponse(new InvalidArgumentResponse($ex));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (HostException $ex) {
$presenter->presentResponse(
match ($ex->getCode()) {
HostException::CODE_CONFLICT => new ConflictResponse($ex),
default => new ErrorResponse($ex),
}
);
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (\Throwable $ex) {
$presenter->presentResponse(
new ErrorResponse(HostException::addHost())
);
$this->error((string) $ex);
}
}
/**
* @param AddHostRequest $request
*
* @throws AssertionFailedException
* @throws HostException
* @throws \Throwable
*
* @return int
*/
private function createHost(AddHostRequest $request): int
{
$this->validation->assertIsValidName($request->name);
$this->validation->assertIsValidMonitoringServer($request->monitoringServerId);
$this->validation->assertIsValidSeverity($request->severityId);
$this->validation->assertIsValidTimezone($request->timezoneId);
$this->validation->assertIsValidTimePeriod($request->checkTimeperiodId, 'checkTimeperiodId');
$this->validation->assertIsValidTimePeriod($request->notificationTimeperiodId, 'notificationTimeperiodId');
$this->validation->assertIsValidCommand($request->checkCommandId, CommandType::Check, 'checkCommandId');
$this->validation->assertIsValidCommand($request->eventHandlerCommandId, null, 'eventHandlerCommandId');
$this->validation->assertIsValidIcon($request->iconId);
$inheritanceMode = $this->optionService->findSelectedOptions(['inheritance_mode']);
$inheritanceMode = isset($inheritanceMode[0])
? (int) $inheritanceMode[0]->getValue()
: 0;
if ($this->writeVaultRepository->isVaultConfigured() === true && $request->snmpCommunity !== '') {
$vaultPaths = $this->writeVaultRepository->upsert(
null,
[VaultConfiguration::HOST_SNMP_COMMUNITY_KEY => $request->snmpCommunity]
);
$vaultPath = $vaultPaths[VaultConfiguration::HOST_SNMP_COMMUNITY_KEY];
$this->uuid ??= $this->getUuidFromPath($vaultPath);
$request->snmpCommunity = $vaultPath;
}
$newHost = NewHostFactory::create($request, $inheritanceMode);
$hostId = $this->writeHostRepository->add($newHost);
$this->info('AddHost: Adding new host', ['host_id' => $hostId]);
return $hostId;
}
/**
* @param AddHostRequest $dto
* @param int $hostId
*
* @throws HostException
* @throws \Throwable
*/
private function linkHostCategories(AddHostRequest $dto, int $hostId): void
{
$categoryIds = array_unique($dto->categories);
if ($categoryIds === []) {
return;
}
$this->validation->assertAreValidCategories($categoryIds);
$this->info(
'AddHost: Linking host categories',
['host_id' => $hostId, 'category_ids' => $categoryIds]
);
$this->writeHostCategoryRepository->linkToHost($hostId, $categoryIds);
}
/**
* @param AddHostRequest $dto
* @param int $hostId
*
* @throws HostException
* @throws \Throwable
*/
private function linkHostGroups(AddHostRequest $dto, int $hostId): void
{
$groupIds = array_unique($dto->groups);
if ($groupIds === []) {
return;
}
$this->validation->assertAreValidGroups($groupIds);
$this->info(
'AddHost: Linking host groups',
['host_id' => $hostId, 'group_ids' => $groupIds]
);
$this->writeHostGroupRepository->linkToHost($hostId, $groupIds);
}
/**
* @param AddHostRequest $dto
* @param int $hostId
*
* @throws HostException
* @throws \Throwable
*/
private function linkParentTemplates(AddHostRequest $dto, int $hostId): void
{
$parentTemplateIds = array_unique($dto->templates);
if ($parentTemplateIds === []) {
return;
}
$this->validation->assertAreValidTemplates($parentTemplateIds, $hostId);
$this->info(
'AddHost: Linking parent templates',
['host_id' => $hostId, 'template_ids' => $parentTemplateIds]
);
foreach ($parentTemplateIds as $order => $templateId) {
$this->writeHostRepository->addParent($hostId, $templateId, $order);
}
}
/**
* @param int[] $templateIds
*
* @throws HostException
* @throws \Throwable
*
* @return array<array{id:int,name:string}>
*/
private function findParentTemplates(array $templateIds): array
{
$templateNames = $this->readHostTemplateRepository->findNamesByIds($templateIds);
$parentTemplates = [];
foreach ($templateIds as $templateId) {
$parentTemplates[] = [
'id' => $templateId,
'name' => $templateNames[$templateId],
];
}
return $parentTemplates;
}
/**
* @param AddHostRequest $dto
* @param int $hostId
*
* @throws \Throwable
*/
private function addMacros(AddHostRequest $dto, int $hostId): void
{
$this->info(
'AddHost: Add macros',
['host_template_id' => $hostId, 'macros' => $dto->macros]
);
/**
* @var array<string,Macro> $inheritedMacros
* @var array<string,CommandMacro> $commandMacros
*/
[$inheritedMacros, $commandMacros]
= $this->findAllInheritedMacros($hostId, $dto->checkCommandId);
$macros = [];
foreach ($dto->macros as $data) {
$macro = HostMacroFactory::create($data, $hostId, $inheritedMacros);
$macros[$macro->getName()] = $macro;
}
$macrosDiff = new MacroDifference();
$macrosDiff->compute([], $inheritedMacros, $commandMacros, $macros);
MacroManager::setOrder($macrosDiff, $macros, []);
foreach ($macrosDiff->addedMacros as $macro) {
if ($macro->getDescription() === '') {
$macro->setDescription(
isset($commandMacros[$macro->getName()])
? $commandMacros[$macro->getName()]->getDescription()
: ''
);
}
if ($this->writeVaultRepository->isVaultConfigured() === true && $macro->isPassword() === true) {
$vaultPaths = $this->writeVaultRepository->upsert(
$this->uuid ?? null,
['_HOST' . $macro->getName() => $macro->getValue()],
);
$vaultPath = $vaultPaths['_HOST' . $macro->getName()];
$this->uuid ??= $this->getUuidFromPath($vaultPath);
$inVaultMacro = new Macro(null, $macro->getOwnerId(), $macro->getName(), $vaultPath);
$inVaultMacro->setDescription($macro->getDescription());
$inVaultMacro->setIsPassword($macro->isPassword());
$inVaultMacro->setOrder($macro->getOrder());
$macro = $inVaultMacro;
}
$this->writeHostMacroRepository->add($macro);
}
}
/**
* Find macros of a host:
* macros linked through template inheritance, macros linked through command inheritance.
*
* @param int $hostId
* @param ?int $checkCommandId
*
* @throws \Throwable
*
* @return array{
* array<string,Macro>,
* array<string,CommandMacro>
* }
*/
private function findAllInheritedMacros(int $hostId, ?int $checkCommandId): array
{
$templateParents = $this->readHostRepository->findParents($hostId);
$inheritanceLine = InheritanceManager::findInheritanceLine($hostId, $templateParents);
$existingHostMacros = $this->readHostMacroRepository->findByHostIds($inheritanceLine);
[, $inheritedMacros] = Macro::resolveInheritance(
$existingHostMacros,
$inheritanceLine,
$hostId
);
/** @var array<string,CommandMacro> $commandMacros */
$commandMacros = [];
if ($checkCommandId !== null) {
$existingCommandMacros = $this->readCommandMacroRepository->findByCommandIdAndType(
$checkCommandId,
CommandMacroType::Host
);
$commandMacros = MacroManager::resolveInheritanceForCommandMacro($existingCommandMacros);
}
return [
$this->writeVaultRepository->isVaultConfigured()
? $this->retrieveMacrosVaultValues($inheritedMacros)
: $inheritedMacros,
$commandMacros,
];
}
/**
* @param int $hostId
* @param int[] $parentTemplateIds
*
* @throws AssertionFailedException
* @throws HostException
* @throws \Throwable
*
* @return AddHostResponse
*/
private function createResponse(int $hostId, array $parentTemplateIds): AddHostResponse
{
$host = $this->readHostRepository->findById($hostId);
if (! $host) {
throw HostException::errorWhileRetrievingObject();
}
if ($this->user->isAdmin()) {
$hostCategories = $this->readHostCategoryRepository->findByHost($hostId);
$hostGroups = $this->readHostGroupRepository->findByHost($hostId);
} else {
$accessGroups = $this->readAccessGroupRepository->findByContact($this->user);
$hostCategories = $this->readHostCategoryRepository->findByHostAndAccessGroups(
$hostId,
$accessGroups
);
$hostGroups = $this->readHostGroupRepository->findByHostAndAccessGroups($hostId, $accessGroups);
}
$parentTemplates = $this->findParentTemplates($parentTemplateIds);
$macros = $this->readHostMacroRepository->findByHostId($hostId);
return AddHostFactory::createResponse($host, $hostCategories, $parentTemplates, $macros, $hostGroups);
}
/**
* @param array<string,Macro> $macros
*
* @throws \Throwable
*
* @return array<string,Macro>
*/
private function retrieveMacrosVaultValues(array $macros): array
{
$updatedMacros = [];
foreach ($macros as $key => $macro) {
if ($macro->isPassword() === false) {
$updatedMacros[$key] = $macro;
continue;
}
$vaultData = $this->readVaultRepository->findFromPath($macro->getValue());
$vaultKey = '_HOST' . $macro->getName();
if (isset($vaultData[$vaultKey])) {
$inVaultMacro = new Macro($macro->getId(), $macro->getOwnerId(), $macro->getName(), $vaultData[$vaultKey]);
$inVaultMacro->setDescription($macro->getDescription());
$inVaultMacro->setIsPassword($macro->isPassword());
$inVaultMacro->setOrder($macro->getOrder());
$updatedMacros[$key] = $inVaultMacro;
}
}
return $updatedMacros;
}
}
| 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/Application/UseCase/AddHost/HostMacroFactory.php | centreon/src/Core/Host/Application/UseCase/AddHost/HostMacroFactory.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\Application\UseCase\AddHost;
use Assert\AssertionFailedException;
use Core\Macro\Domain\Model\Macro;
final class HostMacroFactory
{
/**
* Create macros object from the request data.
* Use direct and inherited macros to retrieve value of macro with isPassword when not provided in dto.
*
* @param array{id?:int|null,name:string,value:string|null,is_password:bool,description:string|null} $data
* @param int $hostId
* @param array<string,Macro> $inheritedMacros
*
* @throws \Throwable
* @throws AssertionFailedException
*
* @return Macro
*/
public static function create(
array $data,
int $hostId,
array $inheritedMacros,
): Macro {
$macroName = mb_strtoupper($data['name']);
$macroValue = $data['value'] ?? '';
$passwordHasNotChanged = ($data['value'] === null) && $data['is_password'];
if ($passwordHasNotChanged) {
$macroValue = match (true) {
// retrieve actual password value
isset($inheritedMacros[$macroName]) => $inheritedMacros[$macroName]->getValue(),
default => $macroValue,
};
}
$macro = new Macro(
$data['id'] ?? null,
$hostId,
$data['name'],
$macroValue,
);
$macro->setIsPassword($data['is_password']);
$macro->setDescription($data['description'] ?? '');
return $macro;
}
}
| 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/Application/UseCase/AddHost/AddHostValidation.php | centreon/src/Core/Host/Application/UseCase/AddHost/AddHostValidation.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\Application\UseCase\AddHost;
use Centreon\Domain\Common\Assertion\Assertion;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Command\Application\Repository\ReadCommandRepositoryInterface;
use Core\Command\Domain\Model\CommandType;
use Core\Host\Application\Exception\HostException;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
use Core\Host\Domain\Model\Host;
use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface;
use Core\HostGroup\Application\Repository\ReadHostGroupRepositoryInterface;
use Core\HostSeverity\Application\Repository\ReadHostSeverityRepositoryInterface;
use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface;
use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Core\MonitoringServer\Model\MonitoringServer;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Core\TimePeriod\Application\Repository\ReadTimePeriodRepositoryInterface;
use Core\Timezone\Application\Repository\ReadTimezoneRepositoryInterface;
use Core\ViewImg\Application\Repository\ReadViewImgRepositoryInterface;
class AddHostValidation
{
use LoggerTrait;
/** @var AccessGroup[] */
public array $accessGroups = [];
public function __construct(
private readonly ReadHostRepositoryInterface $readHostRepository,
private readonly ReadMonitoringServerRepositoryInterface $readMonitoringServerRepository,
private readonly ReadHostTemplateRepositoryInterface $readHostTemplateRepository,
private readonly ReadViewImgRepositoryInterface $readViewImgRepository,
private readonly ReadTimePeriodRepositoryInterface $readTimePeriodRepository,
private readonly ReadHostSeverityRepositoryInterface $readHostSeverityRepository,
private readonly ReadTimezoneRepositoryInterface $readTimezoneRepository,
private readonly ReadCommandRepositoryInterface $readCommandRepository,
private readonly ReadHostCategoryRepositoryInterface $readHostCategoryRepository,
private readonly ReadHostGroupRepositoryInterface $readHostGroupRepository,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly ContactInterface $user,
) {
}
/**
* Assert name is not already used.
*
* @param string $name
*
* @throws HostException|\Throwable
*/
public function assertIsValidName(string $name): void
{
Assertion::unauthorizedCharacters(
$name,
MonitoringServer::ILLEGAL_CHARACTERS,
'Host::name'
);
$formattedName = Host::formatName($name);
if ($this->readHostRepository->existsByName($formattedName)) {
$this->error('Host name already exists', compact('name', 'formattedName'));
throw HostException::nameAlreadyExists($formattedName, $name);
}
if (str_starts_with($name, '_Module_')) {
throw HostException::nameIsInvalid();
}
}
/**
* Assert monitoring server ID is valid.
*
* @param int $monitoringServerId
*
* @throws HostException|\Throwable
*/
public function assertIsValidMonitoringServer(int $monitoringServerId): void
{
if ($monitoringServerId !== null) {
$exists = ($this->accessGroups === [])
? $this->readMonitoringServerRepository->exists($monitoringServerId)
: $this->readMonitoringServerRepository->existsByAccessGroups($monitoringServerId, $this->accessGroups);
if (! $exists) {
$this->error('Monitoring server does not exist', ['monitoringServerId' => $monitoringServerId]);
throw HostException::idDoesNotExist('monitoringServerId', $monitoringServerId);
}
}
}
/**
* Assert icon ID is valid.
*
* @param ?int $iconId
*
* @throws HostException|\Throwable
*/
public function assertIsValidIcon(?int $iconId): void
{
if ($iconId !== null && $this->readViewImgRepository->existsOne($iconId) === false) {
$this->error('Icon does not exist', ['icon_id' => $iconId]);
throw HostException::idDoesNotExist('iconId', $iconId);
}
}
/**
* Assert time period ID is valid.
*
* @param ?int $timePeriodId
* @param ?string $propertyName
*
* @throws HostException|\Throwable
*/
public function assertIsValidTimePeriod(?int $timePeriodId, ?string $propertyName = null): void
{
if ($timePeriodId !== null && $this->readTimePeriodRepository->exists($timePeriodId) === false) {
$this->error('Time period does not exist', ['time_period_id' => $timePeriodId]);
throw HostException::idDoesNotExist($propertyName ?? 'timePeriodId', $timePeriodId);
}
}
/**
* Assert host severity ID is valid.
*
* @param ?int $severityId
*
* @throws HostException|\Throwable
*/
public function assertIsValidSeverity(?int $severityId): void
{
if ($severityId !== null) {
$exists = ($this->accessGroups === [])
? $this->readHostSeverityRepository->exists($severityId)
: $this->readHostSeverityRepository->existsByAccessGroups($severityId, $this->accessGroups);
if (! $exists) {
$this->error('Host severity does not exist', ['severity_id' => $severityId]);
throw HostException::idDoesNotExist('severityId', $severityId);
}
}
}
/**
* Assert timezone ID is valid.
*
* @param ?int $timezoneId
*
* @throws HostException
*/
public function assertIsValidTimezone(?int $timezoneId): void
{
if ($timezoneId !== null && $this->readTimezoneRepository->exists($timezoneId) === false) {
$this->error('Timezone does not exist', ['timezone_id' => $timezoneId]);
throw HostException::idDoesNotExist('timezoneId', $timezoneId);
}
}
/**
* Assert command ID is valid.
*
* @param ?int $commandId
* @param ?CommandType $commandType
* @param ?string $propertyName
*
* @throws HostException
*/
public function assertIsValidCommand(
?int $commandId,
?CommandType $commandType = null,
?string $propertyName = null,
): void {
if ($commandId === null) {
return;
}
if ($commandType === null && $this->readCommandRepository->exists($commandId) === false) {
$this->error('Command does not exist', ['command_id' => $commandId]);
throw HostException::idDoesNotExist($propertyName ?? 'commandId', $commandId);
}
if (
$commandType !== null
&& $this->readCommandRepository->existsByIdAndCommandType($commandId, $commandType) === false
) {
$this->error('Command does not exist', ['command_id' => $commandId, 'command_type' => $commandType]);
throw HostException::idDoesNotExist($propertyName ?? 'commandId', $commandId);
}
}
/**
* Assert category IDs are valid.
*
* @param int[] $categoryIds
*
* @throws HostException
* @throws \Throwable
*/
public function assertAreValidCategories(array $categoryIds): void
{
if ($this->user->isAdmin()) {
$validCategoryIds = $this->readHostCategoryRepository->exist($categoryIds);
} else {
$accessGroups = $this->readAccessGroupRepository->findByContact($this->user);
$validCategoryIds = $this->readHostCategoryRepository->existByAccessGroups($categoryIds, $accessGroups);
}
if ([] !== ($invalidIds = array_diff($categoryIds, $validCategoryIds))) {
throw HostException::idsDoNotExist('categories', $invalidIds);
}
}
/**
* Assert group IDs are valid.
*
* @param int[] $groupIds
*
* @throws HostException
* @throws \Throwable
*/
public function assertAreValidGroups(array $groupIds): void
{
if ($this->user->isAdmin()) {
$validGroupIds = $this->readHostGroupRepository->exist($groupIds);
} else {
$accessGroups = $this->readAccessGroupRepository->findByContact($this->user);
$validGroupIds = $this->readHostGroupRepository->existByAccessGroups($groupIds, $accessGroups);
}
if ([] !== ($invalidIds = array_diff($groupIds, $validGroupIds))) {
throw HostException::idsDoNotExist('groups', $invalidIds);
}
}
/**
* Assert template IDs are valid.
*
* @param int[] $templateIds
* @param int $hostTemplateId
*
* @throws HostException
* @throws \Throwable
*/
public function assertAreValidTemplates(array $templateIds, int $hostTemplateId): void
{
if (in_array($hostTemplateId, $templateIds, true)) {
throw HostException::circularTemplateInheritance();
}
$validTemplateIds = $this->readHostTemplateRepository->exist($templateIds);
if ([] !== ($invalidIds = array_diff($templateIds, $validTemplateIds))) {
throw HostException::idsDoNotExist('templates', $invalidIds);
}
}
}
| 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/Application/UseCase/DeleteHost/DeleteHost.php | centreon/src/Core/Host/Application/UseCase/DeleteHost/DeleteHost.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\Application\UseCase\DeleteHost;
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\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Application\Common\UseCase\PresenterInterface;
use Core\Common\Application\Repository\WriteVaultRepositoryInterface;
use Core\Common\Application\UseCase\VaultTrait;
use Core\Common\Infrastructure\Repository\AbstractVaultRepository;
use Core\Host\Application\Exception\HostException;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
use Core\Host\Application\Repository\WriteHostRepositoryInterface;
use Core\Host\Domain\Model\Host;
use Core\Macro\Application\Repository\ReadHostMacroRepositoryInterface;
use Core\Macro\Application\Repository\ReadServiceMacroRepositoryInterface;
use Core\MonitoringServer\Application\Repository\WriteMonitoringServerRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Core\Service\Application\Repository\ReadServiceRepositoryInterface;
use Core\Service\Application\Repository\WriteServiceRepositoryInterface;
final class DeleteHost
{
use LoggerTrait;
use VaultTrait;
public function __construct(
private readonly ReadHostRepositoryInterface $readHostRepository,
private readonly WriteHostRepositoryInterface $writeHostRepository,
private readonly ReadServiceRepositoryInterface $readServiceRepository,
private readonly WriteServiceRepositoryInterface $writeServiceRepository,
private readonly ContactInterface $contact,
private readonly DataStorageEngineInterface $storageEngine,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly WriteMonitoringServerRepositoryInterface $writeMonitoringServerRepository,
private readonly WriteVaultRepositoryInterface $writeVaultRepository,
private readonly ReadHostMacroRepositoryInterface $readHostMacroRepository,
private readonly ReadServiceMacroRepositoryInterface $readServiceMacroRepository,
) {
}
/**
* @param int $hostId
* @param PresenterInterface $presenter
*/
public function __invoke(int $hostId, PresenterInterface $presenter): void
{
try {
$this->info('Use case: DeleteHost');
if (! $this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_HOSTS_WRITE)) {
$this->error(
"User doesn't have sufficient rights to delete a host",
['user_id' => $this->contact->getId(), 'host_id' => $hostId]
);
$presenter->setResponseStatus(
new ForbiddenResponse(HostException::deleteNotAllowed())
);
return;
}
if (! $this->hostExists($hostId) || ($host = $this->readHostRepository->findById($hostId)) === null) {
$this->error('Host not found', ['host_id' => $hostId]);
$presenter->setResponseStatus(new NotFoundResponse('Host'));
return;
}
$this->deleteHost($host);
$presenter->setResponseStatus(new NoContentResponse());
} catch (\Throwable $ex) {
$presenter->setResponseStatus(new ErrorResponse(HostException::errorWhileDeleting($ex)));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
}
}
/**
* @param Host $host
*
* @throws \Throwable
*/
private function deleteHost(Host $host): void
{
$this->debug('Start transaction');
$this->storageEngine->startTransaction();
$isVaultActive = $this->writeVaultRepository->isVaultConfigured();
try {
// Only delete services that are exclusively linked to this host
$serviceIds = $this->readServiceRepository->findServiceIdsExclusivelyLinkedToHostId($host->getId());
if ($serviceIds !== []) {
$this->info('Services to delete (exclusively linked to this host)', ['user_id' => $this->contact->getId(), 'services' => $serviceIds]);
if ($isVaultActive) {
$serviceUuids = $this->retrieveServiceUuidsFromVault($serviceIds);
$this->writeVaultRepository->setCustomPath(AbstractVaultRepository::SERVICE_VAULT_PATH);
foreach ($serviceUuids as $serviceUuid) {
$this->writeVaultRepository->delete($serviceUuid);
}
}
$this->writeServiceRepository->deleteByIds(...$serviceIds);
} else {
$this->info('No services to delete', ['user_id' => $this->contact->getId()]);
}
$this->info('Host to delete', ['user_id' => $this->contact->getId(), 'host_id' => $host->getId()]);
if ($isVaultActive) {
$this->retrieveHostUuidFromVault($host);
if ($this->uuid !== null) {
$this->writeVaultRepository->setCustomPath(AbstractVaultRepository::HOST_VAULT_PATH);
$this->writeVaultRepository->delete($this->uuid);
}
}
$this->writeHostRepository->deleteById($host->getId());
$this->writeMonitoringServerRepository->notifyConfigurationChange($host->getMonitoringServerId());
$this->debug('Commit transaction');
$this->storageEngine->commitTransaction();
} catch (\Throwable $ex) {
$this->debug('Rollback transaction');
$this->storageEngine->rollbackTransaction();
throw $ex;
}
}
/**
* Indicates whether the host can be deleted according to ACLs.
*
* @param int $hostId
*
* @throws \Throwable
*
* @return bool
*/
private function hostExists(int $hostId): bool
{
if ($this->contact->isAdmin()) {
$this->info('Admin user', ['user_id' => $this->contact->getId()]);
return $this->readHostRepository->exists($hostId);
}
$accessGroups = $this->readAccessGroupRepository->findByContact($this->contact);
$this->info(
'Non-admin user',
[
'user_id' => $this->contact->getId(),
'access_groups' => array_map(fn (AccessGroup $accessGroup) => $accessGroup->getId(), $accessGroups)],
);
return $this->readHostRepository->existsByAccessGroups($hostId, $accessGroups);
}
/**
* @param Host $host
*
* @throws \Throwable
*/
private function retrieveHostUuidFromVault(Host $host): void
{
$this->uuid = $this->getUuidFromPath($host->getSnmpCommunity());
if ($this->uuid === null) {
$macros = $this->readHostMacroRepository->findByHostId($host->getId());
foreach ($macros as $macro) {
if (
$macro->isPassword() === true
&& null !== ($this->uuid = $this->getUuidFromPath($macro->getValue()))
) {
break;
}
}
}
}
/**
* @param int[] $serviceIds
*
* @throws \Throwable
*
* @return string[]
*/
private function retrieveServiceUuidsFromVault(array $serviceIds): array
{
$uuids = [];
$macros = $this->readServiceMacroRepository->findByServiceIds(...$serviceIds);
foreach ($macros as $macro) {
if (
$macro->isPassword() === true
&& null !== ($uuid = $this->getUuidFromPath($macro->getValue()))
) {
$uuids[] = $uuid;
}
}
return array_unique($uuids);
}
}
| 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/Application/UseCase/FindRealTimeHostStatusesCount/FindRealTimeHostStatusesCountResponse.php | centreon/src/Core/Host/Application/UseCase/FindRealTimeHostStatusesCount/FindRealTimeHostStatusesCountResponse.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\Application\UseCase\FindRealTimeHostStatusesCount;
final class FindRealTimeHostStatusesCountResponse
{
public int $upStatuses = 0;
public int $downStatuses = 0;
public int $unreachableStatuses = 0;
public int $pendingStatuses = 0;
public int $total = 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/Host/Application/UseCase/FindRealTimeHostStatusesCount/FindRealTimeHostStatusesCountPresenterInterface.php | centreon/src/Core/Host/Application/UseCase/FindRealTimeHostStatusesCount/FindRealTimeHostStatusesCountPresenterInterface.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\Application\UseCase\FindRealTimeHostStatusesCount;
use Core\Application\Common\UseCase\PresenterInterface;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface FindRealTimeHostStatusesCountPresenterInterface extends PresenterInterface
{
/**
* @param FindRealTimeHostStatusesCountResponse|ResponseStatusInterface $response
*/
public function presentResponse(FindRealTimeHostStatusesCountResponse|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/Host/Application/UseCase/FindRealTimeHostStatusesCount/FindRealTimeHostStatusesCount.php | centreon/src/Core/Host/Application/UseCase/FindRealTimeHostStatusesCount/FindRealTimeHostStatusesCount.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\Application\UseCase\FindRealTimeHostStatusesCount;
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\Host\Application\Exception\HostException;
use Core\Host\Application\Repository\ReadRealTimeHostRepositoryInterface;
use Core\Host\Domain\Model\HostStatusesCount;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
final class FindRealTimeHostStatusesCount
{
use LoggerTrait;
public const AUTHORIZED_ACL_GROUPS = ['customer_admin_acl'];
/**
* @param ContactInterface $user
* @param ReadRealTimeHostRepositoryInterface $repository
* @param ReadAccessGroupRepositoryInterface $accessGroupRepository
* @param RequestParametersInterface $requestParameters
*/
public function __construct(
private readonly ContactInterface $user,
private readonly ReadRealTimeHostRepositoryInterface $repository,
private readonly ReadAccessGroupRepositoryInterface $accessGroupRepository,
private readonly RequestParametersInterface $requestParameters,
) {
}
/**
* @param FindRealTimeHostStatusesCountPresenterInterface $presenter
*/
public function __invoke(FindRealTimeHostStatusesCountPresenterInterface $presenter): void
{
try {
if (! $this->isAuthorized()) {
$this->error(
"User doesn't have sufficient rights to get services information",
[
'user_id' => $this->user->getId(),
]
);
$presenter->presentResponse(
new ForbiddenResponse(HostException::accessNotAllowedForRealTime()->getMessage())
);
return;
}
$statuses = $this->isUserAdmin()
? $this->findStatusesCountAsAdmin()
: $this->findStatusesCountAsUser();
$this->info('Find host statuses distribution');
$this->debug(
'Find host statuses distribution',
[
'user_id' => $this->user->getId(),
'request_parameters' => $this->requestParameters->toArray(),
]
);
$presenter->presentResponse($this->createResponse($statuses));
} catch (RequestParametersTranslatorException $ex) {
$presenter->presentResponse(new ErrorResponse($ex->getMessage()));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (\Throwable $exception) {
$presenter->presentResponse(new ErrorResponse(HostException::errorWhileRetrievingHostStatusesCount()));
$this->error($exception->getMessage(), ['trace' => $exception->getTraceAsString()]);
}
}
/**
* @return HostStatusesCount
*/
private function findStatusesCountAsAdmin(): HostStatusesCount
{
return $this->repository->findStatusesByRequestParameters($this->requestParameters);
}
/**
* @return bool
*/
private function isAuthorized(): bool
{
return $this->user->isAdmin()
|| (
$this->user->hasTopologyRole(Contact::ROLE_MONITORING_RESOURCES_STATUS_RW)
|| $this->user->hasTopologyRole(Contact::ROLE_MONITORING_RW)
);
}
/**
* @return HostStatusesCount
*/
private function findStatusesCountAsUser(): HostStatusesCount
{
$accessGroupIds = array_map(
static fn (AccessGroup $accessGroup): int => $accessGroup->getId(),
$this->accessGroupRepository->findByContact($this->user)
);
return $this->repository->findStatusesByRequestParametersAndAccessGroupIds($this->requestParameters, $accessGroupIds);
}
/**
* @param HostStatusesCount $status
*
* @return FindRealTimeHostStatusesCountResponse
*/
private function createResponse(HostStatusesCount $status): FindRealTimeHostStatusesCountResponse
{
$response = new FindRealTimeHostStatusesCountResponse();
$response->upStatuses = $status->getTotalUp();
$response->downStatuses = $status->getTotalDown();
$response->unreachableStatuses = $status->getTotalUnreachable();
$response->pendingStatuses = $status->getTotalPending();
$response->total = $status->getTotal();
return $response;
}
/**
* Indicates if the current user is admin or not (cloud + onPremise context).
*
* @return bool
*/
private function isUserAdmin(): bool
{
if ($this->user->isAdmin()) {
return true;
}
$userAccessGroupNames = array_map(
static fn (AccessGroup $accessGroup): string => $accessGroup->getName(),
$this->accessGroupRepository->findByContact($this->user)
);
return ! empty(array_intersect($userAccessGroupNames, self::AUTHORIZED_ACL_GROUPS));
}
}
| 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/Application/UseCase/FindHosts/FindHosts.php | centreon/src/Core/Host/Application/UseCase/FindHosts/FindHosts.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\Application\UseCase\FindHosts;
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\Host\Application\Exception\HostException;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
use Core\Host\Domain\Model\SmallHost;
use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface;
use Core\HostGroup\Application\Repository\ReadHostGroupRepositoryInterface;
use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
final class FindHosts
{
use LoggerTrait;
public function __construct(
private readonly RequestParametersInterface $requestParameters,
private readonly ContactInterface $user,
private readonly ReadHostRepositoryInterface $hostRepository,
private readonly ReadAccessGroupRepositoryInterface $accessGroupRepository,
private readonly ReadHostCategoryRepositoryInterface $categoryRepository,
private readonly ReadHostTemplateRepositoryInterface $hostTemplateRepository,
private readonly ReadHostGroupRepositoryInterface $groupRepository,
private readonly AdminResolver $adminResolver,
) {
}
public function __invoke(FindHostsPresenterInterface $presenter): void
{
try {
if (! $this->canAccessToListing()) {
$this->error(
"User doesn't have sufficient rights to list hosts",
['user_id' => $this->user->getId()]
);
$presenter->presentResponse(
new ForbiddenResponse(HostException::listingNotAllowed())
);
return;
}
$hosts = $this->adminResolver->isAdmin($this->user)
? $this->hostRepository->findByRequestParameters($this->requestParameters)
: $this->hostRepository->findByRequestParametersAndAccessGroups(
$this->requestParameters,
$this->accessGroupRepository->findByContact($this->user)
);
$presenter->presentResponse($this->createResponse($hosts));
} catch (RequestParametersTranslatorException $ex) {
$presenter->presentResponse(new ErrorResponse($ex->getMessage()));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (\Throwable $ex) {
$presenter->presentResponse(new ErrorResponse(HostException::errorWhileSearchingForHosts($ex)));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
}
}
private function canAccessToListing(): bool
{
return $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_HOSTS_READ)
|| $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_HOSTS_WRITE);
}
/**
* @param SmallHost[] $hosts
*
* @throws \Throwable
*
* @return FindHostsResponse
*/
private function createResponse(array $hosts): FindHostsResponse
{
$response = new FindHostsResponse();
foreach ($hosts as $host) {
$dto = new HostDto(
$host->getId(),
(string) $host->getName(),
$host->getAlias()?->value,
(string) $host->getIpAddress(),
new SimpleDto(
$host->getMonitoringServer()->getId(),
$host->getMonitoringServer()->getName() ?? '',
),
$host->getNormalCheckInterval(),
$host->getRetryCheckInterval(),
$host->isActivated(),
);
if ($host->getSeverity() !== null) {
$dto->severity = new SimpleDto(
$host->getSeverity()->getId(),
$host->getSeverity()->getName() ?? '',
);
}
if ($host->getNotificationTimePeriod() !== null) {
$dto->notificationTimeperiod = new SimpleDto(
$host->getNotificationTimePeriod()->getId(),
$host->getNotificationTimePeriod()->getName() ?? '',
);
}
if ($host->getCheckTimePeriod() !== null) {
$dto->checkTimeperiod = new SimpleDto(
$host->getCheckTimePeriod()->getId(),
$host->getCheckTimePeriod()->getName() ?? '',
);
}
$hostTemplates = $this->hostTemplateRepository->findByIds(...$host->getTemplateIds());
foreach ($hostTemplates as $template) {
$dto->templateParents[] = new SimpleDto($template->getId(), $template->getName());
}
$groups = $this->groupRepository->findByIds(...$host->getGroupIds());
foreach ($groups as $group) {
$dto->groups[] = new SimpleDto($group->getId(), $group->getName());
}
$categories = $this->categoryRepository->findByIds(...$host->getCategoryIds());
foreach ($categories as $category) {
$dto->categories[] = new SimpleDto($category->getId(), $category->getName());
}
$response->hostDto[] = $dto;
}
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/Host/Application/UseCase/FindHosts/SimpleDto.php | centreon/src/Core/Host/Application/UseCase/FindHosts/SimpleDto.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\Application\UseCase\FindHosts;
final class SimpleDto
{
public function __construct(public int $id, public string $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/Host/Application/UseCase/FindHosts/HostDto.php | centreon/src/Core/Host/Application/UseCase/FindHosts/HostDto.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\Application\UseCase\FindHosts;
final class HostDto
{
/** @var SimpleDto[] */
public array $templateParents = [];
public ?SimpleDto $notificationTimeperiod = null;
public ?SimpleDto $checkTimeperiod = null;
public ?SimpleDto $severity = null;
/** @var SimpleDto[] */
public array $categories = [];
/** @var SimpleDto[] */
public array $groups = [];
public function __construct(
public int $id,
public string $name,
public ?string $alias,
public string $ipAddress,
public SimpleDto $poller,
public ?int $normalCheckInterval,
public ?int $retryCheckInterval,
public bool $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/Host/Application/UseCase/FindHosts/FindHostsResponse.php | centreon/src/Core/Host/Application/UseCase/FindHosts/FindHostsResponse.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\Application\UseCase\FindHosts;
final class FindHostsResponse
{
/** @var HostDto[] */
public array $hostDto = [];
}
| 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/Application/UseCase/FindHosts/FindHostsPresenterInterface.php | centreon/src/Core/Host/Application/UseCase/FindHosts/FindHostsPresenterInterface.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\Application\UseCase\FindHosts;
use Core\Application\Common\UseCase\PresenterInterface;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface FindHostsPresenterInterface extends PresenterInterface
{
public function presentResponse(FindHostsResponse|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/Host/Application/UseCase/PartialUpdateHost/PartialUpdateHostRequest.php | centreon/src/Core/Host/Application/UseCase/PartialUpdateHost/PartialUpdateHostRequest.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\Application\UseCase\PartialUpdateHost;
use Core\Common\Application\Type\NoValue;
final class PartialUpdateHostRequest
{
/**
* @param NoValue|string $name
* @param NoValue|string $address
* @param NoValue|int $monitoringServerId
* @param NoValue|null|string $alias
* @param NoValue|null|string $snmpVersion
* @param NoValue|null|string $snmpCommunity
* @param NoValue|null|string $noteUrl
* @param NoValue|null|string $note
* @param NoValue|null|string $actionUrl
* @param NoValue|null|string $iconAlternative
* @param NoValue|null|string $comment
* @param NoValue|null|string $geoCoordinates
* @param NoValue|string[] $checkCommandArgs
* @param NoValue|string[] $eventHandlerCommandArgs
* @param NoValue|int $activeCheckEnabled
* @param NoValue|int $passiveCheckEnabled
* @param NoValue|int $notificationEnabled
* @param NoValue|int $freshnessChecked
* @param NoValue|int $flapDetectionEnabled
* @param NoValue|int $eventHandlerEnabled
* @param NoValue|null|int $timezoneId
* @param NoValue|null|int $severityId
* @param NoValue|null|int $checkCommandId
* @param NoValue|null|int $checkTimeperiodId
* @param NoValue|null|int $notificationTimeperiodId
* @param NoValue|null|int $eventHandlerCommandId
* @param NoValue|null|int $iconId
* @param NoValue|null|int $maxCheckAttempts
* @param NoValue|null|int $normalCheckInterval
* @param NoValue|null|int $retryCheckInterval
* @param NoValue|null|int $notificationOptions
* @param NoValue|null|int $notificationInterval
* @param NoValue|bool $addInheritedContactGroup
* @param NoValue|bool $addInheritedContact
* @param NoValue|null|int $firstNotificationDelay
* @param NoValue|null|int $recoveryNotificationDelay
* @param NoValue|null|int $acknowledgementTimeout
* @param NoValue|null|int $freshnessThreshold
* @param NoValue|null|int $lowFlapThreshold
* @param NoValue|null|int $highFlapThreshold
* @param NoValue|int[] $categories
* @param NoValue|int[] $groups
* @param NoValue|int[] $templates
* @param NoValue|array<array{name:string,value:null|string,is_password:bool,description:null|string}> $macros
* @param NoValue|bool $isActivated
*/
public function __construct(
public NoValue|string $name = new NoValue(),
public NoValue|string $address = new NoValue(),
public NoValue|int $monitoringServerId = new NoValue(),
public NoValue|null|string $alias = new NoValue(),
public NoValue|null|string $snmpVersion = new NoValue(),
public NoValue|null|string $snmpCommunity = new NoValue(),
public NoValue|null|string $noteUrl = new NoValue(),
public NoValue|null|string $note = new NoValue(),
public NoValue|null|string $actionUrl = new NoValue(),
public NoValue|null|string $iconAlternative = new NoValue(),
public NoValue|null|string $comment = new NoValue(),
public NoValue|null|string $geoCoordinates = new NoValue(),
public NoValue|array $checkCommandArgs = new NoValue(),
public NoValue|array $eventHandlerCommandArgs = new NoValue(),
public NoValue|int $activeCheckEnabled = new NoValue(),
public NoValue|int $passiveCheckEnabled = new NoValue(),
public NoValue|int $notificationEnabled = new NoValue(),
public NoValue|int $freshnessChecked = new NoValue(),
public NoValue|int $flapDetectionEnabled = new NoValue(),
public NoValue|int $eventHandlerEnabled = new NoValue(),
public NoValue|null|int $timezoneId = new NoValue(),
public NoValue|null|int $severityId = new NoValue(),
public NoValue|null|int $checkCommandId = new NoValue(),
public NoValue|null|int $checkTimeperiodId = new NoValue(),
public NoValue|null|int $notificationTimeperiodId = new NoValue(),
public NoValue|null|int $eventHandlerCommandId = new NoValue(),
public NoValue|null|int $iconId = new NoValue(),
public NoValue|null|int $maxCheckAttempts = new NoValue(),
public NoValue|null|int $normalCheckInterval = new NoValue(),
public NoValue|null|int $retryCheckInterval = new NoValue(),
public NoValue|null|int $notificationOptions = new NoValue(),
public NoValue|null|int $notificationInterval = new NoValue(),
public NoValue|bool $addInheritedContactGroup = new NoValue(),
public NoValue|bool $addInheritedContact = new NoValue(),
public NoValue|null|int $firstNotificationDelay = new NoValue(),
public NoValue|null|int $recoveryNotificationDelay = new NoValue(),
public NoValue|null|int $acknowledgementTimeout = new NoValue(),
public NoValue|null|int $freshnessThreshold = new NoValue(),
public NoValue|null|int $lowFlapThreshold = new NoValue(),
public NoValue|null|int $highFlapThreshold = new NoValue(),
public NoValue|array $categories = new NoValue(),
public NoValue|array $groups = new NoValue(),
public NoValue|array $templates = new NoValue(),
public NoValue|array $macros = new NoValue(),
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/Host/Application/UseCase/PartialUpdateHost/PartialUpdateHost.php | centreon/src/Core/Host/Application/UseCase/PartialUpdateHost/PartialUpdateHost.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\Application\UseCase\PartialUpdateHost;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Option\OptionService;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Core\Application\Common\UseCase\ConflictResponse;
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\Application\Common\UseCase\PresenterInterface;
use Core\Command\Domain\Model\CommandType;
use Core\CommandMacro\Application\Repository\ReadCommandMacroRepositoryInterface;
use Core\CommandMacro\Domain\Model\CommandMacro;
use Core\CommandMacro\Domain\Model\CommandMacroType;
use Core\Common\Application\Converter\YesNoDefaultConverter;
use Core\Common\Application\Repository\ReadVaultRepositoryInterface;
use Core\Common\Application\Repository\WriteVaultRepositoryInterface;
use Core\Common\Application\Type\NoValue;
use Core\Common\Application\UseCase\VaultTrait;
use Core\Common\Infrastructure\Repository\AbstractVaultRepository;
use Core\Domain\Common\GeoCoords;
use Core\Host\Application\Converter\HostEventConverter;
use Core\Host\Application\Exception\HostException;
use Core\Host\Application\InheritanceManager;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
use Core\Host\Application\Repository\WriteHostRepositoryInterface;
use Core\Host\Domain\Model\Host;
use Core\Host\Domain\Model\SnmpVersion;
use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface;
use Core\HostCategory\Application\Repository\WriteHostCategoryRepositoryInterface;
use Core\HostCategory\Domain\Model\HostCategory;
use Core\HostGroup\Application\Repository\ReadHostGroupRepositoryInterface;
use Core\HostGroup\Application\Repository\WriteHostGroupRepositoryInterface;
use Core\HostGroup\Domain\Model\HostGroup;
use Core\Macro\Application\Repository\ReadHostMacroRepositoryInterface;
use Core\Macro\Application\Repository\WriteHostMacroRepositoryInterface;
use Core\Macro\Domain\Model\Macro;
use Core\Macro\Domain\Model\MacroDifference;
use Core\Macro\Domain\Model\MacroManager;
use Core\MonitoringServer\Application\Repository\WriteMonitoringServerRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Core\Security\Vault\Domain\Model\VaultConfiguration;
use Utility\Difference\BasicDifference;
final class PartialUpdateHost
{
use LoggerTrait;
use VaultTrait;
private const VERTICAL_INHERITANCE_MODE = 1;
/** @var AccessGroup[] */
private array $accessGroups = [];
public function __construct(
private readonly WriteHostRepositoryInterface $writeHostRepository,
private readonly ReadHostRepositoryInterface $readHostRepository,
private readonly WriteMonitoringServerRepositoryInterface $writeMonitoringServerRepository,
private readonly ReadHostCategoryRepositoryInterface $readHostCategoryRepository,
private readonly ReadHostGroupRepositoryInterface $readHostGroupRepository,
private readonly WriteHostCategoryRepositoryInterface $writeHostCategoryRepository,
private readonly WriteHostGroupRepositoryInterface $writeHostGroupRepository,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly ReadHostMacroRepositoryInterface $readHostMacroRepository,
private readonly ReadCommandMacroRepositoryInterface $readCommandMacroRepository,
private readonly WriteHostMacroRepositoryInterface $writeHostMacroRepository,
private readonly DataStorageEngineInterface $dataStorageEngine,
private readonly OptionService $optionService,
private readonly ContactInterface $user,
private readonly PartialUpdateHostValidation $validation,
private readonly WriteVaultRepositoryInterface $writeVaultRepository,
private readonly ReadVaultRepositoryInterface $readVaultRepository,
) {
$this->writeVaultRepository->setCustomPath(AbstractVaultRepository::HOST_VAULT_PATH);
}
/**
* @param PartialUpdateHostRequest $request
* @param PresenterInterface $presenter
* @param int $hostId
*/
public function __invoke(
PartialUpdateHostRequest $request,
PresenterInterface $presenter,
int $hostId,
): void {
try {
if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_HOSTS_WRITE)) {
$this->error(
"User doesn't have sufficient rights to edit a host",
['user_id' => $this->user->getId()]
);
$presenter->setResponseStatus(
new ForbiddenResponse(HostException::editNotAllowed())
);
return;
}
if (! $this->user->isAdmin()) {
$this->accessGroups = $this->readAccessGroupRepository->findByContact($this->user);
$this->validation->accessGroups = $this->accessGroups;
}
if (
(
! $this->user->isAdmin()
&& ! $this->readHostRepository->existsByAccessGroups($hostId, $this->accessGroups)
)
|| ! ($host = $this->readHostRepository->findById($hostId))
) {
$this->error(
'Host not found',
['host_id' => $hostId]
);
$presenter->setResponseStatus(new NotFoundResponse('Host'));
return;
}
$this->updatePropertiesInTransaction($request, $host);
$presenter->setResponseStatus(new NoContentResponse());
} catch (HostException $ex) {
$presenter->setResponseStatus(
match ($ex->getCode()) {
HostException::CODE_CONFLICT => new ConflictResponse($ex),
default => new ErrorResponse($ex),
}
);
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (AssertionFailedException $ex) {
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (\Throwable $ex) {
$presenter->setResponseStatus(new ErrorResponse(HostException::editHost()));
$this->error((string) $ex);
}
}
private function updatePropertiesInTransaction(PartialUpdateHostRequest $request, Host $host): void
{
try {
$this->dataStorageEngine->startTransaction();
if ($this->writeVaultRepository->isVaultConfigured()) {
$this->retrieveHostUuidFromVault($host);
}
$previousMonitoringServer = $host->getMonitoringServerId();
$this->updateHost($request, $host);
$this->updateHostCategories($request, $host);
$this->updateHostGroups($request, $host);
$this->updateParentTemplates($request, $host);
// Note: parent templates must be updated before macros for macro inheritance resolution
$this->updateMacros($request, $host);
$this->writeMonitoringServerRepository->notifyConfigurationChange($host->getMonitoringServerId());
if ($previousMonitoringServer !== $host->getMonitoringServerId()) {
// Monitoring server has changed, notify previous monitoring server of configuration changes.
$this->writeMonitoringServerRepository->notifyConfigurationChange($previousMonitoringServer);
}
$this->dataStorageEngine->commitTransaction();
} catch (\Throwable $ex) {
$this->error("Rollback of 'PartialUpdateHost' transaction", ['trace' => $ex->getTraceAsString()]);
$this->dataStorageEngine->rollbackTransaction();
throw $ex;
}
}
/**
* @param PartialUpdateHostRequest $dto
* @param Host $host
*
* @throws \Throwable|AssertionFailedException|HostException
*/
private function updateHost(PartialUpdateHostRequest $dto, Host $host): void
{
$this->info('PartialUpdateHost: update host', ['host_id' => $host->getId()]);
$inheritanceMode = $this->optionService->findSelectedOptions(['inheritance_mode']);
$inheritanceMode = isset($inheritanceMode[0])
? (int) $inheritanceMode[0]->getValue()
: null;
if (! $dto->name instanceof NoValue) {
$this->validation->assertIsValidName($dto->name, $host);
$host->setName($dto->name);
}
if (! $dto->address instanceof NoValue) {
$host->setAddress($dto->address);
}
if (! $dto->monitoringServerId instanceof NoValue) {
$this->validation->assertIsValidMonitoringServer($dto->monitoringServerId);
$host->setMonitoringServerId($dto->monitoringServerId);
}
if (! $dto->alias instanceof NoValue) {
$host->setAlias($dto->alias ?? '');
}
if (! $dto->noteUrl instanceof NoValue) {
$host->setNoteUrl($dto->noteUrl ?? '');
}
if (! $dto->note instanceof NoValue) {
$host->setNote($dto->note ?? '');
}
if (! $dto->actionUrl instanceof NoValue) {
$host->setActionUrl($dto->actionUrl ?? '');
}
if (! $dto->iconId instanceof NoValue) {
$this->validation->assertIsValidIcon($dto->iconId);
$host->setIconId($dto->iconId);
}
if (! $dto->iconAlternative instanceof NoValue) {
$host->setIconAlternative($dto->iconAlternative ?? '');
}
if (! $dto->comment instanceof NoValue) {
$host->setComment($dto->comment ?? '');
}
if (! $dto->checkCommandArgs instanceof NoValue) {
$host->setCheckCommandArgs($dto->checkCommandArgs);
}
if (! $dto->eventHandlerCommandArgs instanceof NoValue) {
$host->setEventHandlerCommandArgs($dto->eventHandlerCommandArgs);
}
if (! $dto->timezoneId instanceof NoValue) {
$this->validation->assertIsValidTimezone($dto->timezoneId);
$host->setTimezoneId($dto->timezoneId);
}
if (! $dto->severityId instanceof NoValue) {
$this->validation->assertIsValidSeverity($dto->severityId);
$host->setSeverityId($dto->severityId);
}
if (! $dto->checkCommandId instanceof NoValue) {
$this->validation->assertIsValidCommand($dto->checkCommandId, CommandType::Check, 'checkCommandId');
$host->setCheckCommandId($dto->checkCommandId);
}
if (! $dto->checkTimeperiodId instanceof NoValue) {
$this->validation->assertIsValidTimePeriod($dto->checkTimeperiodId, 'checkTimeperiodId');
$host->setCheckTimeperiodId($dto->checkTimeperiodId);
}
if (! $dto->notificationTimeperiodId instanceof NoValue) {
$this->validation->assertIsValidTimePeriod($dto->notificationTimeperiodId, 'notificationTimeperiodId');
$host->setNotificationTimeperiodId($dto->notificationTimeperiodId);
}
if (! $dto->eventHandlerCommandId instanceof NoValue) {
$this->validation->assertIsValidCommand($dto->eventHandlerCommandId, null, 'eventHandlerCommandId');
$host->setEventHandlerCommandId($dto->eventHandlerCommandId);
}
if (! $dto->maxCheckAttempts instanceof NoValue) {
$host->setMaxCheckAttempts($dto->maxCheckAttempts);
}
if (! $dto->normalCheckInterval instanceof NoValue) {
$host->setNormalCheckInterval($dto->normalCheckInterval);
}
if (! $dto->retryCheckInterval instanceof NoValue) {
$host->setRetryCheckInterval($dto->retryCheckInterval);
}
if (! $dto->notificationInterval instanceof NoValue) {
$host->setNotificationInterval($dto->notificationInterval);
}
if (! $dto->firstNotificationDelay instanceof NoValue) {
$host->setFirstNotificationDelay($dto->firstNotificationDelay);
}
if (! $dto->recoveryNotificationDelay instanceof NoValue) {
$host->setRecoveryNotificationDelay($dto->recoveryNotificationDelay);
}
if (! $dto->acknowledgementTimeout instanceof NoValue) {
$host->setAcknowledgementTimeout($dto->acknowledgementTimeout);
}
if (! $dto->freshnessThreshold instanceof NoValue) {
$host->setFreshnessThreshold($dto->freshnessThreshold);
}
if (! $dto->lowFlapThreshold instanceof NoValue) {
$host->setLowFlapThreshold($dto->lowFlapThreshold);
}
if (! $dto->highFlapThreshold instanceof NoValue) {
$host->setHighFlapThreshold($dto->highFlapThreshold);
}
if (! $dto->isActivated instanceof NoValue) {
$host->setIsActivated($dto->isActivated);
}
if (! $dto->activeCheckEnabled instanceof NoValue) {
$host->setActiveCheckEnabled(YesNoDefaultConverter::fromScalar($dto->activeCheckEnabled));
}
if (! $dto->passiveCheckEnabled instanceof NoValue) {
$host->setPassiveCheckEnabled(YesNoDefaultConverter::fromScalar($dto->passiveCheckEnabled));
}
if (! $dto->notificationEnabled instanceof NoValue) {
$host->setNotificationEnabled(YesNoDefaultConverter::fromScalar($dto->notificationEnabled));
}
if (! $dto->freshnessChecked instanceof NoValue) {
$host->setFreshnessChecked(YesNoDefaultConverter::fromScalar($dto->freshnessChecked));
}
if (! $dto->flapDetectionEnabled instanceof NoValue) {
$host->setFlapDetectionEnabled(YesNoDefaultConverter::fromScalar($dto->flapDetectionEnabled));
}
if (! $dto->eventHandlerEnabled instanceof NoValue) {
$host->setEventHandlerEnabled(YesNoDefaultConverter::fromScalar($dto->eventHandlerEnabled));
}
if (! $dto->snmpVersion instanceof NoValue) {
$host->setSnmpVersion(
$dto->snmpVersion === '' || $dto->snmpVersion === null
? null
: SnmpVersion::from($dto->snmpVersion)
);
}
if (! $dto->geoCoordinates instanceof NoValue) {
$host->setGeoCoordinates(
$dto->geoCoordinates === '' || $dto->geoCoordinates === null
? null
: GeoCoords::fromString($dto->geoCoordinates)
);
}
if (! $dto->notificationOptions instanceof NoValue) {
$host->setNotificationOptions(
$dto->notificationOptions === null
? []
: HostEventConverter::fromBitFlag($dto->notificationOptions)
);
}
if (! $dto->addInheritedContactGroup instanceof NoValue) {
$host->setAddInheritedContactGroup(
$inheritanceMode === self::VERTICAL_INHERITANCE_MODE ? $dto->addInheritedContactGroup : false
);
}
if (! $dto->addInheritedContact instanceof NoValue) {
$host->setAddInheritedContact(
$inheritanceMode === self::VERTICAL_INHERITANCE_MODE ? $dto->addInheritedContact : false
);
}
$this->updateSnmpCommunity($host, $dto->snmpCommunity);
$this->writeHostRepository->update($host);
}
/**
* @param PartialUpdateHostRequest $dto
* @param Host $host
*
* @throws \Throwable|AssertionFailedException|HostException
*/
private function updateHostCategories(PartialUpdateHostRequest $dto, Host $host): void
{
$this->info(
'PartialUpdateHost: update categories',
['host_id' => $host->getId(), 'categories' => $dto->categories]
);
if ($dto->categories instanceof NoValue) {
$this->info('Categories not provided, nothing to update');
return;
}
$categoryIds = array_unique($dto->categories);
$this->validation->assertAreValidCategories($categoryIds);
if ($this->user->isAdmin()) {
$originalCategories = $this->readHostCategoryRepository->findByHost($host->getId());
} else {
$originalCategories = $this->readHostCategoryRepository->findByHostAndAccessGroups(
$host->getId(),
$this->accessGroups
);
}
$originalCategoryIds = array_map(
static fn (HostCategory $category): int => $category->getId(),
$originalCategories
);
$categoryDiff = new BasicDifference($originalCategoryIds, $categoryIds);
$addedCategories = $categoryDiff->getAdded();
$removedCategories = $categoryDiff->getRemoved();
$this->writeHostCategoryRepository->linkToHost($host->getId(), $addedCategories);
$this->writeHostCategoryRepository->unlinkFromHost($host->getId(), $removedCategories);
}
/**
* @param PartialUpdateHostRequest $dto
* @param Host $host
*
* @throws HostException
* @throws \Throwable
*/
private function updateHostGroups(PartialUpdateHostRequest $dto, Host $host): void
{
$this->info(
'PartialUpdateHost: update groups',
['host_id' => $host->getId(), 'groups' => $dto->groups]
);
if ($dto->groups instanceof NoValue) {
$this->info('Groups not provided, nothing to update');
return;
}
$groupIds = array_unique($dto->groups);
$this->validation->assertAreValidGroups($groupIds);
if ($this->user->isAdmin()) {
$originalGroups = $this->readHostGroupRepository->findByHost($host->getId());
} else {
$originalGroups = $this->readHostGroupRepository->findByHostAndAccessGroups(
$host->getId(),
$this->accessGroups
);
}
$originalGroupIds = array_map(
static fn (HostGroup $group): int => $group->getId(),
$originalGroups
);
$groupDiff = new BasicDifference($originalGroupIds, $groupIds);
$addedGroups = $groupDiff->getAdded();
$removedGroups = $groupDiff->getRemoved();
$this->writeHostGroupRepository->linkToHost($host->getId(), $addedGroups);
$this->writeHostGroupRepository->unlinkFromHost($host->getId(), $removedGroups);
}
/**
* @param PartialUpdateHostRequest $dto
* @param Host $host
*
* @throws \Throwable|HostException
*/
private function updateParentTemplates(PartialUpdateHostRequest $dto, Host $host): void
{
$this->info(
'PartialUpdateHost: Update parent templates',
['host_id' => $host->getId(), 'template_ids' => $dto->templates]
);
if ($dto->templates instanceof NoValue) {
$this->info('Parent templates not provided, nothing to update');
return;
}
/** @var int[] $parentTemplateIds */
$parentTemplateIds = array_unique($dto->templates);
$this->validation->assertAreValidTemplates($parentTemplateIds, $host->getId());
$this->info('Remove parent templates from a host', ['host_id' => $host->getId()]);
$this->writeHostRepository->deleteParents($host->getId());
foreach ($parentTemplateIds as $order => $templateId) {
$this->info('Add a parent template to a host', [
'host_id' => $host->getId(), 'parent_id' => $templateId, 'order' => $order,
]);
$this->writeHostRepository->addParent($host->getId(), $templateId, $order);
}
}
/**
* @param PartialUpdateHostRequest $dto
* @param Host $host
*
* @throws \Throwable
*/
private function updateMacros(PartialUpdateHostRequest $dto, Host $host): void
{
$this->debug(
'PartialUpdateHost: update macros',
['host_id' => $host->getId(), 'macros' => $dto->macros]
);
if ($dto->macros instanceof NoValue) {
$this->debug('Macros not provided, nothing to update');
return;
}
/**
* @var array<string,Macro> $directMacros
* @var array<string,Macro> $inheritedMacros
* @var array<string,CommandMacro> $commandMacros
*/
[$directMacros, $inheritedMacros, $commandMacros] = $this->findOriginalMacros($host);
$macros = [];
foreach ($dto->macros as $data) {
$macro = HostMacroFactory::create($data, $host->getId(), $directMacros, $inheritedMacros);
$macros[$macro->getName()] = $macro;
}
$macrosDiff = new MacroDifference();
$macrosDiff->compute($directMacros, $inheritedMacros, $commandMacros, $macros);
MacroManager::setOrder($macrosDiff, $macros, $directMacros);
foreach ($macrosDiff->removedMacros as $macro) {
$this->updateMacroInVault($macro, 'DELETE');
$this->writeHostMacroRepository->delete($macro);
}
foreach ($macrosDiff->updatedMacros as $macro) {
$macro = $this->updateMacroInVault($macro, 'INSERT');
$this->writeHostMacroRepository->update($macro);
}
foreach ($macrosDiff->addedMacros as $macro) {
if ($macro->getDescription() === '') {
$macro->setDescription(
isset($commandMacros[$macro->getName()])
? $commandMacros[$macro->getName()]->getDescription()
: ''
);
}
$macro = $this->updateMacroInVault($macro, 'INSERT');
$this->writeHostMacroRepository->add($macro);
}
}
/**
* Find macros of a host:
* - macros linked directly,
* - macros linked through template inheritance,
* - macros linked through command inheritance.
*
* @param Host $host
*
* @throws \Throwable
*
* @return array{
* array<string,Macro>,
* array<string,Macro>,
* array<string,CommandMacro>
* }
*/
private function findOriginalMacros(Host $host): array
{
$templateParents = $this->readHostRepository->findParents($host->getId());
$inheritanceLine = InheritanceManager::findInheritanceLine($host->getId(), $templateParents);
$existingHostMacros = $this->readHostMacroRepository->findByHostIds(array_merge([$host->getId()], $inheritanceLine));
[$directMacros, $inheritedMacros] = Macro::resolveInheritance(
$existingHostMacros,
$inheritanceLine,
$host->getId()
);
/** @var array<string,CommandMacro> $commandMacros */
$commandMacros = [];
if ($host->getCheckCommandId() !== null) {
$existingCommandMacros = $this->readCommandMacroRepository->findByCommandIdAndType(
$host->getCheckCommandId(),
CommandMacroType::Host
);
$commandMacros = MacroManager::resolveInheritanceForCommandMacro($existingCommandMacros);
}
return [
$this->writeVaultRepository->isVaultConfigured()
? $this->retrieveMacrosVaultValues($directMacros)
: $directMacros,
$this->writeVaultRepository->isVaultConfigured()
? $this->retrieveMacrosVaultValues($inheritedMacros)
: $inheritedMacros,
$commandMacros,
];
}
/**
* @param Host $host
*
* @throws \Throwable
*/
private function retrieveHostUuidFromVault(Host $host): void
{
$this->uuid = $this->getUuidFromPath($host->getSnmpCommunity());
if ($this->uuid === null) {
$macros = $this->readHostMacroRepository->findByHostId($host->getId());
foreach ($macros as $macro) {
if (
$macro->isPassword() === true
&& null !== ($this->uuid = $this->getUuidFromPath($macro->getValue()))
) {
break;
}
}
}
}
/**
* Upsert or delete macro for vault storage and return macro with updated value (aka vaultPath).
*
* @param Macro $macro
* @param string $action
*
* @throws \Throwable
*
* @return Macro
*/
private function updateMacroInVault(Macro $macro, string $action): Macro
{
if ($this->writeVaultRepository->isVaultConfigured() && $macro->isPassword() === true) {
$macroPrefixedName = '_HOST' . $macro->getName();
$vaultPaths = $this->writeVaultRepository->upsert(
$this->uuid ?? null,
$action === 'INSERT' ? [$macroPrefixedName => $macro->getValue()] : [],
$action === 'DELETE' ? [$macroPrefixedName => $macro->getValue()] : [],
);
// No need to update the macro if it is being deleted
if ($action === 'DELETE') {
return $macro;
}
$this->uuid ??= $this->getUuidFromPath($vaultPaths[$macroPrefixedName]);
$inVaultMacro = new Macro($macro->getId(), $macro->getOwnerId(), $macro->getName(), $vaultPaths[$macroPrefixedName]);
$inVaultMacro->setDescription($macro->getDescription());
$inVaultMacro->setIsPassword($macro->isPassword());
$inVaultMacro->setOrder($macro->getOrder());
return $inVaultMacro;
}
return $macro;
}
/**
* @param array<string,Macro> $macros
*
* @throws \Throwable
*
* @return array<string,Macro>
*/
private function retrieveMacrosVaultValues(array $macros): array
{
$updatedMacros = [];
foreach ($macros as $key => $macro) {
if ($macro->isPassword() === false || $this->isAVaultPath($macro->getValue()) === false) {
$updatedMacros[$key] = $macro;
continue;
}
$vaultData = $this->readVaultRepository->findFromPath($macro->getValue());
$vaultKey = '_HOST' . $macro->getName();
if (isset($vaultData[$vaultKey])) {
$inVaultMacro = new Macro($macro->getId(), $macro->getOwnerId(), $macro->getName(), $vaultData[$vaultKey]);
$inVaultMacro->setDescription($macro->getDescription());
$inVaultMacro->setIsPassword($macro->isPassword());
$inVaultMacro->setOrder($macro->getOrder());
$updatedMacros[$key] = $inVaultMacro;
}
}
return $updatedMacros;
}
/**
* Update SNMP community for a host, handling vault storage and clearing logic.
*
* @param Host $host
* @param NoValue|string|null $snmpCommunity
*
* @throws \Throwable
*/
private function updateSnmpCommunity(Host $host, NoValue|string|null $snmpCommunity): void
{
if ($snmpCommunity instanceof NoValue) {
return;
}
// If vault is not configured, just set the value directly
if (! $this->writeVaultRepository->isVaultConfigured()) {
$host->setSnmpCommunity($snmpCommunity ?? '');
return;
}
// If the value is already a vault path, do nothing
if ($this->isAVaultPath($snmpCommunity ?? '')) {
return;
}
// If the current value is a vault path and we want to clear it
if ($this->isAVaultPath($host->getSnmpCommunity()) && empty($snmpCommunity)) {
$this->writeVaultRepository->upsert(
uuid: $this->getUuidFromPath($host->getSnmpCommunity()),
deletes: [VaultConfiguration::HOST_SNMP_COMMUNITY_KEY => $snmpCommunity ?? '']
);
$host->setSnmpCommunity($snmpCommunity ?? '');
return;
}
// If the new value is empty, do nothing
if (empty($snmpCommunity)) {
return;
}
// Otherwise, store in vault and update host
$vaultPaths = $this->writeVaultRepository->upsert(
uuid: $this->uuid ?? null,
inserts: [VaultConfiguration::HOST_SNMP_COMMUNITY_KEY => $snmpCommunity],
);
$this->uuid ??= $this->getUuidFromPath($vaultPaths[VaultConfiguration::HOST_SNMP_COMMUNITY_KEY]);
$host->setSnmpCommunity($vaultPaths[VaultConfiguration::HOST_SNMP_COMMUNITY_KEY]);
}
}
| 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/Application/UseCase/PartialUpdateHost/PartialUpdateHostValidation.php | centreon/src/Core/Host/Application/UseCase/PartialUpdateHost/PartialUpdateHostValidation.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\Application\UseCase\PartialUpdateHost;
use Centreon\Domain\Common\Assertion\Assertion;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Command\Application\Repository\ReadCommandRepositoryInterface;
use Core\Command\Domain\Model\CommandType;
use Core\Host\Application\Exception\HostException;
use Core\Host\Application\InheritanceManager;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
use Core\Host\Domain\Model\Host;
use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface;
use Core\HostGroup\Application\Repository\ReadHostGroupRepositoryInterface;
use Core\HostSeverity\Application\Repository\ReadHostSeverityRepositoryInterface;
use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface;
use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Core\MonitoringServer\Model\MonitoringServer;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Core\TimePeriod\Application\Repository\ReadTimePeriodRepositoryInterface;
use Core\Timezone\Application\Repository\ReadTimezoneRepositoryInterface;
use Core\ViewImg\Application\Repository\ReadViewImgRepositoryInterface;
class PartialUpdateHostValidation
{
use LoggerTrait;
/**
* @param ReadHostRepositoryInterface $readHostRepository
* @param ReadMonitoringServerRepositoryInterface $readMonitoringServerRepository
* @param ReadHostTemplateRepositoryInterface $readHostTemplateRepository
* @param ReadViewImgRepositoryInterface $readViewImgRepository
* @param ReadTimePeriodRepositoryInterface $readTimePeriodRepository
* @param ReadHostSeverityRepositoryInterface $readHostSeverityRepository
* @param ReadTimezoneRepositoryInterface $readTimezoneRepository
* @param ReadCommandRepositoryInterface $readCommandRepository
* @param ReadHostCategoryRepositoryInterface $readHostCategoryRepository
* @param ReadHostGroupRepositoryInterface $readHostGroupRepository
* @param InheritanceManager $inheritanceManager
* @param ContactInterface $user
* @param AccessGroup[] $accessGroups
*/
public function __construct(
private readonly ReadHostRepositoryInterface $readHostRepository,
private readonly ReadMonitoringServerRepositoryInterface $readMonitoringServerRepository,
private readonly ReadHostTemplateRepositoryInterface $readHostTemplateRepository,
private readonly ReadViewImgRepositoryInterface $readViewImgRepository,
private readonly ReadTimePeriodRepositoryInterface $readTimePeriodRepository,
private readonly ReadHostSeverityRepositoryInterface $readHostSeverityRepository,
private readonly ReadTimezoneRepositoryInterface $readTimezoneRepository,
private readonly ReadCommandRepositoryInterface $readCommandRepository,
private readonly ReadHostCategoryRepositoryInterface $readHostCategoryRepository,
private readonly ReadHostGroupRepositoryInterface $readHostGroupRepository,
private readonly InheritanceManager $inheritanceManager,
private readonly ContactInterface $user,
public array $accessGroups = [],
) {
}
/**
* Assert name is not already used.
*
* @param string $name
* @param Host $host
*
* @throws HostException|\Throwable
*/
public function assertIsValidName(string $name, Host $host): void
{
Assertion::unauthorizedCharacters(
$name,
MonitoringServer::ILLEGAL_CHARACTERS,
'Host::name'
);
if ($host->isNameIdentical($name)) {
return;
}
$formattedName = Host::formatName($name);
if ($this->readHostRepository->existsByName($formattedName)) {
$this->error('Host name already exists', compact('name', 'formattedName'));
throw HostException::nameAlreadyExists($formattedName, $name);
}
if (str_starts_with($name, '_Module_')) {
throw HostException::nameIsInvalid();
}
}
/**
* Assert monitoring server ID is valid.
*
* @param int $monitoringServerId
*
* @throws HostException|\Throwable
*/
public function assertIsValidMonitoringServer(int $monitoringServerId): void
{
if ($monitoringServerId !== null) {
$exists = ($this->accessGroups === [])
? $this->readMonitoringServerRepository->exists($monitoringServerId)
: $this->readMonitoringServerRepository->existsByAccessGroups($monitoringServerId, $this->accessGroups);
if (! $exists) {
$this->error('Monitoring server does not exist', ['monitoringServerId' => $monitoringServerId]);
throw HostException::idDoesNotExist('monitoringServerId', $monitoringServerId);
}
}
}
/**
* Assert icon ID is valid.
*
* @param ?int $iconId
*
* @throws HostException|\Throwable
*/
public function assertIsValidIcon(?int $iconId): void
{
if ($iconId !== null && $this->readViewImgRepository->existsOne($iconId) === false) {
$this->error('Icon does not exist', ['icon_id' => $iconId]);
throw HostException::idDoesNotExist('iconId', $iconId);
}
}
/**
* Assert time period ID is valid.
*
* @param ?int $timePeriodId
* @param ?string $propertyName
*
* @throws HostException|\Throwable
*/
public function assertIsValidTimePeriod(?int $timePeriodId, ?string $propertyName = null): void
{
if ($timePeriodId !== null && $this->readTimePeriodRepository->exists($timePeriodId) === false) {
$this->error('Time period does not exist', ['time_period_id' => $timePeriodId]);
throw HostException::idDoesNotExist($propertyName ?? 'timePeriodId', $timePeriodId);
}
}
/**
* Assert host severity ID is valid.
*
* @param ?int $severityId
*
* @throws HostException|\Throwable
*/
public function assertIsValidSeverity(?int $severityId): void
{
if ($severityId !== null) {
$exists = ($this->accessGroups === [])
? $this->readHostSeverityRepository->exists($severityId)
: $this->readHostSeverityRepository->existsByAccessGroups($severityId, $this->accessGroups);
if (! $exists) {
$this->error('Host severity does not exist', ['severity_id' => $severityId]);
throw HostException::idDoesNotExist('severityId', $severityId);
}
}
}
/**
* Assert timezone ID is valid.
*
* @param ?int $timezoneId
*
* @throws HostException
*/
public function assertIsValidTimezone(?int $timezoneId): void
{
if ($timezoneId !== null && $this->readTimezoneRepository->exists($timezoneId) === false) {
$this->error('Timezone does not exist', ['timezone_id' => $timezoneId]);
throw HostException::idDoesNotExist('timezoneId', $timezoneId);
}
}
/**
* Assert command ID is valid.
*
* @param ?int $commandId
* @param ?CommandType $commandType
* @param ?string $propertyName
*
* @throws HostException
*/
public function assertIsValidCommand(
?int $commandId,
?CommandType $commandType = null,
?string $propertyName = null,
): void {
if ($commandId === null) {
return;
}
if ($commandType === null && $this->readCommandRepository->exists($commandId) === false) {
$this->error('Command does not exist', ['command_id' => $commandId]);
throw HostException::idDoesNotExist($propertyName ?? 'commandId', $commandId);
}
if (
$commandType !== null
&& $this->readCommandRepository->existsByIdAndCommandType($commandId, $commandType) === false
) {
$this->error('Command does not exist', ['command_id' => $commandId, 'command_type' => $commandType]);
throw HostException::idDoesNotExist($propertyName ?? 'commandId', $commandId);
}
}
/**
* Assert category IDs are valid.
*
* @param int[] $categoryIds
*
* @throws HostException
* @throws \Throwable
*/
public function assertAreValidCategories(array $categoryIds): void
{
if ($this->user->isAdmin()) {
$validCategoryIds = $this->readHostCategoryRepository->exist($categoryIds);
} else {
$validCategoryIds = $this->readHostCategoryRepository->existByAccessGroups($categoryIds, $this->accessGroups);
}
if ([] !== ($invalidIds = array_diff($categoryIds, $validCategoryIds))) {
throw HostException::idsDoNotExist('categories', $invalidIds);
}
}
/**
* Assert group IDs are valid.
*
* @param int[] $groupIds
*
* @throws HostException
* @throws \Throwable
*/
public function assertAreValidGroups(array $groupIds): void
{
if ($this->user->isAdmin()) {
$validGroupIds = $this->readHostGroupRepository->exist($groupIds);
} else {
$validGroupIds = $this->readHostGroupRepository->existByAccessGroups($groupIds, $this->accessGroups);
}
if ([] !== ($invalidIds = array_diff($groupIds, $validGroupIds))) {
throw HostException::idsDoNotExist('groups', $invalidIds);
}
}
/**
* Assert template IDs are valid.
*
* @param int[] $templateIds
* @param int $hostId
*
* @throws HostException
* @throws \Throwable
*/
public function assertAreValidTemplates(array $templateIds, int $hostId): void
{
if ($templateIds === []) {
return;
}
$validTemplateIds = $this->readHostTemplateRepository->exist($templateIds);
if ([] !== ($invalidIds = array_diff($templateIds, $validTemplateIds))) {
throw HostException::idsDoNotExist('templates', $invalidIds);
}
if (
in_array($hostId, $templateIds, true)
|| $this->inheritanceManager->isValidInheritanceTree($hostId, $templateIds) === false
) {
throw HostException::circularTemplateInheritance();
}
}
}
| 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/Application/UseCase/PartialUpdateHost/HostMacroFactory.php | centreon/src/Core/Host/Application/UseCase/PartialUpdateHost/HostMacroFactory.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\Application\UseCase\PartialUpdateHost;
use Assert\AssertionFailedException;
use Core\Macro\Domain\Model\Macro;
final class HostMacroFactory
{
/**
* Create macros object from the request data.
* Use direct and inherited macros to retrieve value of macro with isPassword when not provided in dto.
*
* @param array{name:string,value:string|null,is_password:bool,description:string|null} $data
* @param int $hostId
* @param array<string,Macro> $directMacros
* @param array<string,Macro> $inheritedMacros
*
* @throws \Throwable
* @throws AssertionFailedException
*
* @return Macro
*/
public static function create(
array $data,
int $hostId,
array $directMacros,
array $inheritedMacros,
): Macro {
$macroName = mb_strtoupper($data['name']);
$macroValue = $data['value'] ?? '';
$passwordHasNotChanged = ($data['value'] === null) && $data['is_password'];
if ($passwordHasNotChanged) {
$macroValue = match (true) {
// retrieve actual password value
isset($directMacros[$macroName]) => $directMacros[$macroName]->getValue(),
isset($inheritedMacros[$macroName]) => $inheritedMacros[$macroName]->getValue(),
default => $macroValue,
};
}
$macro = new Macro(
$data['id'] ?? null,
$hostId,
$data['name'],
$macroValue,
);
$macro->setIsPassword($data['is_password']);
$macro->setDescription($data['description'] ?? '');
return $macro;
}
}
| 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/Application/Exception/HostException.php | centreon/src/Core/Host/Application/Exception/HostException.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\Application\Exception;
class HostException extends \Exception
{
public const CODE_CONFLICT = 1;
/**
* @return self
*/
public static function accessNotAllowedForRealTime(): self
{
return new self(_('You are not allowed to access hosts in the real time context'));
}
/**
* @return self
*/
public static function addHost(): self
{
return new self(_('Error while adding a host'));
}
/**
* @return self
*/
public static function editHost(): self
{
return new self(_('Error while updating a host'));
}
/**
* @return self
*/
public static function deleteNotAllowed(): self
{
return new self(_('You are not allowed to delete a host'));
}
/**
* @return self
*/
public static function editNotAllowed(): self
{
return new self(_('You are not allowed to edit a host'));
}
/**
* @param \Throwable $ex
*
* @return self
*/
public static function linkHostCategories(\Throwable $ex): self
{
return new self(_('Error while linking host categories to a host'), 0, $ex);
}
/**
* @return self
*/
public static function addNotAllowed(): self
{
return new self(_('You are not allowed to add hosts'));
}
/**
* @param int $hostId
*
* @return self
*/
public static function notFound(int $hostId): self
{
return new self(sprintf(_('Host #%d not found'), $hostId));
}
/**
* @param string $propertyName
* @param int $propertyValue
*
* @return self
*/
public static function idDoesNotExist(string $propertyName, int $propertyValue): self
{
return new self(
sprintf(_("The %s with value '%d' does not exist"), $propertyName, $propertyValue),
self::CODE_CONFLICT
);
}
/**
* @param string $propertyName
* @param int[] $propertyValues
*
* @return self
*/
public static function idsDoNotExist(string $propertyName, array $propertyValues): self
{
return new self(
sprintf(
_("The %s does not exist with ID(s) '%s'"),
$propertyName,
implode(',', $propertyValues)
),
self::CODE_CONFLICT
);
}
/**
* @return self
*/
public static function listingNotAllowed(): self
{
return new self(_('You are not allowed to list hosts'));
}
/**
* @param string $formattedName
* @param string $originalName
*
* @return self
*/
public static function nameAlreadyExists(string $formattedName, string $originalName = 'undefined'): self
{
return new self(
sprintf(_('The name %s (original name: %s) already exists'), $formattedName, $originalName),
self::CODE_CONFLICT
);
}
/**
* @return self
*/
public static function nameIsInvalid(): self
{
return new self(
_("Host name should not start with '_Module_'"),
self::CODE_CONFLICT
);
}
/**
* @return self
*/
public static function errorWhileRetrievingObject(): self
{
return new self(_('Error while retrieving a host'));
}
/**
* @return self
*/
public static function circularTemplateInheritance(): self
{
return new self(_('Circular inheritance not allowed'), self::CODE_CONFLICT);
}
/**
* @param \Throwable $ex
*
* @return self
*/
public static function errorWhileDeleting(\Throwable $ex): self
{
return new self(_('Error while deleting the host'), 0, $ex);
}
/**
* @param \Throwable $ex
*
* @return self
*/
public static function errorWhileSearchingForHosts(\Throwable $ex): self
{
return new self(_('Error while searching for host configurations'));
}
/**
* @return HostException
*/
public static function errorWhileRetrievingHostStatusesCount(): self
{
return new self(_('Error while retrieving host statuses distribution'));
}
}
| 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/Application/Converter/HostEventConverter.php | centreon/src/Core/Host/Application/Converter/HostEventConverter.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\Application\Converter;
use Core\Host\Domain\Model\HostEvent;
/**
* This class purpose is to allow convertion from the legacy host event enum to a string.
*/
class HostEventConverter
{
public const MAX_BITFLAG = 0b11111;
private const CASE_NONE_AS_STR = 'n';
private const CASE_DOWN_AS_STR = 'd';
private const CASE_UNREACHABLE_AS_STR = 'u';
private const CASE_RECOVERY_AS_STR = 'r';
private const CASE_FLAPPING_AS_STR = 'f';
private const CASE_DOWNTIME_SCHEDULED_AS_STR = 's';
private const CASE_NONE_AS_BIT = 0b00000;
private const CASE_DOWN_AS_BIT = 0b00001;
private const CASE_UNREACHABLE_AS_BIT = 0b00010;
private const CASE_RECOVERY_AS_BIT = 0b00100;
private const CASE_FLAPPING_AS_BIT = 0b01000;
private const CASE_DOWNTIME_SCHEDULED_AS_BIT = 0b10000;
/**
* Convert an array of HostEvent to a string.
* ex: [HostEvent::Down, HostEvent::Unreachable] => 'd,u'.
*
* @param HostEvent[] $events
*
* @return string
*/
public static function toString(array $events): string
{
$eventsAsBitmask = [];
foreach ($events as $event) {
$eventsAsBitmask[] = match ($event) {
HostEvent::None => self::CASE_NONE_AS_STR,
HostEvent::Down => self::CASE_DOWN_AS_STR,
HostEvent::Unreachable => self::CASE_UNREACHABLE_AS_STR,
HostEvent::Recovery => self::CASE_RECOVERY_AS_STR,
HostEvent::Flapping => self::CASE_FLAPPING_AS_STR,
HostEvent::DowntimeScheduled => self::CASE_DOWNTIME_SCHEDULED_AS_STR,
};
}
return implode(',', array_unique($eventsAsBitmask));
}
/**
* Convert a string to an array of HostEvent.
* ex: 'd,u' => [HostEvent::Down, HostEvent::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_NONE_AS_STR => HostEvent::None,
self::CASE_DOWN_AS_STR => HostEvent::Down,
self::CASE_UNREACHABLE_AS_STR => HostEvent::Unreachable,
self::CASE_RECOVERY_AS_STR => HostEvent::Recovery,
self::CASE_FLAPPING_AS_STR => HostEvent::Flapping,
self::CASE_DOWNTIME_SCHEDULED_AS_STR => HostEvent::DowntimeScheduled,
default => null,
};
}
return array_values(array_filter($events));
}
/**
* Convert a HostEvent into bitFlag.
*
* @param HostEvent $event
*
* @return int
*/
public static function toBit(HostEvent $event): int
{
return match ($event) {
HostEvent::None => self::CASE_NONE_AS_BIT,
HostEvent::Down => self::CASE_DOWN_AS_BIT,
HostEvent::Unreachable => self::CASE_UNREACHABLE_AS_BIT,
HostEvent::Recovery => self::CASE_RECOVERY_AS_BIT,
HostEvent::Flapping => self::CASE_FLAPPING_AS_BIT,
HostEvent::DowntimeScheduled => self::CASE_DOWNTIME_SCHEDULED_AS_BIT,
};
}
/**
* Convert a bitFlag into an array of HostEvent.
*
* @param ?int $bitFlag
*
* @throws \Throwable
*
* @return HostEvent[]
*/
public static function fromBitFlag(?int $bitFlag): array
{
if ($bitFlag > self::MAX_BITFLAG || $bitFlag < 0) {
throw new \ValueError("\"{$bitFlag}\" is not a valid value for enum HostEvent");
}
if ($bitFlag === self::CASE_NONE_AS_BIT) {
return [HostEvent::None];
}
$enums = [];
foreach (HostEvent::cases() as $enum) {
if ($bitFlag & self::toBit($enum)) {
$enums[] = $enum;
}
}
return $enums;
}
/**
* Convert an array of HostEvent into a bitFlag
* If the array contains HostEvent::None, an empty bitFlag will be returned
* If the array is empty, null is returned.
*
* @param HostEvent[] $enums
*
* @return ?int
*/
public static function toBitFlag(array $enums): ?int
{
if ($enums === []) {
return null;
}
$bitFlag = 0;
foreach ($enums as $event) {
// Value 0 is not a bit, we consider it resets the bitFlag
if (self::toBit($event) === 0) {
return 0;
}
$bitFlag |= self::toBit($event);
}
return $bitFlag;
}
}
| 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/Application/Repository/WriteHostRepositoryInterface.php | centreon/src/Core/Host/Application/Repository/WriteHostRepositoryInterface.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\Application\Repository;
use Core\Host\Domain\Model\Host;
use Core\Host\Domain\Model\NewHost;
interface WriteHostRepositoryInterface
{
/**
* Add host.
*
* @param NewHost $host
*
* @throws \Throwable
*
* @return int
*/
public function add(NewHost $host): int;
/**
* Update host.
*
* @param Host $host
*
* @throws \Throwable
*/
public function update(Host $host): void;
/**
* Link a parent template to a child host.
*
* @param int $childId host to be linked as a child
* @param int $parentId host template to be linked as a parent
* @param int $order order of inheritance of the parent
*
* @throws \Throwable
*/
public function addParent(int $childId, int $parentId, int $order): void;
/**
* Unlink parent templates from a child host.
*
* @param int $childId host to be unlinked as a child
*
* @throws \Throwable
*/
public function deleteParents(int $childId): void;
/**
* Delete a host by ID.
*
* @param int $hostId
*
* @throws \Throwable
*/
public function deleteById(int $hostId): 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/Host/Application/Repository/ReadHostRepositoryInterface.php | centreon/src/Core/Host/Application/Repository/ReadHostRepositoryInterface.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\Application\Repository;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Common\Domain\SimpleEntity;
use Core\Host\Domain\Model\Host;
use Core\Host\Domain\Model\HostNamesById;
use Core\Host\Domain\Model\SmallHost;
use Core\Host\Domain\Model\TinyHost;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
interface ReadHostRepositoryInterface
{
/**
* Determine if a host exists by its name.
* (include both host templates and hosts names).
*
* @param string $hostName
*
* @throws \Throwable
*
* @return bool
*/
public function existsByName(string $hostName): bool;
/**
* Find a host by its id.
*
* @param int $hostId
*
* @throws \Throwable
*
* @return ?Host
*/
public function findById(int $hostId): ?Host;
/**
* Find hosts by their id.
*
* @param list<int> $hostIds
*
* @throws \Throwable
*
* @return list<TinyHost>
*/
public function findByIds(array $hostIds): array;
/**
* Find hosts by their names.
*
* @param list<string> $hostNames
*
* @throws \Throwable
*
* @return list<TinyHost>
*/
public function findByNames(array $hostNames): array;
/**
* Find hosts based on query parameters.
*
* @param RequestParametersInterface $requestParameters
*
* @throws \Throwable
*
* @return SmallHost[]
*/
public function findByRequestParameters(RequestParametersInterface $requestParameters): array;
/**
* Find hosts based on query parameters and access groups.
* If the list of access groups is empty, no restrictions will be applied.
*
* @param RequestParametersInterface $requestParameters
* @param AccessGroup[] $accessGroups If the list is empty, no restrictions will be applied
*
* @throws \Throwable
*
* @return SmallHost[]
*/
public function findByRequestParametersAndAccessGroups(
RequestParametersInterface $requestParameters,
array $accessGroups,
): array;
/**
* Retrieve all parent template ids of a host.
*
* @param int $hostId
*
* @throws \Throwable
*
* @return array<array{parent_id:int,child_id:int,order:int}>
*/
public function findParents(int $hostId): array;
/**
* Indicates whether the host already exists.
*
* @param int $hostId
*
* @throws \Throwable
*
* @return bool
*/
public function exists(int $hostId): bool;
/**
* Indicates whether the hosts exist and return the ids found.
*
* @param int[] $hostIds
*
* @throws \Throwable
*
* @return int[]
*/
public function exist(array $hostIds): array;
/**
* Indicates whether the host already exists.
*
* @param int $hostId
* @param AccessGroup[] $accessGroups
*
* @throws \Throwable
*
* @return bool
*/
public function existsByAccessGroups(int $hostId, array $accessGroups): bool;
/**
* Find host names by their IDs.
*
* @param int[] $hostIds
*
* @throws \Throwable
*
* @return HostNamesById
*/
public function findNames(array $hostIds): HostNamesById;
/**
* Find all hosts.
*
* @throws \Throwable
*
* @return Host[]
*/
public function findAll(): array;
/**
* @param int $hostGroupId
*
* @throws \Throwable
*
* @return SimpleEntity[]
*/
public function findByHostGroup(int $hostGroupId): array;
/**
* @param int $hostGroupId
* @param AccessGroup[] $accessGroups
*
* @throws \Throwable
*
* @return SimpleEntity[]
*/
public function findByHostGroupAndAccessGroups(int $hostGroupId, array $accessGroups): 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/Host/Application/Repository/ReadRealTimeHostRepositoryInterface.php | centreon/src/Core/Host/Application/Repository/ReadRealTimeHostRepositoryInterface.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\Application\Repository;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Host\Domain\Model\HostStatusesCount;
interface ReadRealTimeHostRepositoryInterface
{
/**
* @param RequestParametersInterface $requestParameters
*
* @return HostStatusesCount
*/
public function findStatusesByRequestParameters(RequestParametersInterface $requestParameters): HostStatusesCount;
/**
* @param RequestParametersInterface $requestParameters
* @param int[] $accessGroupIds
*
* @return HostStatusesCount
*/
public function findStatusesByRequestParametersAndAccessGroupIds(
RequestParametersInterface $requestParameters,
array $accessGroupIds,
): HostStatusesCount;
}
| 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/Application/Repository/WriteRealTimeHostRepositoryInterface.php | centreon/src/Core/Host/Application/Repository/WriteRealTimeHostRepositoryInterface.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\Application\Repository;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
interface WriteRealTimeHostRepositoryInterface
{
/**
* Link host to Resource ACLs.
*
* @param int $hostId
* @param AccessGroup[] $accessGroups
*
* @throws \Throwable
*/
public function addHostToResourceAcls(int $hostId, array $accessGroups): 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/Host/Domain/Model/HostNamesById.php | centreon/src/Core/Host/Domain/Model/HostNamesById.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\Domain\Model;
use Core\Common\Domain\TrimmedString;
class HostNamesById
{
/** @var array<int,TrimmedString> */
private array $names = [];
public function __construct()
{
}
/**
* @param int $hostId
* @param TrimmedString $hostName
*/
public function addName(int $hostId, TrimmedString $hostName): void
{
$this->names[$hostId] = $hostName;
}
/**
* @param int $hostId
*
* @return null|string
*/
public function getName(int $hostId): ?string
{
return isset($this->names[$hostId]) ? $this->names[$hostId]->value : null;
}
/**
* @return array<int,TrimmedString>
*/
public function getNames(): array
{
return $this->names;
}
}
| 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/Domain/Model/HostStatusesCount.php | centreon/src/Core/Host/Domain/Model/HostStatusesCount.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\Domain\Model;
class HostStatusesCount
{
public const STATUS_UP = 0;
public const STATUS_DOWN = 1;
public const STATUS_UNREACHABLE = 2;
public const STATUS_PENDING = 4;
public function __construct(
private readonly int $totalUp,
private readonly int $totalDown,
private readonly int $totalUnreachable,
private readonly int $totalPending,
) {
}
public function getTotalPending(): int
{
return $this->totalPending;
}
public function getTotalUnreachable(): int
{
return $this->totalUnreachable;
}
public function getTotalDown(): int
{
return $this->totalDown;
}
public function getTotalUp(): int
{
return $this->totalUp;
}
public function getTotal(): int
{
return array_sum([$this->totalPending, $this->totalUp, $this->totalUnreachable, $this->totalDown]);
}
}
| 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/Domain/Model/SmallHost.php | centreon/src/Core/Host/Domain/Model/SmallHost.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\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Core\Common\Domain\SimpleEntity;
use Core\Common\Domain\TrimmedString;
class SmallHost
{
public const MAX_NAME_LENGTH = NewHost::MAX_NAME_LENGTH;
public const MAX_ADDRESS_LENGTH = NewHost::MAX_ADDRESS_LENGTH;
/** @var list<int> */
private array $categoryIds = [];
/** @var list<int> */
private array $groupIds = [];
/** @var list<int> */
private array $templateIds = [];
/**
* @param int $id
* @param TrimmedString $name
* @param ?TrimmedString $alias
* @param TrimmedString $ipAddress
* @param int|null $normalCheckInterval
* @param int|null $retryCheckInterval
* @param bool $isActivated
* @param SimpleEntity $monitoringServer
* @param SimpleEntity|null $checkTimePeriod
* @param SimpleEntity|null $notificationTimePeriod
* @param SimpleEntity|null $severity
*
* @throws AssertionFailedException
*/
public function __construct(
private readonly int $id,
private readonly TrimmedString $name,
private readonly ?TrimmedString $alias,
private readonly TrimmedString $ipAddress,
private readonly ?int $normalCheckInterval,
private readonly ?int $retryCheckInterval,
private readonly bool $isActivated,
private readonly SimpleEntity $monitoringServer,
private readonly ?SimpleEntity $checkTimePeriod,
private readonly ?SimpleEntity $notificationTimePeriod,
private readonly ?SimpleEntity $severity,
) {
$shortName = 'Host';
Assertion::positiveInt($id, "{$shortName}::id");
Assertion::notEmptyString($name->value, "{$shortName}::name");
Assertion::notEmptyString($ipAddress->value, "{$shortName}::ipAddress");
if ($normalCheckInterval !== null) {
Assertion::positiveInt($normalCheckInterval, "{$shortName}::checkInterval");
}
if ($retryCheckInterval !== null) {
Assertion::min($retryCheckInterval, 1, "{$shortName}::retryCheckInterval");
}
}
public function getId(): int
{
return $this->id;
}
public function getName(): TrimmedString
{
return $this->name;
}
public function getAlias(): ?TrimmedString
{
return $this->alias;
}
public function getIpAddress(): TrimmedString
{
return $this->ipAddress;
}
public function getNormalCheckInterval(): ?int
{
return $this->normalCheckInterval;
}
public function getRetryCheckInterval(): ?int
{
return $this->retryCheckInterval;
}
public function isActivated(): bool
{
return $this->isActivated;
}
public function getCheckTimePeriod(): ?SimpleEntity
{
return $this->checkTimePeriod;
}
public function getNotificationTimePeriod(): ?SimpleEntity
{
return $this->notificationTimePeriod;
}
public function getSeverity(): ?SimpleEntity
{
return $this->severity;
}
public function getMonitoringServer(): SimpleEntity
{
return $this->monitoringServer;
}
public function addCategoryId(int $categoryId): void
{
$this->categoryIds[] = $categoryId;
}
/**
* @return list<int>
*/
public function getCategoryIds(): array
{
return $this->categoryIds;
}
public function addGroupId(int $groupId): void
{
$this->groupIds[] = $groupId;
}
/**
* @return list<int>
*/
public function getGroupIds(): array
{
return $this->groupIds;
}
public function addTemplateId(int $templateId): void
{
$this->templateIds[] = $templateId;
}
/**
* @return list<int>
*/
public function getTemplateIds(): array
{
return $this->templateIds;
}
}
| 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/Domain/Model/HostEvent.php | centreon/src/Core/Host/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\Host\Domain\Model;
/**
* This enum is to be used to handle the legacy notification events for hosts and host templates.
*/
enum HostEvent
{
case Down;
case Unreachable;
case Recovery;
case Flapping;
case DowntimeScheduled;
case None;
}
| 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/Domain/Model/SnmpVersion.php | centreon/src/Core/Host/Domain/Model/SnmpVersion.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\Domain\Model;
/**
* This enum is to be used to handle snmp version options.
*/
enum SnmpVersion: string
{
case One = '1';
case Two = '2c';
case Three = '3';
}
| 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/Domain/Model/TinyHost.php | centreon/src/Core/Host/Domain/Model/TinyHost.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\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Core\Common\Domain\Comparable;
use Core\Common\Domain\Identifiable;
class TinyHost implements Comparable, Identifiable
{
/**
* @param int $id
* @param string $name
* @param ?string $alias
* @param int $monitoringServerId
*
* @throws AssertionFailedException
*/
public function __construct(
private readonly int $id,
private string $name,
private ?string $alias,
private readonly int $monitoringServerId,
) {
Assertion::positiveInt($this->id, 'Host::id');
$this->name = trim($this->name);
Assertion::notEmptyString($this->name, 'Host::name');
if ($this->alias !== null) {
$this->alias = trim($this->alias);
}
Assertion::positiveInt($this->id, 'Host::monitoringServerId');
}
public function getId(): int
{
return $this->id;
}
public function getName(): string
{
return $this->name;
}
public function getAlias(): ?string
{
return $this->alias;
}
public function getMonitoringServerId(): int
{
return $this->monitoringServerId;
}
public function isEqual(object $object): bool
{
return $object instanceof self && $object->getEqualityHash() === $this->getEqualityHash();
}
public function getEqualityHash(): string
{
return md5($this->getName());
}
}
| 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/Domain/Model/NewHost.php | centreon/src/Core/Host/Domain/Model/NewHost.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\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Core\Common\Domain\YesNoDefault;
use Core\Domain\Common\GeoCoords;
class NewHost
{
public const MAX_NAME_LENGTH = 200;
public const MAX_ALIAS_LENGTH = 200;
public const MAX_SNMP_COMMUNITY_LENGTH = 255;
public const MAX_ADDRESS_LENGTH = 255;
public const MAX_NOTE_URL_LENGTH = 65535;
public const MAX_NOTE_LENGTH = 65535;
public const MAX_ACTION_URL_LENGTH = 65535;
public const MAX_ICON_ALT_LENGTH = 200;
public const MAX_COMMENT_LENGTH = 65535;
/**
* @param int $monitoringServerId
* @param string $name
* @param string $address
* @param null|GeoCoords $geoCoordinates
* @param null|SnmpVersion $snmpVersion
* @param string $alias
* @param string $snmpCommunity
* @param string $noteUrl
* @param string $note
* @param string $actionUrl
* @param string $iconAlternative
* @param string $comment
* @param string[] $checkCommandArgs
* @param string[] $eventHandlerCommandArgs
* @param HostEvent[] $notificationOptions
* @param null|int $timezoneId
* @param null|int $severityId
* @param null|int $checkCommandId
* @param null|int $checkTimeperiodId
* @param null|int $maxCheckAttempts
* @param null|int $normalCheckInterval
* @param null|int $retryCheckInterval
* @param null|int $notificationInterval
* @param null|int $notificationTimeperiodId
* @param null|int $eventHandlerCommandId
* @param null|int $iconId
* @param null|int $firstNotificationDelay
* @param null|int $recoveryNotificationDelay
* @param null|int $acknowledgementTimeout
* @param null|int $freshnessThreshold
* @param null|int $lowFlapThreshold
* @param null|int $highFlapThreshold
* @param YesNoDefault $activeCheckEnabled
* @param YesNoDefault $passiveCheckEnabled
* @param YesNoDefault $notificationEnabled
* @param YesNoDefault $freshnessChecked
* @param YesNoDefault $flapDetectionEnabled
* @param YesNoDefault $eventHandlerEnabled
* @param bool $addInheritedContactGroup
* @param bool $addInheritedContact
* @param bool $isActivated
*
* @throws AssertionFailedException
*/
public function __construct(
protected int $monitoringServerId,
protected string $name,
protected string $address,
protected ?SnmpVersion $snmpVersion = null,
protected ?GeoCoords $geoCoordinates = null,
protected string $alias = '',
protected string $snmpCommunity = '',
protected string $noteUrl = '',
protected string $note = '',
protected string $actionUrl = '',
protected string $iconAlternative = '',
protected string $comment = '',
protected array $checkCommandArgs = [],
protected array $eventHandlerCommandArgs = [],
protected array $notificationOptions = [],
protected ?int $timezoneId = null,
protected ?int $severityId = null,
protected ?int $checkCommandId = null,
protected ?int $checkTimeperiodId = null,
protected ?int $notificationTimeperiodId = null,
protected ?int $eventHandlerCommandId = null,
protected ?int $iconId = null,
protected ?int $maxCheckAttempts = null,
protected ?int $normalCheckInterval = null,
protected ?int $retryCheckInterval = null,
protected ?int $notificationInterval = null,
protected ?int $firstNotificationDelay = null,
protected ?int $recoveryNotificationDelay = null,
protected ?int $acknowledgementTimeout = null,
protected ?int $freshnessThreshold = null,
protected ?int $lowFlapThreshold = null,
protected ?int $highFlapThreshold = null,
protected YesNoDefault $activeCheckEnabled = YesNoDefault::Default,
protected YesNoDefault $passiveCheckEnabled = YesNoDefault::Default,
protected YesNoDefault $notificationEnabled = YesNoDefault::Default,
protected YesNoDefault $freshnessChecked = YesNoDefault::Default,
protected YesNoDefault $flapDetectionEnabled = YesNoDefault::Default,
protected YesNoDefault $eventHandlerEnabled = YesNoDefault::Default,
protected bool $addInheritedContactGroup = false,
protected bool $addInheritedContact = false,
protected bool $isActivated = true,
) {
$shortName = (new \ReflectionClass($this))->getShortName();
// Formating and assertions on string properties
$this->name = self::formatName($name);
$this->alias = trim($alias);
$this->checkCommandArgs = array_map(trim(...), $checkCommandArgs);
$this->eventHandlerCommandArgs = array_map(trim(...), $eventHandlerCommandArgs);
$this->snmpCommunity = trim($snmpCommunity);
$this->note = trim($note);
$this->noteUrl = trim($noteUrl);
$this->actionUrl = trim($actionUrl);
$this->iconAlternative = trim($iconAlternative);
$this->comment = trim($comment);
$this->address = trim($this->address);
Assertion::notEmptyString($this->name, "{$shortName}::name");
Assertion::maxLength($this->name, self::MAX_NAME_LENGTH, "{$shortName}::name");
Assertion::maxLength($this->address, self::MAX_ADDRESS_LENGTH, "{$shortName}::address");
Assertion::maxLength($this->snmpCommunity, self::MAX_SNMP_COMMUNITY_LENGTH, "{$shortName}::snmpCommunity");
Assertion::maxLength($this->alias, self::MAX_ALIAS_LENGTH, "{$shortName}::alias");
Assertion::maxLength($this->noteUrl, self::MAX_NOTE_URL_LENGTH, "{$shortName}::noteUrl");
Assertion::maxLength($this->note, self::MAX_NOTE_LENGTH, "{$shortName}::note");
Assertion::maxLength($this->actionUrl, self::MAX_ACTION_URL_LENGTH, "{$shortName}::actionUrl");
Assertion::maxLength($this->iconAlternative, self::MAX_ICON_ALT_LENGTH, "{$shortName}::iconAlternative");
Assertion::maxLength($this->comment, self::MAX_COMMENT_LENGTH, "{$shortName}::comment");
// Assertions on ForeignKeys
$foreignKeys = [
'timezoneId' => $timezoneId,
'severityId' => $severityId,
'checkCommandId' => $checkCommandId,
'checkTimeperiodId' => $checkTimeperiodId,
'notificationTimeperiodId' => $notificationTimeperiodId,
'eventHandlerCommandId' => $eventHandlerCommandId,
'iconId' => $iconId,
'monitoringServerId' => $monitoringServerId,
];
foreach ($foreignKeys as $foreignKeyName => $foreignKeyValue) {
if ($foreignKeyValue !== null) {
Assertion::positiveInt($foreignKeyValue, "{$shortName}::{$foreignKeyName}");
}
}
// Assertion on integer properties
Assertion::min($maxCheckAttempts ?? 0, 0, "{$shortName}::maxCheckAttempts");
Assertion::min($normalCheckInterval ?? 0, 0, "{$shortName}::normalCheckInterval");
Assertion::min($retryCheckInterval ?? 0, 0, "{$shortName}::retryCheckInterval");
Assertion::min($notificationInterval ?? 0, 0, "{$shortName}::notificationInterval");
Assertion::min($firstNotificationDelay ?? 0, 0, "{$shortName}::firstNotificationDelay");
Assertion::min($recoveryNotificationDelay ?? 0, 0, "{$shortName}::recoveryNotificationDelay");
Assertion::min($acknowledgementTimeout ?? 0, 0, "{$shortName}::acknowledgementTimeout");
Assertion::min($freshnessThreshold ?? 0, 0, "{$shortName}::freshnessThreshold");
Assertion::min($lowFlapThreshold ?? 0, 0, "{$shortName}::lowFlapThreshold");
Assertion::min($highFlapThreshold ?? 0, 0, "{$shortName}::highFlapThreshold");
// Other assert
Assertion::ipOrDomain($address, "{$shortName}::address");
}
/**
* Format a string as per domain rules for a host template name.
*
* @param string $name
*/
final public static function formatName(string $name): string
{
return str_replace(' ', '_', trim($name));
}
public function getName(): string
{
return $this->name;
}
public function getAlias(): string
{
return $this->alias;
}
public function getSnmpCommunity(): string
{
return $this->snmpCommunity;
}
/**
* @return string[]
*/
public function getCheckCommandArgs(): array
{
return $this->checkCommandArgs;
}
/**
* @return string[]
*/
public function getEventHandlerCommandArgs(): array
{
return $this->eventHandlerCommandArgs;
}
public function getNoteUrl(): string
{
return $this->noteUrl;
}
public function getNote(): string
{
return $this->note;
}
public function getActionUrl(): string
{
return $this->actionUrl;
}
public function getIconAlternative(): string
{
return $this->iconAlternative;
}
public function getComment(): string
{
return $this->comment;
}
public function getTimezoneId(): ?int
{
return $this->timezoneId;
}
public function getSeverityId(): ?int
{
return $this->severityId;
}
public function getCheckCommandId(): ?int
{
return $this->checkCommandId;
}
public function getCheckTimeperiodId(): ?int
{
return $this->checkTimeperiodId;
}
public function getNotificationTimeperiodId(): ?int
{
return $this->notificationTimeperiodId;
}
public function getEventHandlerCommandId(): ?int
{
return $this->eventHandlerCommandId;
}
public function getIconId(): ?int
{
return $this->iconId;
}
public function getMaxCheckAttempts(): ?int
{
return $this->maxCheckAttempts;
}
public function getNormalCheckInterval(): ?int
{
return $this->normalCheckInterval;
}
public function getRetryCheckInterval(): ?int
{
return $this->retryCheckInterval;
}
public function getNotificationInterval(): ?int
{
return $this->notificationInterval;
}
public function getFirstNotificationDelay(): ?int
{
return $this->firstNotificationDelay;
}
public function getRecoveryNotificationDelay(): ?int
{
return $this->recoveryNotificationDelay;
}
public function getAcknowledgementTimeout(): ?int
{
return $this->acknowledgementTimeout;
}
public function getFreshnessThreshold(): ?int
{
return $this->freshnessThreshold;
}
public function getLowFlapThreshold(): ?int
{
return $this->lowFlapThreshold;
}
public function getHighFlapThreshold(): ?int
{
return $this->highFlapThreshold;
}
public function getSnmpVersion(): ?SnmpVersion
{
return $this->snmpVersion;
}
/**
* @return HostEvent[]
*/
public function getNotificationOptions(): array
{
return $this->notificationOptions;
}
public function getActiveCheckEnabled(): YesNoDefault
{
return $this->activeCheckEnabled;
}
public function getPassiveCheckEnabled(): YesNoDefault
{
return $this->passiveCheckEnabled;
}
public function getNotificationEnabled(): YesNoDefault
{
return $this->notificationEnabled;
}
public function getFreshnessChecked(): YesNoDefault
{
return $this->freshnessChecked;
}
public function getFlapDetectionEnabled(): YesNoDefault
{
return $this->flapDetectionEnabled;
}
public function getEventHandlerEnabled(): YesNoDefault
{
return $this->eventHandlerEnabled;
}
public function addInheritedContactGroup(): bool
{
return $this->addInheritedContactGroup;
}
public function addInheritedContact(): bool
{
return $this->addInheritedContact;
}
public function isActivated(): bool
{
return $this->isActivated;
}
public function getAddress(): string
{
return $this->address;
}
public function getMonitoringServerId(): int
{
return $this->monitoringServerId;
}
public function getGeoCoordinates(): GeoCoords|null
{
return $this->geoCoordinates;
}
}
| 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/Domain/Model/Host.php | centreon/src/Core/Host/Domain/Model/Host.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\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Core\Common\Domain\YesNoDefault;
use Core\Domain\Common\GeoCoords;
class Host extends NewHost
{
private string $shortName = '';
/**
* @param int $id
* @param int $monitoringServerId
* @param string $name
* @param string $address
* @param null|GeoCoords $geoCoordinates
* @param null|SnmpVersion $snmpVersion
* @param string $alias
* @param string $snmpCommunity
* @param string $noteUrl
* @param string $note
* @param string $actionUrl
* @param string $iconAlternative
* @param string $comment
* @param string[] $checkCommandArgs
* @param string[] $eventHandlerCommandArgs
* @param HostEvent[] $notificationOptions
* @param null|int $timezoneId
* @param null|int $severityId
* @param null|int $checkCommandId
* @param null|int $checkTimeperiodId
* @param null|int $notificationTimeperiodId
* @param null|int $eventHandlerCommandId
* @param null|int $iconId
* @param null|int $maxCheckAttempts
* @param null|int $normalCheckInterval
* @param null|int $retryCheckInterval
* @param null|int $notificationInterval
* @param null|int $firstNotificationDelay
* @param null|int $recoveryNotificationDelay
* @param null|int $acknowledgementTimeout
* @param null|int $freshnessThreshold
* @param null|int $lowFlapThreshold
* @param null|int $highFlapThreshold
* @param YesNoDefault $activeCheckEnabled
* @param YesNoDefault $passiveCheckEnabled
* @param YesNoDefault $notificationEnabled
* @param YesNoDefault $freshnessChecked
* @param YesNoDefault $flapDetectionEnabled
* @param YesNoDefault $eventHandlerEnabled
* @param bool $addInheritedContactGroup
* @param bool $addInheritedContact
* @param bool $isActivated
*
* @throws AssertionFailedException
*/
public function __construct(
private readonly int $id,
int $monitoringServerId,
string $name,
string $address,
?GeoCoords $geoCoordinates = null,
?SnmpVersion $snmpVersion = null,
string $alias = '',
string $snmpCommunity = '',
string $noteUrl = '',
string $note = '',
string $actionUrl = '',
string $iconAlternative = '',
string $comment = '',
array $checkCommandArgs = [],
array $eventHandlerCommandArgs = [],
?int $timezoneId = null,
?int $severityId = null,
?int $checkCommandId = null,
?int $checkTimeperiodId = null,
?int $notificationTimeperiodId = null,
?int $eventHandlerCommandId = null,
?int $iconId = null,
?int $maxCheckAttempts = null,
?int $normalCheckInterval = null,
?int $retryCheckInterval = null,
array $notificationOptions = [],
?int $notificationInterval = null,
?int $firstNotificationDelay = null,
?int $recoveryNotificationDelay = null,
?int $acknowledgementTimeout = null,
?int $freshnessThreshold = null,
?int $lowFlapThreshold = null,
?int $highFlapThreshold = null,
YesNoDefault $activeCheckEnabled = YesNoDefault::Default,
YesNoDefault $passiveCheckEnabled = YesNoDefault::Default,
YesNoDefault $notificationEnabled = YesNoDefault::Default,
YesNoDefault $freshnessChecked = YesNoDefault::Default,
YesNoDefault $flapDetectionEnabled = YesNoDefault::Default,
YesNoDefault $eventHandlerEnabled = YesNoDefault::Default,
bool $addInheritedContactGroup = false,
bool $addInheritedContact = false,
bool $isActivated = true,
) {
$this->shortName = (new \ReflectionClass($this))->getShortName();
Assertion::positiveInt($id, "{$this->shortName}::id");
parent::__construct(
monitoringServerId: $monitoringServerId,
name: $name,
address: $address,
geoCoordinates: $geoCoordinates,
snmpVersion: $snmpVersion,
alias: $alias,
snmpCommunity: $snmpCommunity,
noteUrl: $noteUrl,
note: $note,
actionUrl: $actionUrl,
iconAlternative: $iconAlternative,
comment: $comment,
checkCommandArgs: $checkCommandArgs,
eventHandlerCommandArgs: $eventHandlerCommandArgs,
notificationOptions: $notificationOptions,
timezoneId: $timezoneId,
severityId: $severityId,
checkCommandId: $checkCommandId,
checkTimeperiodId: $checkTimeperiodId,
notificationTimeperiodId: $notificationTimeperiodId,
eventHandlerCommandId: $eventHandlerCommandId,
iconId: $iconId,
maxCheckAttempts: $maxCheckAttempts,
normalCheckInterval: $normalCheckInterval,
retryCheckInterval: $retryCheckInterval,
activeCheckEnabled: $activeCheckEnabled,
passiveCheckEnabled: $passiveCheckEnabled,
notificationEnabled: $notificationEnabled,
notificationInterval: $notificationInterval,
firstNotificationDelay: $firstNotificationDelay,
recoveryNotificationDelay: $recoveryNotificationDelay,
acknowledgementTimeout: $acknowledgementTimeout,
freshnessChecked: $freshnessChecked,
freshnessThreshold: $freshnessThreshold,
flapDetectionEnabled: $flapDetectionEnabled,
lowFlapThreshold: $lowFlapThreshold,
highFlapThreshold: $highFlapThreshold,
eventHandlerEnabled: $eventHandlerEnabled,
addInheritedContactGroup: $addInheritedContactGroup,
addInheritedContact: $addInheritedContact,
isActivated: $isActivated,
);
}
public function getId(): int
{
return $this->id;
}
public function isNameIdentical(string $testName): bool
{
return $this->name === self::formatName($testName);
}
/**
* @param string $name
*
* @throws AssertionFailedException
*/
public function setName(string $name): void
{
$this->name = $this->formatName($name);
Assertion::notEmptyString($this->name, "{$this->shortName}::name");
Assertion::maxLength($this->name, self::MAX_NAME_LENGTH, "{$this->shortName}::name");
}
/**
* @param string $alias
*
* @throws AssertionFailedException
*/
public function setAlias(string $alias): void
{
$this->alias = trim($alias);
Assertion::maxLength($this->alias, self::MAX_ALIAS_LENGTH, "{$this->shortName}::alias");
}
/**
* @param string[] $checkCommandArgs
*/
public function setCheckCommandArgs(array $checkCommandArgs): void
{
$this->checkCommandArgs = array_map(trim(...), $checkCommandArgs);
}
/**
* @param string[] $eventHandlerCommandArgs
*/
public function setEventHandlerCommandArgs(array $eventHandlerCommandArgs): void
{
$this->eventHandlerCommandArgs = array_map(trim(...), $eventHandlerCommandArgs);
}
/**
* @param SnmpVersion|null $snmpVersion
*
* @throws AssertionFailedException
*/
public function setSnmpVersion(SnmpVersion|null $snmpVersion): void
{
$this->snmpVersion = $snmpVersion;
}
/**
* @param string $snmpCommunity
*
* @throws AssertionFailedException
*/
public function setSnmpCommunity(string $snmpCommunity): void
{
$this->snmpCommunity = trim($snmpCommunity);
Assertion::maxLength($this->snmpCommunity, self::MAX_SNMP_COMMUNITY_LENGTH, "{$this->shortName}::snmpCommunity");
}
/**
* @param string $note
*
* @throws AssertionFailedException
*/
public function setNote(string $note): void
{
$this->note = trim($note);
Assertion::maxLength($this->note, self::MAX_NOTE_LENGTH, "{$this->shortName}::note");
}
/**
* @param string $noteUrl
*
* @throws AssertionFailedException
*/
public function setNoteUrl(string $noteUrl): void
{
$this->noteUrl = trim($noteUrl);
Assertion::maxLength($this->noteUrl, self::MAX_NOTE_URL_LENGTH, "{$this->shortName}::noteUrl");
}
/**
* @param string $actionUrl
*
* @throws AssertionFailedException
*/
public function setActionUrl(string $actionUrl): void
{
$this->actionUrl = trim($actionUrl);
Assertion::maxLength($this->actionUrl, self::MAX_ACTION_URL_LENGTH, "{$this->shortName}::actionUrl");
}
/**
* @param string $iconAlternative
*
* @throws AssertionFailedException
*/
public function setIconAlternative(string $iconAlternative): void
{
$this->iconAlternative = trim($iconAlternative);
Assertion::maxLength($this->iconAlternative, self::MAX_ICON_ALT_LENGTH, "{$this->shortName}::iconAlternative");
}
/**
* @param string $comment
*
* @throws AssertionFailedException
*/
public function setComment(string $comment): void
{
$this->comment = trim($comment);
Assertion::maxLength($this->comment, self::MAX_COMMENT_LENGTH, "{$this->shortName}::comment");
}
/**
* @param int|null $timezoneId
*
* @throws AssertionFailedException
*/
public function setTimezoneId(int|null $timezoneId): void
{
$this->timezoneId = $timezoneId;
if ($this->timezoneId !== null) {
Assertion::positiveInt($this->timezoneId, "{$this->shortName}::timezoneId");
}
}
/**
* @param int|null $severityId
*
* @throws AssertionFailedException
*/
public function setSeverityId(int|null $severityId): void
{
$this->severityId = $severityId;
if ($this->severityId !== null) {
Assertion::positiveInt($this->severityId, "{$this->shortName}::severityId");
}
}
/**
* @param int|null $checkCommandId
*
* @throws AssertionFailedException
*/
public function setCheckCommandId(int|null $checkCommandId): void
{
$this->checkCommandId = $checkCommandId;
if ($this->checkCommandId !== null) {
Assertion::positiveInt($this->checkCommandId, "{$this->shortName}::checkCommandId");
}
}
/**
* @param int|null $checkTimeperiodId
*
* @throws AssertionFailedException
*/
public function setCheckTimeperiodId(int|null $checkTimeperiodId): void
{
$this->checkTimeperiodId = $checkTimeperiodId;
if ($this->checkTimeperiodId !== null) {
Assertion::positiveInt($this->checkTimeperiodId, "{$this->shortName}::checkTimeperiodId");
}
}
/**
* @param int|null $notificationTimeperiodId
*
* @throws AssertionFailedException
*/
public function setNotificationTimeperiodId(int|null $notificationTimeperiodId): void
{
$this->notificationTimeperiodId = $notificationTimeperiodId;
if ($this->notificationTimeperiodId !== null) {
Assertion::positiveInt($this->notificationTimeperiodId, "{$this->shortName}::notificationTimeperiodId");
}
}
/**
* @param int|null $eventHandlerCommandId
*
* @throws AssertionFailedException
*/
public function setEventHandlerCommandId(int|null $eventHandlerCommandId): void
{
$this->eventHandlerCommandId = $eventHandlerCommandId;
if ($this->eventHandlerCommandId !== null) {
Assertion::positiveInt($this->eventHandlerCommandId, "{$this->shortName}::eventHandlerCommandId");
}
}
/**
* @param int|null $iconId
*
* @throws AssertionFailedException
*/
public function setIconId(int|null $iconId): void
{
$this->iconId = $iconId;
if ($this->iconId !== null) {
Assertion::positiveInt($this->iconId, "{$this->shortName}::iconId");
}
}
/**
* @param int|null $maxCheckAttempts
*
* @throws AssertionFailedException
*/
public function setMaxCheckAttempts(int|null $maxCheckAttempts): void
{
$this->maxCheckAttempts = $maxCheckAttempts;
Assertion::min($this->maxCheckAttempts ?? 0, 0, "{$this->shortName}::maxCheckAttempts");
}
/**
* @param int|null $normalCheckInterval
*
* @throws AssertionFailedException
*/
public function setNormalCheckInterval(int|null $normalCheckInterval): void
{
$this->normalCheckInterval = $normalCheckInterval;
Assertion::min($this->normalCheckInterval ?? 0, 0, "{$this->shortName}::normalCheckInterval");
}
/**
* @param int|null $retryCheckInterval
*
* @throws AssertionFailedException
*/
public function setRetryCheckInterval(int|null $retryCheckInterval): void
{
$this->retryCheckInterval = $retryCheckInterval;
Assertion::min($this->retryCheckInterval ?? 0, 0, "{$this->shortName}::retryCheckInterval");
}
/**
* @param int|null $notificationInterval
*
* @throws AssertionFailedException
*/
public function setNotificationInterval(int|null $notificationInterval): void
{
$this->notificationInterval = $notificationInterval;
Assertion::min($this->notificationInterval ?? 0, 0, "{$this->shortName}::notificationInterval");
}
/**
* @param int|null $firstNotificationDelay
*
* @throws AssertionFailedException
*/
public function setFirstNotificationDelay(int|null $firstNotificationDelay): void
{
$this->firstNotificationDelay = $firstNotificationDelay;
Assertion::min($this->firstNotificationDelay ?? 0, 0, "{$this->shortName}::firstNotificationDelay");
}
/**
* @param int|null $recoveryNotificationDelay
*
* @throws AssertionFailedException
*/
public function setRecoveryNotificationDelay(int|null $recoveryNotificationDelay): void
{
$this->recoveryNotificationDelay = $recoveryNotificationDelay;
Assertion::min($this->recoveryNotificationDelay ?? 0, 0, "{$this->shortName}::recoveryNotificationDelay");
}
/**
* @param int|null $acknowledgementTimeout
*
* @throws AssertionFailedException
*/
public function setAcknowledgementTimeout(int|null $acknowledgementTimeout): void
{
$this->acknowledgementTimeout = $acknowledgementTimeout;
Assertion::min($this->acknowledgementTimeout ?? 0, 0, "{$this->shortName}::acknowledgementTimeout");
}
/**
* @param int|null $freshnessThreshold
*
* @throws AssertionFailedException
*/
public function setFreshnessThreshold(int|null $freshnessThreshold): void
{
$this->freshnessThreshold = $freshnessThreshold;
Assertion::min($this->freshnessThreshold ?? 0, 0, "{$this->shortName}::freshnessThreshold");
}
/**
* @param int|null $lowFlapThreshold
*
* @throws AssertionFailedException
*/
public function setLowFlapThreshold(int|null $lowFlapThreshold): void
{
$this->lowFlapThreshold = $lowFlapThreshold;
Assertion::min($this->lowFlapThreshold ?? 0, 0, "{$this->shortName}::lowFlapThreshold");
}
/**
* @param int|null $highFlapThreshold
*
* @throws AssertionFailedException
*/
public function setHighFlapThreshold(int|null $highFlapThreshold): void
{
$this->highFlapThreshold = $highFlapThreshold;
Assertion::min($this->highFlapThreshold ?? 0, 0, "{$this->shortName}::highFlapThreshold");
}
/**
* @param HostEvent[] $notificationOptions
*/
public function setNotificationOptions(array $notificationOptions): void
{
$this->notificationOptions = $notificationOptions;
}
public function setActiveCheckEnabled(YesNoDefault $activeCheckEnabled): void
{
$this->activeCheckEnabled = $activeCheckEnabled;
}
public function setPassiveCheckEnabled(YesNoDefault $passiveCheckEnabled): void
{
$this->passiveCheckEnabled = $passiveCheckEnabled;
}
public function setNotificationEnabled(YesNoDefault $notificationEnabled): void
{
$this->notificationEnabled = $notificationEnabled;
}
public function setFreshnessChecked(YesNoDefault $freshnessChecked): void
{
$this->freshnessChecked = $freshnessChecked;
}
public function setFlapDetectionEnabled(YesNoDefault $flapDetectionEnabled): void
{
$this->flapDetectionEnabled = $flapDetectionEnabled;
}
public function setEventHandlerEnabled(YesNoDefault $eventHandlerEnabled): void
{
$this->eventHandlerEnabled = $eventHandlerEnabled;
}
public function setAddInheritedContactGroup(bool $addInheritedContactGroup): void
{
$this->addInheritedContactGroup = $addInheritedContactGroup;
}
public function setAddInheritedContact(bool $addInheritedContact): void
{
$this->addInheritedContact = $addInheritedContact;
}
public function setIsActivated(bool $isActivated): void
{
$this->isActivated = $isActivated;
}
public function setAddress(string $address): void
{
$this->address = trim($address);
Assertion::maxLength($this->address, self::MAX_ADDRESS_LENGTH, "{$this->shortName}::address");
Assertion::ipOrDomain($this->address, "{$this->shortName}::address");
}
public function setMonitoringServerId(int $monitoringServerId): void
{
$this->monitoringServerId = $monitoringServerId;
Assertion::positiveInt($this->monitoringServerId, "{$this->shortName}::monitoringServerId");
}
public function setGeoCoordinates(?GeoCoords $geoCoordinates): void
{
$this->geoCoordinates = $geoCoordinates;
}
}
| 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/Repository/DbWriteHostActionLogRepository.php | centreon/src/Core/Host/Infrastructure/Repository/DbWriteHostActionLogRepository.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\Repository;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Repository\RepositoryException;
use Centreon\Infrastructure\DatabaseConnection;
use Core\ActionLog\Application\Repository\WriteActionLogRepositoryInterface;
use Core\ActionLog\Domain\Model\ActionLog;
use Core\Common\Application\Converter\YesNoDefaultConverter;
use Core\Common\Domain\YesNoDefault;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Domain\Common\GeoCoords;
use Core\Host\Application\Converter\HostEventConverter;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
use Core\Host\Application\Repository\WriteHostRepositoryInterface;
use Core\Host\Domain\Model\Host;
use Core\Host\Domain\Model\HostEvent;
use Core\Host\Domain\Model\NewHost;
use Core\Host\Domain\Model\SnmpVersion;
class DbWriteHostActionLogRepository extends AbstractRepositoryRDB implements WriteHostRepositoryInterface
{
use LoggerTrait;
public const HOST_PROPERTIES_MAP = [
'name' => 'host_name',
'alias' => 'host_alias',
'address' => 'host_address',
'monitoringServerId' => 'nagios_server_id',
'activeCheckEnabled' => 'host_active_checks_enabled',
'passiveCheckEnabled' => 'host_passive_checks_enabled',
'notificationEnabled' => 'host_notifications_enabled',
'freshnessChecked' => 'host_check_freshness',
'flapDetectionEnabled' => 'host_flap_detection_enabled',
'eventHandlerEnabled' => 'host_event_handler_enabled',
'isActivated' => 'host_activate',
'snmpVersion' => 'host_snmp_version',
'snmpCommunity' => 'host_snmp_community',
'timezoneId' => 'host_location',
'checkCommandId' => 'command_command_id',
'checkTimeperiodId' => 'timeperiod_tp_id',
'maxCheckAttempts' => 'host_max_check_attempts',
'normalCheckInterval' => 'host_check_interval',
'retryCheckInterval' => 'host_retry_check_interval',
'checkCommandArgs' => 'command_command_id_arg1',
'noteUrl' => 'ehi_notes_url',
'note' => 'ehi_notes',
'actionUrl' => 'ehi_action_url',
'iconAlternative' => 'ehi_icon_image_alt',
'comment' => 'host_comment',
'eventHandlerCommandArgs' => 'command_command_id_arg2',
'notificationTimeperiodId' => 'timeperiod_tp_id2',
'eventHandlerCommandId' => 'command_command_id2',
'geoCoordinates' => 'geo_coords',
'notificationOptions' => 'host_notifOpts',
'iconId' => 'ehi_icon_image',
'notificationInterval' => 'host_notification_interval',
'firstNotificationDelay' => 'host_first_notification_delay',
'recoveryNotificationDelay' => 'host_recovery_notification_delay',
'acknowledgementTimeout' => 'host_acknowledgement_timeout',
'freshnessThreshold' => 'host_freshness_threshold',
'lowFlapThreshold' => 'host_low_flap_threshold',
'highFlapThreshold' => 'host_high_flap_threshold',
'severityId' => 'severity_id',
'addInheritedContactGroup' => 'cg_additive_inheritance',
'addInheritedContact' => 'contact_additive_inheritance',
];
/**
* @param WriteHostRepositoryInterface $writeHostRepository
* @param ContactInterface $contact
* @param ReadHostRepositoryInterface $readHostRepository
* @param WriteActionLogRepositoryInterface $writeActionLogRepository
* @param DatabaseConnection $db
*/
public function __construct(
private readonly WriteHostRepositoryInterface $writeHostRepository,
private readonly ContactInterface $contact,
private readonly ReadHostRepositoryInterface $readHostRepository,
private readonly WriteActionLogRepositoryInterface $writeActionLogRepository,
DatabaseConnection $db,
) {
$this->db = $db;
}
/**
* @inheritDoc
*/
public function add(NewHost $host): int
{
try {
$hostId = $this->writeHostRepository->add($host);
if ($hostId === 0) {
throw new RepositoryException('Host ID cannot be 0');
}
$actionLog = new ActionLog(
ActionLog::OBJECT_TYPE_HOST,
$hostId,
$host->getName(),
ActionLog::ACTION_TYPE_ADD,
$this->contact->getId()
);
$actionLogId = $this->writeActionLogRepository->addAction($actionLog);
if ($actionLogId === 0) {
throw new RepositoryException('Action log ID cannot be 0');
}
$actionLog->setId($actionLogId);
$details = $this->getHostPropertiesAsArray($host);
$this->writeActionLogRepository->addActionDetails($actionLog, $details);
return $hostId;
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
throw $ex;
}
}
/**
* @inheritDoc
*/
public function deleteById(int $hostId): void
{
try {
$host = $this->readHostRepository->findById($hostId);
if ($host === null) {
throw new RepositoryException('Cannot find host to update.');
}
$this->writeHostRepository->deleteById($hostId);
$actionLog = new ActionLog(
ActionLog::OBJECT_TYPE_HOST,
$hostId,
$host->getName(),
ActionLog::ACTION_TYPE_DELETE,
$this->contact->getId()
);
$this->writeActionLogRepository->addAction($actionLog);
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
throw $ex;
}
}
/**
* @inheritDoc
*/
public function update(Host $host): void
{
try {
$currentHost = $this->readHostRepository->findById($host->getId());
if ($currentHost === null) {
throw new RepositoryException('Cannot find host to update.');
}
$currentHostDetails = $this->getHostPropertiesAsArray($currentHost);
$updatedHostDetails = $this->getHostPropertiesAsArray($host);
$diff = array_diff_assoc($updatedHostDetails, $currentHostDetails);
$this->writeHostRepository->update($host);
if (array_key_exists('isActivated', $diff) && count($diff) === 1) {
$action = (bool) $diff['isActivated']
? ActionLog::ACTION_TYPE_ENABLE
: ActionLog::ACTION_TYPE_DISABLE;
$actionLog = new ActionLog(
ActionLog::OBJECT_TYPE_HOST,
$host->getId(),
$host->getName(),
$action,
$this->contact->getId()
);
$this->writeActionLogRepository->addAction($actionLog);
}
if (array_key_exists('isActivated', $diff) && count($diff) > 1) {
$action = (bool) $diff['isActivated']
? ActionLog::ACTION_TYPE_ENABLE
: ActionLog::ACTION_TYPE_DISABLE;
$actionLog = new ActionLog(
ActionLog::OBJECT_TYPE_HOST,
$host->getId(),
$host->getName(),
$action,
$this->contact->getId()
);
$this->writeActionLogRepository->addAction($actionLog);
$actionLogChange = new ActionLog(
ActionLog::OBJECT_TYPE_HOST,
$host->getId(),
$host->getName(),
ActionLog::ACTION_TYPE_CHANGE,
$this->contact->getId()
);
$actionLogChangeId = $this->writeActionLogRepository->addAction($actionLogChange);
if ($actionLogChangeId === 0) {
throw new RepositoryException('Action log ID cannot be 0');
}
$actionLogChange->setId($actionLogChangeId);
$this->writeActionLogRepository->addActionDetails($actionLogChange, $updatedHostDetails);
}
if (! array_key_exists('isActivated', $diff) && count($diff) >= 1) {
$actionLogChange = new ActionLog(
ActionLog::OBJECT_TYPE_HOST,
$host->getId(),
$host->getName(),
ActionLog::ACTION_TYPE_CHANGE,
$this->contact->getId()
);
$actionLogChangeId = $this->writeActionLogRepository->addAction($actionLogChange);
if ($actionLogChangeId === 0) {
throw new RepositoryException('Action log ID cannot be 0');
}
$actionLogChange->setId($actionLogChangeId);
$this->writeActionLogRepository->addActionDetails($actionLogChange, $updatedHostDetails);
}
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
throw $ex;
}
}
/**
* @inheritDoc
*/
public function addParent(int $childId, int $parentId, int $order): void
{
$this->writeHostRepository->addParent($childId, $parentId, $order);
}
/**
* @inheritDoc
*/
public function deleteParents(int $childId): void
{
$this->writeHostRepository->deleteParents($childId);
}
/**
* @param NewHost $host
*
* @return array<string,int|bool|string>
*/
private function getHostPropertiesAsArray(NewHost $host): array
{
$hostPropertiesArray = [];
$hostReflection = new \ReflectionClass($host);
foreach ($hostReflection->getProperties() as $property) {
$propertyName = $property->getName();
$mappedName = self::HOST_PROPERTIES_MAP[$propertyName] ?? $propertyName;
$value = $property->getValue($host);
if ($value === null) {
$value = '';
}
if ($value instanceof GeoCoords) {
$value = $value->__toString();
}
if ($value instanceof YesNoDefault) {
$value = YesNoDefaultConverter::toString($value);
}
if ($value instanceof SnmpVersion) {
$value = $value->value;
}
if (is_array($value)) {
if ($value === []) {
$value = '';
} elseif (is_string($value[0])) {
$value = '!' . implode('!', str_replace(["\n", "\t", "\r"], ['#BR#', '#T#', '#R#'], $value));
} elseif ($value[0] instanceof HostEvent) {
$value = HostEventConverter::toString($value);
}
}
$hostPropertiesArray[$mappedName] = $value;
}
/** @var array<string,int|bool|string> $hostPropertiesArray */
return $hostPropertiesArray;
}
}
| 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/Repository/DbReadRealTimeHostRepository.php | centreon/src/Core/Host/Infrastructure/Repository/DbReadRealTimeHostRepository.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\Repository;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\RequestParameters\Interfaces\NormalizerInterface;
use Centreon\Infrastructure\RequestParameters\RequestParametersTranslatorException;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait;
use Core\Host\Application\Repository\ReadRealTimeHostRepositoryInterface;
use Core\Host\Domain\Model\HostStatusesCount;
/**
* @phpstan-type _HostStatuses array{
* array{
* id: int,
* name: string,
* status: int
* }
* }|array{}
*/
class DbReadRealTimeHostRepository extends AbstractRepositoryRDB implements ReadRealTimeHostRepositoryInterface
{
use SqlMultipleBindTrait;
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function findStatusesByRequestParameters(RequestParametersInterface $requestParameters): HostStatusesCount
{
$sqlTranslator = $this->prepareSqlRequestParametersTranslatorForStatuses($requestParameters);
$request = $this->returnBaseQuery();
$request .= $search = $sqlTranslator->translateSearchParameterToSql();
$request .= $search !== null ? ' AND ' : ' WHERE ';
$request .= <<<'SQL'
hosts.type = 1
AND hosts.enabled = 1
AND hosts.name NOT LIKE "_Module_%"
SQL;
$request .= ' GROUP BY hosts.id, hosts.name, hosts.status ';
$sort = $sqlTranslator->translateSortParameterToSql();
$request .= $sort ?? ' ORDER BY hosts.name ASC';
$statement = $this->db->prepare($this->translateDbName($request));
$sqlTranslator->bindSearchValues($statement);
$statement->execute();
/** @var _HostStatuses $hosts */
$hosts = $statement->fetchAll(\PDO::FETCH_ASSOC);
return $this->createHostStatusesCountFromRecord($hosts);
}
/**
* @inheritDoc
*/
public function findStatusesByRequestParametersAndAccessGroupIds(
RequestParametersInterface $requestParameters,
array $accessGroupIds,
): HostStatusesCount {
if ($accessGroupIds === []) {
$this->createHostStatusesCountFromRecord([]);
}
[$bindValues, $bindQuery] = $this->createMultipleBindQuery($accessGroupIds, ':access_group');
$sqlTranslator = $this->prepareSqlRequestParametersTranslatorForStatuses($requestParameters);
$request = $this->returnBaseQuery();
$request .= <<<'SQL'
INNER JOIN `:dbstg`.centreon_acl acls
ON acls.host_id = hosts.id
AND acls.service_id = services.id
SQL;
$request .= $search = $sqlTranslator->translateSearchParameterToSql();
$request .= $search !== null ? ' AND ' : ' WHERE ';
$request .= "hosts.type = 1 AND hosts.enabled = 1 AND acls.group_id IN ({$bindQuery})";
$request .= ' GROUP BY hosts.id, hosts.name, hosts.status ';
$sort = $sqlTranslator->translateSortParameterToSql();
$request .= $sort ?? ' ORDER BY hosts.name ASC';
$statement = $this->db->prepare($this->translateDbName($request));
$sqlTranslator->bindSearchValues($statement);
foreach ($bindValues as $token => $value) {
$statement->bindValue($token, $value, \PDO::PARAM_INT);
}
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
/** @var _HostStatuses $hosts */
$hosts = $statement->fetchAll();
return $this->createHostStatusesCountFromRecord($hosts);
}
/**
* @param RequestParametersInterface $requestParameters
*
* @return SqlRequestParametersTranslator
*/
private function prepareSqlRequestParametersTranslatorForStatuses(
RequestParametersInterface $requestParameters,
): SqlRequestParametersTranslator {
$sqlTranslator = new SqlRequestParametersTranslator($requestParameters);
$sqlTranslator->setConcordanceArray([
'name' => 'hosts.name',
'status' => 'hosts.status',
'service.name' => 'services.name',
'service.id' => 'services.id',
'host_category.name' => 'host_categories.name',
'host_category.id' => 'host_categories.id',
'host_group.name' => 'host_groups.name',
'host_group.id' => 'host_groups.id',
'service_group.name' => 'service_groups.name',
'service_group.id' => 'service_groups.id',
'service_category.name' => 'service_categories.name',
'service_category.id' => 'service_categories.id',
]);
$sqlTranslator->addNormalizer(
'status',
new class () implements NormalizerInterface {
/**
* @inheritDoc
*/
public function normalize($valueToNormalize)
{
switch (mb_strtoupper((string) $valueToNormalize)) {
case 'UP':
$code = HostStatusesCount::STATUS_UP;
break;
case 'DOWN':
$code = HostStatusesCount::STATUS_DOWN;
break;
case 'UNREACHABLE':
$code = HostStatusesCount::STATUS_UNREACHABLE;
break;
case 'PENDING':
$code = HostStatusesCount::STATUS_PENDING;
break;
default:
throw new RequestParametersTranslatorException('Status provided not handled');
}
return $code;
}
}
);
return $sqlTranslator;
}
/**
* @return string
*/
private function returnBaseQuery(): string
{
// tags 0=servicegroup, 1=hostgroup, 2=servicecategory, 3=hostcategory
return <<<'SQL'
SELECT
hosts.id AS `id`,
hosts.name AS `name`,
hosts.status AS `status`
FROM `:dbstg`.resources AS hosts
LEFT JOIN `:dbstg`.resources AS services
ON services.parent_id = hosts.id
LEFT JOIN `:dbstg`.resources_tags AS rtags_host_groups
ON hosts.resource_id = rtags_host_groups.resource_id
LEFT JOIN `:dbstg`.tags host_groups
ON rtags_host_groups.tag_id = host_groups.tag_id
AND host_groups.type = 1
LEFT JOIN `:dbstg`.resources_tags AS rtags_host_categories
ON hosts.resource_id = rtags_host_categories.resource_id
LEFT JOIN `:dbstg`.tags host_categories
ON rtags_host_categories.tag_id = host_categories.tag_id
AND host_categories.type = 3
LEFT JOIN `:dbstg`.resources_tags AS rtags_service_groups
ON services.resource_id = rtags_service_groups.resource_id
LEFT JOIN `:dbstg`.tags service_groups
ON rtags_service_groups.tag_id = service_groups.tag_id
AND service_groups.type = 0
LEFT JOIN `:dbstg`.resources_tags AS rtags_service_categories
ON services.resource_id = rtags_service_categories.resource_id
LEFT JOIN `:dbstg`.tags service_categories
ON rtags_service_categories.tag_id = service_categories.tag_id
AND service_categories.type = 2
SQL;
}
/**
* @param _HostStatuses $record
*
* @return HostStatusesCount
*/
private function createHostStatusesCountFromRecord(array $record): HostStatusesCount
{
return new HostStatusesCount(
$this->countStatuses($record, HostStatusesCount::STATUS_UP),
$this->countStatuses($record, HostStatusesCount::STATUS_DOWN),
$this->countStatuses($record, HostStatusesCount::STATUS_UNREACHABLE),
$this->countStatuses($record, HostStatusesCount::STATUS_PENDING)
);
}
/**
* @param _HostStatuses $record
* @param int $statusCode
*
* @return int
*/
private function countStatuses(array $record, int $statusCode): int
{
return count(
array_filter(
$record,
static fn (array $host) => $host['status'] === $statusCode
)
);
}
}
| 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/Repository/HostRepositoryTrait.php | centreon/src/Core/Host/Infrastructure/Repository/HostRepositoryTrait.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\Repository;
use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait;
trait HostRepositoryTrait
{
use SqlMultipleBindTrait;
/**
* @param int[] $accessGroupIds
*
* @return string
*/
public function generateHostAclSubRequest(array $accessGroupIds = []): string
{
$subRequest = '';
if (
$accessGroupIds !== []
&& ! $this->hasAccessToAllHosts($accessGroupIds)
) {
[, $bindQuery] = $this->createMultipleBindQuery($accessGroupIds, ':access_group_id_');
$subRequest = <<<SQL
SELECT arhr.host_host_id
FROM `:db`.acl_resources_host_relations arhr
INNER JOIN `:db`.acl_resources res
ON res.acl_res_id = arhr.acl_res_id
INNER JOIN `:db`.acl_res_group_relations argr
ON argr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_groups ag
ON ag.acl_group_id = argr.acl_group_id
WHERE ag.acl_group_id IN ({$bindQuery})
SQL;
}
return $subRequest;
}
/**
* @param int[] $accessGroupIds
*
* @return bool
*/
public function hasAccessToAllHosts(array $accessGroupIds): bool
{
if ($accessGroupIds === []) {
return false;
}
[$bindValues, $bindQuery] = $this->createMultipleBindQuery($accessGroupIds, ':access_group_id_');
$request = <<<SQL
SELECT res.all_hosts
FROM `:db`.acl_resources res
INNER JOIN `:db`.acl_res_group_relations argr
ON argr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_groups ag
ON ag.acl_group_id = argr.acl_group_id
WHERE res.acl_res_activate = '1' AND ag.acl_group_id IN ({$bindQuery})
SQL;
$statement = $this->db->prepare($this->translateDbName($request));
foreach ($bindValues as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->execute();
while (false !== ($hasAccessToAll = $statement->fetchColumn())) {
if ((bool) $hasAccessToAll === true) {
return true;
}
}
return false;
}
}
| 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/Repository/TinyHostFactory.php | centreon/src/Core/Host/Infrastructure/Repository/TinyHostFactory.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\Repository;
use Assert\AssertionFailedException;
use Core\Host\Domain\Model\TinyHost;
/**
* @phpstan-type _TinyHost array{
* id: int,
* name: string,
* alias: string|null,
* monitoring_server_id: int
* }
*/
class TinyHostFactory
{
/**
* @param array{id: int, name: string, alias:string|null, monitoring_server_id: int} $data
*
* @throws AssertionFailedException
*
* @return TinyHost
*/
public static function createFromDb(array $data): TinyHost
{
return new TinyHost(
$data['id'],
$data['name'],
$data['alias'] ?? null,
$data['monitoring_server_id'],
);
}
/**
* @param array{id: int, name: string, alias:string|null, monitoring_server: array{id: int}} $data
*
* @throws AssertionFailedException
*
* @return TinyHost
*/
public static function createFromApi(array $data): TinyHost
{
return new TinyHost(
$data['id'],
$data['name'],
$data['alias'] ?? null,
$data['monitoring_server']['id'],
);
}
}
| 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/Repository/DbWriteHostRepository.php | centreon/src/Core/Host/Infrastructure/Repository/DbWriteHostRepository.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\Repository;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Application\Converter\YesNoDefaultConverter;
use Core\Common\Domain\HostType;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Common\Infrastructure\Repository\RepositoryTrait;
use Core\Common\Infrastructure\RequestParameters\Normalizer\BoolToEnumNormalizer;
use Core\Host\Application\Converter\HostEventConverter;
use Core\Host\Application\Repository\WriteHostRepositoryInterface;
use Core\Host\Domain\Model\Host;
use Core\Host\Domain\Model\NewHost;
class DbWriteHostRepository extends AbstractRepositoryRDB implements WriteHostRepositoryInterface
{
use LoggerTrait;
use RepositoryTrait;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function addParent(int $childId, int $parentId, int $order): void
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
INSERT INTO `:db`.`host_template_relation` (`host_tpl_id`, `host_host_id`, `order`)
VALUES (:parent_id, :child_id, :order)
SQL
));
$statement->bindValue(':child_id', $childId, \PDO::PARAM_INT);
$statement->bindValue(':parent_id', $parentId, \PDO::PARAM_INT);
$statement->bindValue(':order', $order, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @inheritDoc
*/
public function deleteParents(int $childId): void
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
DELETE FROM `:db`.`host_template_relation`
WHERE `host_host_id` = :child_id
SQL
));
$statement->bindValue(':child_id', $childId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @inheritDoc
*/
public function add(NewHost $host): int
{
$this->debug('Add host');
$alreadyInTransaction = $this->db->inTransaction();
if (! $alreadyInTransaction) {
$this->db->beginTransaction();
}
try {
$hostId = $this->addBasicInformations($host);
$this->addMonitoringServer($hostId, $host);
$this->addExtendedInformations($hostId, $host);
if ($host->getSeverityId() !== null) {
$this->addSeverity($hostId, $host);
}
if (! $alreadyInTransaction) {
$this->db->commit();
}
$this->debug('Host added with ID ' . $hostId);
return $hostId;
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
if (! $alreadyInTransaction) {
$this->db->rollBack();
}
throw $ex;
}
}
/**
* @inheritDoc
*/
public function deleteById(int $hostId): void
{
$request = $this->translateDbName('DELETE FROM `:db`.host WHERE host_id = :host_id AND host_register = \'1\'');
$statement = $this->db->prepare($request);
$statement->bindValue(':host_id', $hostId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @inheritDoc
*/
public function update(Host $host): void
{
$alreadyInTransaction = $this->db->inTransaction();
if (! $alreadyInTransaction) {
$this->db->beginTransaction();
}
try {
$this->updateBasicInformations($host);
$this->updateExtendedInformations($host);
$this->updateMonitoringServer($host);
$this->updateSeverity($host);
if (! $alreadyInTransaction) {
$this->db->commit();
}
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
if (! $alreadyInTransaction) {
$this->db->rollBack();
}
throw $ex;
}
}
/**
* @param Host $host
*
* @throws \Throwable
*/
private function updateMonitoringServer(Host $host): void
{
$this->deleteLinkToMonitoringServer($host->getId());
$this->addMonitoringServer($host->getId(), $host);
}
/**
* @param Host $host
*
* @throws \Throwable
*/
private function updateSeverity(Host $host): void
{
$this->deleteLinkToSeverity($host->getId());
if ($host->getSeverityId() !== null) {
$this->addSeverity($host->getId(), $host);
}
}
/**
* @param NewHost $host
*
* @throws \Throwable
*
* @return int
*/
private function addBasicInformations(NewHost $host): int
{
$request = $this->translateDbName(
<<<'SQL'
INSERT INTO `:db`.host
(
host_name,
host_address,
host_alias,
host_snmp_version,
host_snmp_community,
host_location,
geo_coords,
command_command_id,
command_command_id_arg1,
timeperiod_tp_id,
host_max_check_attempts,
host_check_interval,
host_retry_check_interval,
host_active_checks_enabled,
host_passive_checks_enabled,
host_notifications_enabled,
host_notification_options,
host_notification_interval,
timeperiod_tp_id2,
cg_additive_inheritance,
contact_additive_inheritance,
host_first_notification_delay,
host_recovery_notification_delay,
host_acknowledgement_timeout,
host_check_freshness,
host_freshness_threshold,
host_flap_detection_enabled,
host_low_flap_threshold,
host_high_flap_threshold,
host_event_handler_enabled,
command_command_id2,
command_command_id_arg2,
host_comment,
host_activate,
host_register
) VALUES
(
:name,
:address,
:alias,
:snmpVersion,
:snmpCommunity,
:timezoneId,
:geoCoords,
:checkCommandId,
:checkCommandArgs,
:checkTimeperiodId,
:maxCheckAttempts,
:normalCheckInterval,
:retryCheckInterval,
:activeCheckEnabled,
:passiveCheckEnabled,
:notificationEnabled,
:notificationOptions,
:notificationInterval,
:notificationTimeperiodId,
:addInheritedContactGroup,
:addInheritedContact,
:firstNotificationDelay,
:recoveryNotificationDelay,
:acknowledgementTimeout,
:freshnessChecked,
:freshnessThreshold,
:flapDetectionEnabled,
:lowFlapThreshold,
:highFlapThreshold,
:eventHandlerEnabled,
:eventHandlerCommandId,
:eventHandlerCommandArgs,
:comment,
:isActivated,
:hostType
)
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':hostType', HostType::Host->value, \PDO::PARAM_STR);
$this->bindHostValues($statement, $host);
$statement->execute();
return (int) $this->db->lastInsertId();
}
/**
* @param int $hostId
* @param NewHost $host
*
* @throws \Throwable
*/
private function addExtendedInformations(int $hostId, NewHost $host): void
{
$request = $this->translateDbName(
<<<'SQL'
INSERT INTO `:db`.extended_host_information
(
host_host_id,
ehi_notes_url,
ehi_notes,
ehi_action_url,
ehi_icon_image,
ehi_icon_image_alt
) VALUES
(
:hostId,
:noteUrl,
:note,
:actionUrl,
:iconId,
:iconAlternative
)
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':hostId', $hostId, \PDO::PARAM_INT);
$statement->bindValue(
':noteUrl',
$host->getNoteUrl() === ''
? null
: $host->getNoteUrl(),
\PDO::PARAM_STR
);
$statement->bindValue(
':note',
$host->getNote() === ''
? null
: $host->getNote(),
\PDO::PARAM_STR
);
$statement->bindValue(
':actionUrl',
$host->getActionUrl() === ''
? null
: $host->getActionUrl(),
\PDO::PARAM_STR
);
$statement->bindValue(':iconId', $host->getIconId(), \PDO::PARAM_INT);
$statement->bindValue(
':iconAlternative',
$host->getIconAlternative() === ''
? null
: $host->getIconAlternative(),
\PDO::PARAM_STR
);
$statement->execute();
}
/**
* @param int $hostId
* @param NewHost|Host $host
*
* @throws \Throwable
*/
private function addMonitoringServer(int $hostId, NewHost|Host $host): void
{
$request = $this->translateDbName(
<<<'SQL'
INSERT INTO `:db`.`ns_host_relation`
(
`host_host_id`,
`nagios_server_id`
) VALUES
(
:hostId,
:monitoringServerId
)
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':hostId', $hostId, \PDO::PARAM_INT);
$statement->bindValue(':monitoringServerId', $host->getMonitoringServerId(), \PDO::PARAM_INT);
$statement->execute();
}
/**
* @param int $hostId
*
* @throws \Throwable
*/
private function deleteLinkToMonitoringServer(int $hostId): void
{
$request = $this->translateDbName(
<<<'SQL'
DELETE
FROM `:db`.`ns_host_relation`
WHERE `host_host_id` = :hostId
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':hostId', $hostId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @param int $hostId
* @param NewHost|Host $host
*
* @throws \Throwable
*/
private function addSeverity(int $hostId, NewHost|Host $host): void
{
$request = $this->translateDbName(
<<<'SQL'
INSERT INTO `:db`.hostcategories_relation
(
host_host_id,
hostcategories_hc_id
) VALUES
(
:hostId,
:severityId
)
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':hostId', $hostId, \PDO::PARAM_INT);
$statement->bindValue(':severityId', $host->getSeverityId(), \PDO::PARAM_INT);
$statement->execute();
}
/**
* @param int $hostId
*
* @throws \Throwable
*/
private function deleteLinkToSeverity(int $hostId): void
{
$request = $this->translateDbName(
<<<'SQL'
DELETE hcrel
FROM `:db`.hostcategories_relation hcrel
JOIN hostcategories hc
ON hcrel.hostcategories_hc_id = hc.hc_id
AND hc.level IS NOT NULL
WHERE hcrel.host_host_id = :hostId
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':hostId', $hostId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @param Host $host
*
* @throws \Throwable
*/
private function updateBasicInformations(Host $host): void
{
$request = $this->translateDbName(
<<<'SQL'
UPDATE `:db`.host
SET
host_name = :name,
host_address = :address,
host_alias = :alias,
host_snmp_version = :snmpVersion,
host_snmp_community = :snmpCommunity,
host_location = :timezoneId,
geo_coords = :geoCoords,
command_command_id = :checkCommandId,
command_command_id_arg1 = :checkCommandArgs,
timeperiod_tp_id = :checkTimeperiodId,
host_max_check_attempts = :maxCheckAttempts,
host_check_interval = :normalCheckInterval,
host_retry_check_interval = :retryCheckInterval,
host_active_checks_enabled = :activeCheckEnabled,
host_passive_checks_enabled = :passiveCheckEnabled,
host_notifications_enabled = :notificationEnabled,
host_notification_options = :notificationOptions,
host_notification_interval = :notificationInterval,
timeperiod_tp_id2 = :notificationTimeperiodId,
cg_additive_inheritance = :addInheritedContactGroup,
contact_additive_inheritance = :addInheritedContact,
host_first_notification_delay = :firstNotificationDelay,
host_recovery_notification_delay = :recoveryNotificationDelay,
host_acknowledgement_timeout = :acknowledgementTimeout,
host_check_freshness = :freshnessChecked,
host_freshness_threshold = :freshnessThreshold,
host_flap_detection_enabled = :flapDetectionEnabled,
host_low_flap_threshold = :lowFlapThreshold,
host_high_flap_threshold = :highFlapThreshold,
host_event_handler_enabled = :eventHandlerEnabled,
command_command_id2 = :eventHandlerCommandId,
command_command_id_arg2 = :eventHandlerCommandArgs,
host_comment = :comment,
host_activate = :isActivated
WHERE host_id = :host_id
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':host_id', $host->getId(), \PDO::PARAM_INT);
$this->bindHostValues($statement, $host);
$statement->execute();
}
/**
* @param Host $host
*
* @throws \Throwable
*/
private function updateExtendedInformations(Host $host): void
{
$request = $this->translateDbName(
<<<'SQL'
UPDATE `:db`.extended_host_information
SET
ehi_notes_url = :noteUrl,
ehi_notes = :note,
ehi_action_url = :actionUrl,
ehi_icon_image = :iconId,
ehi_icon_image_alt = :iconAlternative
WHERE host_host_id = :hostId
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':hostId', $host->getId(), \PDO::PARAM_INT);
$statement->bindValue(
':noteUrl',
$host->getNoteUrl() === ''
? null
: $host->getNoteUrl(),
\PDO::PARAM_STR
);
$statement->bindValue(
':note',
$host->getNote() === ''
? null
: $host->getNote(),
\PDO::PARAM_STR
);
$statement->bindValue(
':actionUrl',
$host->getActionUrl() === ''
? null
: $host->getActionUrl(),
\PDO::PARAM_STR
);
$statement->bindValue(':iconId', $host->getIconId(), \PDO::PARAM_INT);
$statement->bindValue(
':iconAlternative',
$host->getIconAlternative() === ''
? null
: $host->getIconAlternative(),
\PDO::PARAM_STR
);
$statement->execute();
}
/**
* @param \PDOStatement $statement
* @param NewHost|Host $host
*
* @throws \Throwable
*/
private function bindHostValues(\PDOStatement $statement, NewHost|Host $host): void
{
$statement->bindValue(
':name',
$host->getName(),
\PDO::PARAM_STR
);
$statement->bindValue(
':address',
$host->getAddress(),
\PDO::PARAM_STR
);
$statement->bindValue(
':alias',
$host->getAlias(),
\PDO::PARAM_STR
);
$statement->bindValue(
':snmpVersion',
$host->getSnmpVersion()?->value,
\PDO::PARAM_STR
);
$statement->bindValue(
':snmpCommunity',
$host->getSnmpCommunity() === ''
? null
: $host->getSnmpCommunity(),
\PDO::PARAM_STR
);
$statement->bindValue(
':geoCoords',
$host->getGeoCoordinates()?->__toString(),
\PDO::PARAM_STR
);
$statement->bindValue(
':comment',
$host->getComment() === ''
? null
: $host->getComment(),
\PDO::PARAM_STR
);
$checkCommandArguments = null;
if ($host->getCheckCommandArgs() !== []) {
$checkCommandArguments = '!' . implode(
'!',
str_replace(["\n", "\t", "\r"], ['#BR#', '#T#', '#R#'], $host->getCheckCommandArgs())
);
}
$statement->bindValue(
':checkCommandArgs',
$checkCommandArguments,
\PDO::PARAM_STR
);
$eventHandlerCommandArguments = null;
if ($host->getEventHandlerCommandArgs() !== []) {
$eventHandlerCommandArguments = '!' . implode(
'!',
str_replace(["\n", "\t", "\r"], ['#BR#', '#T#', '#R#'], $host->getEventHandlerCommandArgs())
);
}
$statement->bindValue(
':notificationOptions',
$host->getNotificationOptions() === []
? null
: HostEventConverter::toString($host->getNotificationOptions()),
\PDO::PARAM_STR
);
$statement->bindValue(
':eventHandlerCommandArgs',
$eventHandlerCommandArguments,
\PDO::PARAM_STR
);
$statement->bindValue(
':timezoneId',
$host->getTimezoneId(),
\PDO::PARAM_INT
);
$statement->bindValue(
':checkCommandId',
$host->getCheckCommandId(),
\PDO::PARAM_INT
);
$statement->bindValue(
':checkTimeperiodId',
$host->getCheckTimeperiodId(),
\PDO::PARAM_INT
);
$statement->bindValue(
':notificationTimeperiodId',
$host->getNotificationTimeperiodId(),
\PDO::PARAM_INT
);
$statement->bindValue(
':eventHandlerCommandId',
$host->getEventHandlerCommandId(),
\PDO::PARAM_INT
);
$statement->bindValue(
':maxCheckAttempts',
$host->getMaxCheckAttempts(),
\PDO::PARAM_INT
);
$statement->bindValue(
':normalCheckInterval',
$host->getNormalCheckInterval(),
\PDO::PARAM_INT
);
$statement->bindValue(
':retryCheckInterval',
$host->getRetryCheckInterval(),
\PDO::PARAM_INT
);
$statement->bindValue(
':notificationInterval',
$host->getNotificationInterval(),
\PDO::PARAM_INT
);
$statement->bindValue(
':firstNotificationDelay',
$host->getFirstNotificationDelay(),
\PDO::PARAM_INT
);
$statement->bindValue(
':recoveryNotificationDelay',
$host->getRecoveryNotificationDelay(),
\PDO::PARAM_INT
);
$statement->bindValue(
':acknowledgementTimeout',
$host->getAcknowledgementTimeout(),
\PDO::PARAM_INT
);
$statement->bindValue(
':freshnessThreshold',
$host->getFreshnessThreshold(),
\PDO::PARAM_INT
);
$statement->bindValue(
':lowFlapThreshold',
$host->getLowFlapThreshold(),
\PDO::PARAM_INT
);
$statement->bindValue(
':highFlapThreshold',
$host->getHighFlapThreshold(),
\PDO::PARAM_INT
);
$statement->bindValue(
':freshnessChecked',
YesNoDefaultConverter::toString($host->getFreshnessChecked()),
\PDO::PARAM_STR
);
$statement->bindValue(
':activeCheckEnabled',
YesNoDefaultConverter::toString($host->getActiveCheckEnabled()),
\PDO::PARAM_STR
);
$statement->bindValue(
':passiveCheckEnabled',
YesNoDefaultConverter::toString($host->getPassiveCheckEnabled()),
\PDO::PARAM_STR
);
$statement->bindValue(
':notificationEnabled',
YesNoDefaultConverter::toString($host->getNotificationEnabled()),
\PDO::PARAM_STR
);
$statement->bindValue(
':flapDetectionEnabled',
YesNoDefaultConverter::toString($host->getFlapDetectionEnabled()),
\PDO::PARAM_STR
);
$statement->bindValue(
':eventHandlerEnabled',
YesNoDefaultConverter::toString($host->getEventHandlerEnabled()),
\PDO::PARAM_STR
);
$statement->bindValue(
':addInheritedContactGroup',
$host->addInheritedContactGroup() ? 1 : 0,
\PDO::PARAM_INT
);
$statement->bindValue(
':addInheritedContact',
$host->addInheritedContact() ? 1 : 0,
\PDO::PARAM_INT
);
$statement->bindValue(
':isActivated',
(new BoolToEnumNormalizer())->normalize($host->isActivated()),
\PDO::PARAM_STR
);
}
}
| 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/Repository/SmallHostFactory.php | centreon/src/Core/Host/Infrastructure/Repository/SmallHostFactory.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\Repository;
use Assert\AssertionFailedException;
use Core\Common\Domain\SimpleEntity;
use Core\Common\Domain\TrimmedString;
use Core\Host\Domain\Model\SmallHost;
/**
* @phpstan-type _SmallHost array{
* id: int,
* name: string,
* alias: string|null,
* ip_address: string,
* check_interval: int|null,
* retry_check_interval: int|null,
* is_activated: string,
* check_timeperiod_id: int|null,
* check_timeperiod_name: string|null,
* notification_timeperiod_id: int|null,
* notification_timeperiod_name: string|null,
* severity_id: int|null,
* severity_name: string|null,
* monitoring_server_id: int,
* monitoring_server_name: string,
* category_ids: string,
* hostgroup_ids: string,
* template_ids: string
* }
*/
class SmallHostFactory
{
/**
* @param _SmallHost $data
*
* @throws AssertionFailedException
*/
public static function createFromDb(array $data): SmallHost
{
$severity = $data['severity_id'] !== null && $data['severity_name'] !== null
? new SimpleEntity(
(int) $data['severity_id'],
new TrimmedString($data['severity_name']),
'Host'
) : null;
$checkTimePeriod
= $data['check_timeperiod_id'] !== null && $data['check_timeperiod_name'] !== null
? new SimpleEntity(
(int) $data['check_timeperiod_id'],
new TrimmedString($data['check_timeperiod_name']),
'Host'
) : null;
$notificationTimePeriod
= $data['notification_timeperiod_id'] !== null && $data['notification_timeperiod_name'] !== null
? new SimpleEntity(
(int) $data['notification_timeperiod_id'],
new TrimmedString($data['notification_timeperiod_name']),
'Host'
) : null;
$host = new SmallHost(
(int) $data['id'],
new TrimmedString($data['name']),
$data['alias'] !== null ? new TrimmedString($data['alias']) : null,
new TrimmedString($data['ip_address']),
self::intOrNull($data, 'check_interval'),
self::intOrNull($data, 'retry_check_interval'),
$data['is_activated'] === '1',
new SimpleEntity(
(int) $data['monitoring_server_id'],
new TrimmedString($data['monitoring_server_name']),
'Host'
),
$checkTimePeriod,
$notificationTimePeriod,
$severity,
);
if ($data['category_ids'] !== null) {
$categoryIds = explode(',', $data['category_ids']);
foreach ($categoryIds as $categoryId) {
$host->addCategoryId((int) $categoryId);
}
}
if ($data['hostgroup_ids'] !== null) {
$groupIds = explode(',', $data['hostgroup_ids']);
foreach ($groupIds as $groupId) {
$host->addGroupId((int) $groupId);
}
}
if ($data['template_ids'] !== null) {
$templateIds = explode(',', $data['template_ids']);
foreach ($templateIds as $templateId) {
$host->addTemplateId((int) $templateId);
}
}
return $host;
}
/**
* @param _SmallHost $data
* @param string $property
*
* @return int|null
*/
private static function intOrNull(array $data, string $property): ?int
{
return array_key_exists($property, $data) && $data[$property] !== null
? (int) $data[$property]
: 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/Host/Infrastructure/Repository/DbWriteRealTimeHostRepository.php | centreon/src/Core/Host/Infrastructure/Repository/DbWriteRealTimeHostRepository.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\Repository;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Host\Application\Repository\WriteRealTimeHostRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
class DbWriteRealTimeHostRepository extends AbstractRepositoryRDB implements WriteRealTimeHostRepositoryInterface
{
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function addHostToResourceAcls(int $hostId, array $accessGroups): void
{
$accessGroupIds = array_map(
fn (AccessGroup $accessGroup) => $accessGroup->getId(),
$accessGroups
);
$request = <<<'SQL'
INSERT INTO `:dbstg`.`centreon_acl`(`group_id`, `host_id`, `service_id`)
VALUES
SQL;
foreach ($accessGroupIds as $accessGroupId) {
$request .= <<<SQL
(:group_{$accessGroupId}, :host_id, NULL),
SQL;
}
$statement = $this->db->prepare($this->translateDbName(trim($request, ',')));
foreach ($accessGroupIds as $accessGroupId) {
$statement->bindValue(':group_' . $accessGroupId, $accessGroupId, \PDO::PARAM_INT);
}
$statement->bindValue(':host_id', $hostId, \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/Host/Infrastructure/Repository/ApiReadHostRepository.php | centreon/src/Core/Host/Infrastructure/Repository/ApiReadHostRepository.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\Repository;
use Centreon\Domain\Repository\RepositoryException;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Common\Infrastructure\Repository\ApiRepositoryTrait;
use Core\Common\Infrastructure\Repository\ApiResponseTrait;
use Core\Common\Infrastructure\Repository\ValuesByPackets;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
use Core\Host\Domain\Model\Host;
use Core\Host\Domain\Model\HostNamesById;
use Core\Host\Domain\Model\TinyHost;
use Psr\Log\LoggerInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class ApiReadHostRepository implements ReadHostRepositoryInterface
{
use ApiResponseTrait;
use ApiRepositoryTrait;
public const URL_SAFETY_MARGIN = 50;
public function __construct(
private readonly HttpClientInterface $httpClient,
private readonly RouterInterface $router,
private readonly LoggerInterface $logger,
) {
}
/**
* @inheritDoc
*/
public function existsByName(string $hostName): bool
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function findById(int $hostId): ?Host
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function findByIds(array $hostIds): array
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function findByNames(array $hostNames): array
{
$apiEndpoint = $this->router->generate('FindHosts');
$options = [
'verify_peer' => true,
'verify_host' => true,
'timeout' => $this->timeout,
'headers' => ['X-AUTH-TOKEN: ' . $this->authenticationToken],
];
if ($this->proxy !== null) {
$options['proxy'] = $this->proxy;
$this->logger->info('Getting hosts using proxy');
}
$debugOptions = $options;
unset($debugOptions['headers'][0]);
$this->logger->debug('Connexion configuration', [
'url' => $apiEndpoint,
'options' => $debugOptions,
]);
$url = $this->url . $apiEndpoint;
/**
* @param list<string> $hostNames
*
* @throws TransportExceptionInterface
* @throws ClientExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ServerExceptionInterface
*
* @return \Generator<TinyHost>
*/
$findHosts = function (array $hostNames) use ($url, $options): \Generator {
// Surround hostnames with double quotes
$hostNames = array_map(fn (string $name) => sprintf('"%s"', $name), $hostNames);
$options['query'] = [
'limit' => count($hostNames),
'search' => sprintf('{"name": {"$in": [%s]}}', implode(',', $hostNames)),
];
$this->logger->debug('Call API', ['url' => $url, 'query_parameter' => $options['query']['search']]);
/**
* @var array{
* result: array<array{id: int, name: string, alias: string|null, monitoring_server: array{id: int}}>
* } $response
*/
$response = $this->getResponseOrFail($this->httpClient->request('GET', $url, $options));
foreach ($response['result'] as $result) {
yield (TinyHostFactory::createFromApi(...))($result);
}
};
$hosts = [];
$maxQueryStringLength = $this->maxQueryStringLength - mb_strlen($url) - self::URL_SAFETY_MARGIN;
foreach (new ValuesByPackets($hostNames, $this->maxItemsByRequest, $maxQueryStringLength) as $names) {
foreach ($findHosts($names) as $host) {
$hosts[] = $host;
}
}
return $hosts;
}
/**
* @inheritDoc
*/
public function findByRequestParameters(RequestParametersInterface $requestParameters): array
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function findByRequestParametersAndAccessGroups(
RequestParametersInterface $requestParameters,
array $accessGroups,
): array {
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function findParents(int $hostId): array
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function exists(int $hostId): bool
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function existsByAccessGroups(int $hostId, array $accessGroups): bool
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function findNames(array $hostGroupIds): HostNamesById
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function exist(array $hostIds): array
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function findAll(): array
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function findByHostGroup(int $hostGroupId): array
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function findByHostGroupAndAccessGroups(int $hostGroupId, array $accessGroups): array
{
throw RepositoryException::notYetImplemented();
}
}
| 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/Repository/DbReadHostRepository.php | centreon/src/Core/Host/Infrastructure/Repository/DbReadHostRepository.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\Repository;
use Assert\AssertionFailedException;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Repository\RepositoryException;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use Core\Common\Application\Converter\YesNoDefaultConverter;
use Core\Common\Domain\HostType;
use Core\Common\Domain\SimpleEntity;
use Core\Common\Domain\TrimmedString;
use Core\Common\Domain\YesNoDefault;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait;
use Core\Common\Infrastructure\RequestParameters\Normalizer\BoolToEnumNormalizer;
use Core\Domain\Common\GeoCoords;
use Core\Host\Application\Converter\HostEventConverter;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
use Core\Host\Domain\Model\Host;
use Core\Host\Domain\Model\HostNamesById;
use Core\Host\Domain\Model\SnmpVersion;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Utility\SqlConcatenator;
/**
* @phpstan-type _Host array{
* host_id: int,
* monitoring_server_id: int,
* host_name: string,
* host_address: string,
* host_alias: string|null,
* host_snmp_version: string|null,
* host_snmp_community: string|null,
* geo_coords: string|null,
* host_location: int|null,
* command_command_id: int|null,
* command_command_id_arg1: string|null,
* timeperiod_tp_id: int|null,
* host_max_check_attempts: int|null,
* host_check_interval: int|null,
* host_retry_check_interval: int|null,
* host_active_checks_enabled: string|null,
* host_passive_checks_enabled: string|null,
* host_notifications_enabled: string|null,
* host_notification_options: string|null,
* host_notification_interval: int|null,
* timeperiod_tp_id2: int|null,
* cg_additive_inheritance: int|null,
* contact_additive_inheritance: int|null,
* host_first_notification_delay: int|null,
* host_recovery_notification_delay: int|null,
* host_acknowledgement_timeout: int|null,
* host_check_freshness: string|null,
* host_freshness_threshold: int|null,
* host_flap_detection_enabled: string|null,
* host_low_flap_threshold: int|null,
* host_high_flap_threshold: int|null,
* host_event_handler_enabled: string|null,
* command_command_id2: int|null,
* command_command_id_arg2: string|null,
* host_comment: string|null,
* host_activate: string|null,
* ehi_notes_url: string|null,
* ehi_notes: string|null,
* ehi_action_url: string|null,
* ehi_icon_image: int|null,
* ehi_icon_image_alt: string|null,
* severity_id: int|null
* }
* @phpstan-type _TinyHost array{
* id: int,
* name: string,
* alias: string|null,
* ip_address: string,
* check_interval: int|null,
* retry_check_interval: int|null,
* is_activated: string,
* check_timeperiod_id: int|null,
* check_timeperiod_name: string|null,
* notification_timeperiod_id: int|null,
* notification_timeperiod_name: string|null,
* severity_id: int|null,
* severity_name: string|null,
* monitoring_server_id: int,
* monitoring_server_name: string,
* category_ids: string,
* hostgroup_ids: string,
* template_ids: string
* }
*/
class DbReadHostRepository extends AbstractRepositoryRDB implements ReadHostRepositoryInterface
{
use LoggerTrait;
use SqlMultipleBindTrait;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @param int $maxItemsByRequest
*/
public function setMaxItemsByRequest(int $maxItemsByRequest): void
{
if ($maxItemsByRequest > 0) {
$this->maxItemsByRequest = $maxItemsByRequest;
}
}
/**
* @inheritDoc
*/
public function existsByName(string $hostName): bool
{
$this->info('Check existence of host with name #' . $hostName);
$request = $this->translateDbName(
<<<'SQL'
SELECT 1
FROM `:db`.host
WHERE host_name = :hostName
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':hostName', $hostName, \PDO::PARAM_STR);
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* @inheritDoc
*/
public function exists(int $hostId): bool
{
$request = $this->translateDbName(
<<<'SQL'
SELECT 1
FROM `:db`.host
WHERE host_id = :host_id
AND host_register = '1'
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':host_id', $hostId, \PDO::PARAM_INT);
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* @inheritDoc
*/
public function exist(array $hostIds): array
{
$this->info('Check existence of hosts', ['host_ids' => $hostIds]);
if ($hostIds === []) {
return [];
}
$bindValues = [];
foreach ($hostIds as $index => $hostId) {
$bindValues[":host_{$index}"] = $hostId;
}
$hostIdsList = implode(', ', array_keys($bindValues));
$request = $this->translateDbName(
<<<SQL
SELECT
host_id
FROM `:db`.host
WHERE host_id IN ({$hostIdsList})
AND host_register = '1'
SQL
);
$statement = $this->db->prepare($request);
foreach ($bindValues as $bindKey => $bindValue) {
$statement->bindValue($bindKey, $bindValue, \PDO::PARAM_INT);
}
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
return $statement->fetchAll(\PDO::FETCH_COLUMN);
}
/**
* @inheritDoc
*/
public function existsByAccessGroups(int $hostId, array $accessGroups): bool
{
if ($accessGroups === []) {
$this->debug('Access groups array empty');
return false;
}
$accessGroupIds = array_map(
static fn (AccessGroup $accessGroup): int => $accessGroup->getId(),
$accessGroups
);
$concatenator = new SqlConcatenator();
$concatenator->defineSelect(
<<<'SQL'
SELECT 1
FROM `:dbstg`.centreon_acl acl
WHERE acl.host_id = :host_id
AND acl.group_id IN (:access_group_ids)
AND acl.service_id IS NULL
SQL
);
$concatenator->storeBindValueMultiple(':access_group_ids', $accessGroupIds, \PDO::PARAM_INT);
$concatenator->storeBindValue(':host_id', $hostId, \PDO::PARAM_INT);
$statement = $this->db->prepare($this->translateDbName($concatenator->__toString()));
$concatenator->bindValuesToStatement($statement);
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* @inheritDoc
*/
public function findById(int $hostId): ?Host
{
$request = $this->translateDbName(
<<<'SQL'
SELECT
h.host_id,
nsr.nagios_server_id as monitoring_server_id,
h.host_name,
h.host_address,
h.host_alias,
h.host_snmp_version,
h.host_snmp_community,
h.geo_coords,
h.host_location,
h.command_command_id,
h.command_command_id_arg1,
h.timeperiod_tp_id,
h.host_max_check_attempts,
h.host_check_interval,
h.host_retry_check_interval,
h.host_active_checks_enabled,
h.host_passive_checks_enabled,
h.host_notifications_enabled,
h.host_notification_options,
h.host_notification_interval,
h.timeperiod_tp_id2,
h.cg_additive_inheritance,
h.contact_additive_inheritance,
h.host_first_notification_delay,
h.host_recovery_notification_delay,
h.host_acknowledgement_timeout,
h.host_check_freshness,
h.host_freshness_threshold,
h.host_flap_detection_enabled,
h.host_low_flap_threshold,
h.host_high_flap_threshold,
h.host_event_handler_enabled,
h.command_command_id2,
h.command_command_id_arg2,
h.host_comment,
h.host_activate,
ehi.ehi_notes_url,
ehi.ehi_notes,
ehi.ehi_action_url,
ehi.ehi_icon_image,
ehi.ehi_icon_image_alt,
hc.hc_id as severity_id
FROM `:db`.host h
LEFT JOIN `:db`.extended_host_information ehi
ON h.host_id = ehi.host_host_id
LEFT JOIN `:db`.ns_host_relation nsr
ON nsr.host_host_id = h.host_id
LEFT JOIN `:db`.hostcategories_relation hcr
ON hcr.host_host_id = h.host_id
LEFT JOIN `:db`.hostcategories hc
ON hc.hc_id = hcr.hostcategories_hc_id
AND hc.level IS NOT NULL
WHERE h.host_id = :hostId
AND h.host_register = :hostType
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':hostId', $hostId, \PDO::PARAM_INT);
$statement->bindValue(':hostType', HostType::Host->value, \PDO::PARAM_STR);
$statement->execute();
$result = $statement->fetch(\PDO::FETCH_ASSOC);
if ($result === false) {
return null;
}
/** @var _Host $result */
return $this->createHostFromArray($result);
}
/**
* @inheritDoc
*/
public function findByIds(array $hostIds): array
{
$request = $this->translateDbName(
<<<'SQL'
SELECT
h.host_id AS id,
h.host_name AS name,
h.host_alias AS alias,
nsr.nagios_server_id AS monitoring_server_id
FROM `:db`.host h
LEFT JOIN `:db`.ns_host_relation nsr
ON nsr.host_host_id = h.host_id
WHERE h.host_id IN (%s)
SQL
);
$hosts = [];
foreach (array_chunk($hostIds, $this->maxItemsByRequest) as $ids) {
[$bindValues, $hostIdsQuery] = $this->createMultipleBindQuery($ids, ':id_');
$finalRequest = sprintf($request, $hostIdsQuery);
$statement = $this->db->prepare($finalRequest);
foreach ($bindValues as $bindKey => $hostGroupId) {
$statement->bindValue($bindKey, $hostGroupId, \PDO::PARAM_INT);
}
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
/** @var array{id: int, name: string, alias: string|null, monitoring_server_id: int} $result */
foreach ($statement as $result) {
$hosts[$result['id']] = TinyHostFactory::createFromDb($result);
}
}
return $hosts;
}
/**
* @inheritDoc
*/
public function findByNames(array $hostNames): array
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function findParents(int $hostId): array
{
$this->info('Find parent IDs of host with ID #' . $hostId);
$request = $this->translateDbName(
<<<'SQL'
WITH RECURSIVE parents AS (
SELECT * FROM `:db`.`host_template_relation`
WHERE `host_host_id` = :hostId
UNION
SELECT rel.* FROM `:db`.`host_template_relation` AS rel, parents AS p
WHERE rel.`host_host_id` = p.`host_tpl_id`
)
SELECT `host_host_id` AS child_id, `host_tpl_id` AS parent_id, `order`
FROM parents
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':hostId', $hostId, \PDO::PARAM_INT);
$statement->execute();
return $statement->fetchAll(\PDO::FETCH_ASSOC);
}
/**
* @inheritDoc
*/
public function findNames(array $hostIds): HostNamesById
{
$concatenator = new SqlConcatenator();
$hostIds = array_unique($hostIds);
$concatenator->defineSelect(
<<<'SQL'
SELECT h.host_id, h.host_name
FROM `:db`.host h
WHERE h.host_id IN (:hostIds)
AND h.host_register = '1'
SQL
);
$concatenator->storeBindValueMultiple(':hostIds', $hostIds, \PDO::PARAM_INT);
$statement = $this->db->prepare($this->translateDbName($concatenator->__toString()));
$concatenator->bindValuesToStatement($statement);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
$groupNames = new HostNamesById();
foreach ($statement as $result) {
/** @var array{host_id:int,host_name:string} $result */
$groupNames->addName(
$result['host_id'],
new TrimmedString($result['host_name'])
);
}
return $groupNames;
}
/**
* @inheritDoc
*/
public function findByRequestParametersAndAccessGroups(
RequestParametersInterface $requestParameters,
array $accessGroups,
): array {
$sqlTranslator = new SqlRequestParametersTranslator($requestParameters);
$sqlTranslator->setConcordanceArray([
'id' => 'h.host_id',
'name' => 'h.host_name',
'address' => 'h.host_address',
'poller.id' => 'ns.id',
'poller.name' => 'ns.name',
'is_activated' => 'h.host_activate',
'category.id' => 'hc.hc_id',
'category.name' => 'hc.hc_name',
'severity.id' => 'sev.hc_id',
'severity.name' => 'sev.hc_name',
'group.id' => 'hg.hg_id',
'group.name' => 'hg.hg_name',
]);
$sqlTranslator->addNormalizer('is_activated', new BoolToEnumNormalizer());
$aclQuery = '';
$accessGroupsBindValues = [];
$hostGroupAcl = '';
$hostCategoriesAcl = '';
$hostSeveritiesAcl = '';
$monitoringServersAcl = '';
if ($accessGroups !== []) {
[$accessGroupsBindValues, $accessGroupIdsQuery] = $this->createMultipleBindQuery(
array_map(fn (AccessGroup $accessGroup) => $accessGroup->getId(), $accessGroups),
':acl_'
);
$aclQuery = <<<SQL
INNER JOIN `:dbstg`.centreon_acl acl
ON acl.host_id = h.host_id
AND acl.service_id IS NULL
AND acl.group_id IN ({$accessGroupIdsQuery})
SQL;
$hostGroupAcl = <<<SQL
AND hgr.hostgroup_hg_id IN (
SELECT aclhgr.hg_hg_id AS id
FROM `:db`.acl_resources_hg_relations aclhgr
INNER JOIN `:db`.acl_resources aclr
ON aclr.acl_res_id = aclhgr.acl_res_id
INNER JOIN `:db`.acl_res_group_relations aclrgr
ON aclrgr.acl_res_id = aclr.acl_res_id
AND aclrgr.acl_group_id IN ({$accessGroupIdsQuery})
)
SQL;
if ($this->hasHostCategoriesFilter($accessGroupIdsQuery, $accessGroupsBindValues)) {
$hostCategoriesAcl = <<<SQL
AND hc.hc_id IN (
SELECT hc.hc_id AS id
FROM `:db`.hostcategories hc
INNER JOIN `:db`.acl_resources_hc_relations aclhcr_hc
ON aclhcr_hc.hc_id = hc.hc_id
INNER JOIN `:db`.acl_resources aclr_hc
ON aclr_hc.acl_res_id = aclhcr_hc.acl_res_id
INNER JOIN `:db`.acl_res_group_relations aclrgr_hc
ON aclrgr_hc.acl_res_id = aclr_hc.acl_res_id
AND aclrgr_hc.acl_group_id IN ({$accessGroupIdsQuery})
WHERE hc.level IS NULL
)
SQL;
$hostSeveritiesAcl = <<<SQL
AND sev.hc_id IN (
SELECT sev.hc_id AS id
FROM `:db`.hostcategories sev
INNER JOIN `:db`.acl_resources_hc_relations aclhcr_sev
ON sev.hc_id = aclhcr_sev.hc_id
INNER JOIN `:db`.acl_resources aclr_sev
ON aclr_sev.acl_res_id = aclhcr_sev.acl_res_id
INNER JOIN `:db`.acl_res_group_relations aclrgr_sev
ON aclrgr_sev.acl_res_id = aclr_sev.acl_res_id
AND aclrgr_sev.acl_group_id IN ({$accessGroupIdsQuery})
WHERE sev.level IS NOT NULL
)
SQL;
}
if ($this->hasMonitoringServerFilter($accessGroupIdsQuery, $accessGroupsBindValues)) {
$monitoringServersAcl = <<<SQL
AND ns.id IN (
SELECT aclpoller.poller_id AS id
FROM `:db`.acl_resources_poller_relations aclpoller
INNER JOIN `:db`.acl_resources aclr_poller
ON aclr_poller.acl_res_id = aclpoller.acl_res_id
INNER JOIN `:db`.acl_res_group_relations aclrgr_poller
ON aclrgr_poller.acl_res_id = aclr_poller.acl_res_id
AND aclrgr_poller.acl_group_id IN ({$accessGroupIdsQuery})
)
SQL;
}
}
$request = <<<SQL
SELECT SQL_CALC_FOUND_ROWS
h.host_id AS id,
h.host_name AS name,
h.host_alias AS alias,
h.host_address AS ip_address,
h.host_check_interval AS check_interval,
h.host_retry_check_interval AS retry_check_interval,
h.host_activate AS is_activated,
ctime.tp_id AS check_timeperiod_id,
ctime.tp_name AS check_timeperiod_name,
ntime.tp_id AS notification_timeperiod_id,
ntime.tp_name AS notification_timeperiod_name,
(
SELECT sev.hc_id
FROM `:db`.hostcategories sev
INNER JOIN `:db`.hostcategories_relation hcr
ON sev.hc_id = hcr.hostcategories_hc_id
WHERE sev.level IS NOT NULL
AND hcr.host_host_id = h.host_id {$hostSeveritiesAcl}
ORDER BY sev.level, sev.hc_id
LIMIT 1
) AS severity_id,
(
SELECT sev.hc_name
FROM `:db`.hostcategories sev
INNER JOIN `:db`.hostcategories_relation hcr
ON sev.hc_id = hcr.hostcategories_hc_id
WHERE sev.level IS NOT NULL
AND hcr.host_host_id = h.host_id {$hostSeveritiesAcl}
ORDER BY sev.level, sev.hc_id
LIMIT 1
) AS severity_name,
ns.id AS monitoring_server_id,
ns.name AS monitoring_server_name,
GROUP_CONCAT(DISTINCT hc.hc_id) AS category_ids,
GROUP_CONCAT(DISTINCT hgr.hostgroup_hg_id) AS hostgroup_ids,
GROUP_CONCAT(DISTINCT htpl.host_tpl_id) AS template_ids
FROM `:db`.host h {$aclQuery}
LEFT JOIN `:db`.hostcategories_relation hcr
ON hcr.host_host_id = h.host_id
LEFT JOIN `:db`.hostcategories hc
ON hc.hc_id = hcr.hostcategories_hc_id
AND hc.level IS NULL {$hostCategoriesAcl}
LEFT JOIN `:db`.hostgroup_relation hgr
ON hgr.host_host_id = h.host_id {$hostGroupAcl}
LEFT JOIN `:db`.hostgroup hg
ON hg.hg_id = hgr.hostgroup_hg_id
LEFT JOIN `:db`.ns_host_relation nsr
ON nsr.host_host_id = h.host_id
INNER JOIN `:db`.nagios_server ns
ON ns.id = nsr.nagios_server_id {$monitoringServersAcl}
LEFT JOIN `:db`.host_template_relation htpl
ON htpl.host_host_id = h.host_id
LEFT JOIN `:db`.timeperiod ctime
ON ctime.tp_id = h.timeperiod_tp_id
LEFT JOIN `:db`.timeperiod ntime
ON ntime.tp_id = h.timeperiod_tp_id2
SQL;
// Search
$request .= $search = $sqlTranslator->translateSearchParameterToSql();
$request .= $search !== null
? ' AND h.host_register = \'1\''
: ' WHERE h.host_register = \'1\'';
$request .= ' GROUP BY h.host_id, ns.id, ns.name';
// Sort
$sortRequest = $sqlTranslator->translateSortParameterToSql();
$request .= ! is_null($sortRequest)
? $sortRequest
: ' ORDER BY h.host_id ASC';
// Pagination
$request .= $sqlTranslator->translatePaginationToSql();
$request = $this->translateDbName($request);
$statement = $this->db->prepare($request);
$hosts = [];
if ($statement === false) {
return $hosts;
}
foreach ($sqlTranslator->getSearchValues() as $key => $data) {
$type = key($data);
if ($type !== null) {
$value = $data[$type];
$statement->bindValue($key, $value, $type);
}
}
foreach ($accessGroupsBindValues as $bindKey => $hostGroupId) {
$statement->bindValue($bindKey, $hostGroupId, \PDO::PARAM_INT);
}
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
// Set total
$result = $this->db->query('SELECT FOUND_ROWS()');
if ($result !== false && ($total = $result->fetchColumn()) !== false) {
$sqlTranslator->getRequestParameters()->setTotal((int) $total);
}
foreach ($statement as $data) {
/** @var _TinyHost $data */
$hosts[] = SmallHostFactory::createFromDb($data);
}
return $hosts;
}
/**
* @inheritDoc
*/
public function findAll(): array
{
$request = $this->translateDbName(
<<<'SQL'
SELECT
h.host_id,
nsr.nagios_server_id as monitoring_server_id,
h.host_name,
h.host_address,
h.host_alias,
h.host_snmp_version,
h.host_snmp_community,
h.geo_coords,
h.host_location,
h.command_command_id,
h.command_command_id_arg1,
h.timeperiod_tp_id,
h.host_max_check_attempts,
h.host_check_interval,
h.host_retry_check_interval,
h.host_active_checks_enabled,
h.host_passive_checks_enabled,
h.host_notifications_enabled,
h.host_notification_options,
h.host_notification_interval,
h.timeperiod_tp_id2,
h.cg_additive_inheritance,
h.contact_additive_inheritance,
h.host_first_notification_delay,
h.host_recovery_notification_delay,
h.host_acknowledgement_timeout,
h.host_check_freshness,
h.host_freshness_threshold,
h.host_flap_detection_enabled,
h.host_low_flap_threshold,
h.host_high_flap_threshold,
h.host_event_handler_enabled,
h.command_command_id2,
h.command_command_id_arg2,
h.host_comment,
h.host_activate,
ehi.ehi_notes_url,
ehi.ehi_notes,
ehi.ehi_action_url,
ehi.ehi_icon_image,
ehi.ehi_icon_image_alt,
hc.hc_id as severity_id
FROM `:db`.host h
LEFT JOIN `:db`.extended_host_information ehi
ON h.host_id = ehi.host_host_id
LEFT JOIN `:db`.ns_host_relation nsr
ON nsr.host_host_id = h.host_id
LEFT JOIN `:db`.hostcategories_relation hcr
ON hcr.host_host_id = h.host_id
LEFT JOIN `:db`.hostcategories hc
ON hc.hc_id = hcr.hostcategories_hc_id
AND hc.level IS NOT NULL
WHERE h.host_register = :hostType
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':hostType', HostType::Host->value, \PDO::PARAM_STR);
$statement->execute();
$hosts = [];
while ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
/** @var _Host $result */
$hosts[] = $this->createHostFromArray($result);
}
return $hosts;
}
/**
* {@inheritDoc}
*
* @throws AssertionFailedException
*/
public function findByRequestParameters(RequestParametersInterface $requestParameters): array
{
return $this->findByRequestParametersAndAccessGroups($requestParameters, []);
}
/**
* @inheritDoc
*/
public function findByHostGroup(int $hostGroupId): array
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
SELECT host_id, host_name FROM host
INNER JOIN hostgroup_relation
ON host_host_id = host_id
WHERE hostgroup_hg_id = :hostGroupId
AND host.host_register = '1'
SQL
));
$statement->bindValue(':hostGroupId', $hostGroupId, \PDO::PARAM_INT);
$statement->execute();
$hostsByHostGroup = [];
while ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
/** @var array{host_id: int, host_name: string} $result */
$hostsByHostGroup[] = $this->createSimpleEntity($result['host_id'], $result['host_name']);
}
return $hostsByHostGroup;
}
/**
* @inheritDoc
*/
public function findByHostGroupAndAccessGroups(int $hostGroupId, array $accessGroups): array
{
if ($accessGroups === []) {
return [];
}
[$accessGroupsBindValues, $accessGroupIdsQuery] = $this->createMultipleBindQuery(
array_map(fn (AccessGroup $accessGroup) => $accessGroup->getId(), $accessGroups),
':acl_'
);
$aclQuery = <<<SQL
INNER JOIN `:dbstg`.centreon_acl acl
ON acl.host_id = h.host_id
AND acl.service_id IS NULL
AND acl.group_id IN ({$accessGroupIdsQuery})
SQL;
$statement = $this->db->prepare($this->translateDbName(
<<<SQL
SELECT h.host_id, h.host_name
FROM host h
INNER JOIN hostgroup_relation hgr
ON hgr.host_host_id = h.host_id
{$aclQuery}
WHERE hostgroup_hg_id = :hostGroupId
AND h.host_register = '1'
GROUP BY h.host_id
SQL
));
$statement->bindValue(':hostGroupId', $hostGroupId, \PDO::PARAM_INT);
foreach ($accessGroupsBindValues as $bindKey => $accessGroupId) {
$statement->bindValue($bindKey, $accessGroupId, \PDO::PARAM_INT);
}
$statement->execute();
$hostsByHostGroup = [];
while ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
/** @var array{host_id: int, host_name: string} $result */
$hostsByHostGroup[] = $this->createSimpleEntity($result['host_id'], $result['host_name']);
}
return $hostsByHostGroup;
}
/**
* @param string $accessGroupIdsQuery
* @param array<string, mixed> $accessGroupsBindValues
*
* @return bool
*/
private function hasHostCategoriesFilter(string $accessGroupIdsQuery, array $accessGroupsBindValues): bool
{
$hostCategoriesQuery = <<<SQL
SELECT COUNT(*)
FROM `:db`.hostcategories hc
INNER JOIN `:db`.acl_resources_hc_relations aclhcr_hc
ON aclhcr_hc.hc_id = hc.hc_id
INNER JOIN `:db`.acl_resources aclr_hc
ON aclr_hc.acl_res_id = aclhcr_hc.acl_res_id
INNER JOIN `:db`.acl_res_group_relations aclrgr_hc
ON aclrgr_hc.acl_res_id = aclr_hc.acl_res_id
AND aclrgr_hc.acl_group_id IN ({$accessGroupIdsQuery})
SQL;
$statement = $this->db->prepare($this->translateDbName($hostCategoriesQuery));
foreach ($accessGroupsBindValues as $bindKey => $hostGroupId) {
$statement->bindValue($bindKey, $hostGroupId, \PDO::PARAM_INT);
}
$statement->execute();
return ($numberOfElements = $statement->fetchColumn()) && ((int) $numberOfElements) > 0;
}
/**
* @param string $accessGroupIdsQuery
* @param array<string, mixed> $accessGroupsBindValues
*
* @return bool
*/
private function hasMonitoringServerFilter(string $accessGroupIdsQuery, array $accessGroupsBindValues): bool
{
$monitoringServersQuery = <<<SQL
SELECT COUNT(*)
FROM `:db`.acl_resources_poller_relations aclpoller
INNER JOIN `:db`.acl_resources aclr_poller
ON aclr_poller.acl_res_id = aclpoller.acl_res_id
INNER JOIN `:db`.acl_res_group_relations aclrgr_poller
ON aclrgr_poller.acl_res_id = aclr_poller.acl_res_id
AND aclrgr_poller.acl_group_id IN ({$accessGroupIdsQuery})
SQL;
$statement = $this->db->prepare($this->translateDbName($monitoringServersQuery));
foreach ($accessGroupsBindValues as $bindKey => $hostGroupId) {
$statement->bindValue($bindKey, $hostGroupId, \PDO::PARAM_INT);
}
$statement->execute();
return ($numberOfElements = $statement->fetchColumn()) && ((int) $numberOfElements) > 0;
}
/**
* @param _Host $result
*
* @throws \Throwable
*
* @return Host
*/
private function createHostFromArray(array $result): Host
{
/* Note:
* Due to legacy installations
* some properties (host_snmp_version, host_location)
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Host/Infrastructure/API/AddHost/AddHostSaasPresenter.php | centreon/src/Core/Host/Infrastructure/API/AddHost/AddHostSaasPresenter.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\AddHost;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\CreatedResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Host\Application\UseCase\AddHost\AddHostPresenterInterface;
use Core\Host\Application\UseCase\AddHost\AddHostResponse;
use Core\Infrastructure\Common\Presenter\PresenterTrait;
class AddHostSaasPresenter extends AbstractPresenter implements AddHostPresenterInterface
{
use PresenterTrait;
/**
* @inheritDoc
*/
public function presentResponse(AddHostResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
$this->present(
new CreatedResponse(
$response->id,
[
'id' => $response->id,
'monitoring_server_id' => $response->monitoringServerId,
'name' => $response->name,
'address' => $response->address,
'snmp_version' => $response->snmpVersion,
'geo_coords' => $response->geoCoords,
'icon_id' => $response->iconId,
'alias' => $this->emptyStringAsNull($response->alias),
'max_check_attempts' => $response->maxCheckAttempts,
'normal_check_interval' => $response->normalCheckInterval,
'retry_check_interval' => $response->retryCheckInterval,
'note_url' => $this->emptyStringAsNull($response->noteUrl),
'note' => $this->emptyStringAsNull($response->note),
'action_url' => $this->emptyStringAsNull($response->actionUrl),
'timezone_id' => $response->timezoneId,
'severity_id' => $response->severityId,
'check_timeperiod_id' => $response->checkTimeperiodId,
'event_handler_enabled' => $response->eventHandlerEnabled,
'event_handler_command_args' => $response->eventHandlerCommandArgs,
'check_command_id' => $response->checkCommandId,
'check_command_args' => $response->checkCommandArgs,
'categories' => array_map(
fn (array $category) => [
'id' => $category['id'],
'name' => $category['name'],
],
$response->categories
),
'groups' => array_map(
fn (array $group) => [
'id' => $group['id'],
'name' => $group['name'],
],
$response->groups
),
'templates' => array_map(
fn (array $template) => [
'id' => $template['id'],
'name' => $template['name'],
],
$response->templates
),
'macros' => array_map(
fn (array $macro) => [
'id' => $macro['id'],
'name' => $macro['name'],
'value' => $macro['isPassword'] ? null : $macro['value'],
'is_password' => $macro['isPassword'],
'description' => $this->emptyStringAsNull($macro['description']),
],
$response->macros
),
]
)
);
// NOT setting location as required route does not currently exist
}
}
}
| 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/AddHost/AddHostController.php | centreon/src/Core/Host/Infrastructure/API/AddHost/AddHostController.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\AddHost;
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\AddHost\AddHost;
use Core\Host\Application\UseCase\AddHost\AddHostRequest;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class AddHostController extends AbstractController
{
use LoggerTrait;
/**
* @param Request $request
* @param AddHost $useCase
* @param AddHostSaasPresenter $saasPresenter
* @param AddHostOnPremPresenter $onPremPresenter
* @param bool $isCloudPlatform
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
Request $request,
AddHost $useCase,
AddHostSaasPresenter $saasPresenter,
AddHostOnPremPresenter $onPremPresenter,
bool $isCloudPlatform,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
if ($isCloudPlatform) {
return $this->executeUseCaseSaas($useCase, $saasPresenter, $request);
}
return $this->executeUseCaseOnPrem($useCase, $onPremPresenter, $request);
}
/**
* @param AddHost $useCase
* @param AddHostOnPremPresenter $presenter
* @param Request $request
*
* @return Response
*/
private function executeUseCaseOnPrem(
AddHost $useCase,
AddHostOnPremPresenter $presenter,
Request $request,
): Response {
try {
/**
* @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, __DIR__ . '/AddHostOnPremSchema.json');
$dto = new AddHostRequest();
$dto->name = $data['name'];
$dto->address = $data['address'];
$dto->monitoringServerId = $data['monitoring_server_id'];
$dto->alias = $data['alias'] ?? '';
$dto->snmpVersion = $data['snmp_version'] ?? '';
$dto->snmpCommunity = $data['snmp_community'] ?? '';
$dto->noteUrl = $data['note_url'] ?? '';
$dto->note = $data['note'] ?? '';
$dto->actionUrl = $data['action_url'] ?? '';
$dto->iconAlternative = $data['icon_alternative'] ?? '';
$dto->comment = $data['comment'] ?? '';
$dto->geoCoordinates = $data['geo_coords'] ?? '';
$dto->checkCommandArgs = $data['check_command_args'] ?? [];
$dto->eventHandlerCommandArgs = $data['event_handler_command_args'] ?? [];
$dto->activeCheckEnabled = $data['active_check_enabled'] ?? 2;
$dto->passiveCheckEnabled = $data['passive_check_enabled'] ?? 2;
$dto->notificationEnabled = $data['notification_enabled'] ?? 2;
$dto->freshnessChecked = $data['freshness_checked'] ?? 2;
$dto->flapDetectionEnabled = $data['flap_detection_enabled'] ?? 2;
$dto->eventHandlerEnabled = $data['event_handler_enabled'] ?? 2;
$dto->timezoneId = $data['timezone_id'] ?? null;
$dto->severityId = $data['severity_id'] ?? null;
$dto->checkCommandId = $data['check_command_id'] ?? null;
$dto->checkTimeperiodId = $data['check_timeperiod_id'] ?? null;
$dto->notificationTimeperiodId = $data['notification_timeperiod_id'] ?? null;
$dto->eventHandlerCommandId = $data['event_handler_command_id'] ?? null;
$dto->iconId = $data['icon_id'] ?? null;
$dto->maxCheckAttempts = $data['max_check_attempts'] ?? null;
$dto->normalCheckInterval = $data['normal_check_interval'] ?? null;
$dto->retryCheckInterval = $data['retry_check_interval'] ?? null;
$dto->notificationOptions = $data['notification_options'] ?? null;
$dto->notificationInterval = $data['notification_interval'] ?? null;
$dto->firstNotificationDelay = $data['first_notification_delay'] ?? null;
$dto->recoveryNotificationDelay = $data['recovery_notification_delay'] ?? null;
$dto->acknowledgementTimeout = $data['acknowledgement_timeout'] ?? null;
$dto->freshnessThreshold = $data['freshness_threshold'] ?? null;
$dto->lowFlapThreshold = $data['low_flap_threshold'] ?? null;
$dto->highFlapThreshold = $data['high_flap_threshold'] ?? null;
$dto->categories = $data['categories'] ?? [];
$dto->groups = $data['groups'] ?? [];
$dto->templates = $data['templates'] ?? [];
$dto->macros = $data['macros'] ?? [];
$dto->addInheritedContactGroup = $data['add_inherited_contact_group'] ?? false;
$dto->addInheritedContact = $data['add_inherited_contact'] ?? false;
$dto->isActivated = $data['is_activated'] ?? true;
$useCase($dto, $presenter);
} 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::addHost()));
}
return $presenter->show();
}
/**
* @param AddHost $useCase
* @param AddHostSaasPresenter $presenter
* @param Request $request
*
* @return Response
*/
private function executeUseCaseSaas(
AddHost $useCase,
AddHostSaasPresenter $presenter,
Request $request,
): Response {
try {
/**
* @var array{
* name: string,
* address: string,
* monitoring_server_id: int,
* alias?: string,
* snmp_version?: string,
* snmp_community?: string,
* icon_id?: null|int,
* max_check_attempts?: null|int,
* normal_check_interval?: null|int,
* retry_check_interval?: null|int,
* note_url?: string,
* note?: string,
* action_url?: string,
* geo_coords?: string,
* timezone_id?: null|int,
* severity_id?: null|int,
* check_timeperiod_id?: 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}>,
* is_activated?: bool,
* event_handler_enabled?: int,
* event_handler_command_id?: null|int,
* check_command_args?: string[],
* check_command_id?: null|int
* } $data
*/
$data = $this->validateAndRetrieveDataSent($request, __DIR__ . '/AddHostSaasSchema.json');
$dto = new AddHostRequest();
$dto->name = $data['name'];
$dto->address = $data['address'];
$dto->monitoringServerId = $data['monitoring_server_id'];
$dto->alias = $data['alias'] ?? '';
$dto->snmpVersion = $data['snmp_version'] ?? '';
$dto->snmpCommunity = $data['snmp_community'] ?? '';
$dto->noteUrl = $data['note_url'] ?? '';
$dto->note = $data['note'] ?? '';
$dto->actionUrl = $data['action_url'] ?? '';
$dto->geoCoordinates = $data['geo_coords'] ?? '';
$dto->timezoneId = $data['timezone_id'] ?? null;
$dto->severityId = $data['severity_id'] ?? null;
$dto->checkTimeperiodId = $data['check_timeperiod_id'] ?? null;
$dto->categories = $data['categories'] ?? [];
$dto->groups = $data['groups'] ?? [];
$dto->templates = $data['templates'] ?? [];
$dto->macros = $data['macros'] ?? [];
$dto->isActivated = $data['is_activated'] ?? true;
$dto->maxCheckAttempts = $data['max_check_attempts'] ?? null;
$dto->normalCheckInterval = $data['normal_check_interval'] ?? null;
$dto->retryCheckInterval = $data['retry_check_interval'] ?? null;
$dto->iconId = $data['icon_id'] ?? null;
$dto->eventHandlerEnabled = $data['event_handler_enabled'] ?? 2;
$dto->eventHandlerCommandId = $data['event_handler_command_id'] ?? null;
$dto->checkCommandArgs = $data['check_command_args'] ?? [];
$dto->checkCommandId = $data['check_command_id'] ?? null;
$useCase($dto, $presenter);
} 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::addHost()));
}
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/Host/Infrastructure/API/AddHost/AddHostOnPremPresenter.php | centreon/src/Core/Host/Infrastructure/API/AddHost/AddHostOnPremPresenter.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\AddHost;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\CreatedResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Host\Application\UseCase\AddHost\AddHostPresenterInterface;
use Core\Host\Application\UseCase\AddHost\AddHostResponse;
use Core\Infrastructure\Common\Presenter\PresenterTrait;
class AddHostOnPremPresenter extends AbstractPresenter implements AddHostPresenterInterface
{
use PresenterTrait;
/**
* @inheritDoc
*/
public function presentResponse(AddHostResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
$this->present(
new CreatedResponse(
$response->id,
[
'id' => $response->id,
'monitoring_server_id' => $response->monitoringServerId,
'name' => $response->name,
'address' => $response->address,
'alias' => $this->emptyStringAsNull($response->alias),
'snmp_version' => $response->snmpVersion,
'geo_coords' => $response->geoCoords,
'note_url' => $this->emptyStringAsNull($response->noteUrl),
'note' => $this->emptyStringAsNull($response->note),
'action_url' => $this->emptyStringAsNull($response->actionUrl),
'icon_alternative' => $this->emptyStringAsNull($response->iconAlternative),
'comment' => $this->emptyStringAsNull($response->comment),
'timezone_id' => $response->timezoneId,
'severity_id' => $response->severityId,
'check_command_id' => $response->checkCommandId,
'check_timeperiod_id' => $response->checkTimeperiodId,
'notification_timeperiod_id' => $response->notificationTimeperiodId,
'event_handler_command_id' => $response->eventHandlerCommandId,
'icon_id' => $response->iconId,
'max_check_attempts' => $response->maxCheckAttempts,
'normal_check_interval' => $response->normalCheckInterval,
'retry_check_interval' => $response->retryCheckInterval,
'notification_options' => $response->notificationOptions,
'notification_interval' => $response->notificationInterval,
'first_notification_delay' => $response->firstNotificationDelay,
'recovery_notification_delay' => $response->recoveryNotificationDelay,
'acknowledgement_timeout' => $response->acknowledgementTimeout,
'freshness_threshold' => $response->freshnessThreshold,
'low_flap_threshold' => $response->lowFlapThreshold,
'high_flap_threshold' => $response->highFlapThreshold,
'freshness_checked' => $response->freshnessChecked,
'active_check_enabled' => $response->activeCheckEnabled,
'passive_check_enabled' => $response->passiveCheckEnabled,
'notification_enabled' => $response->notificationEnabled,
'flap_detection_enabled' => $response->flapDetectionEnabled,
'event_handler_enabled' => $response->eventHandlerEnabled,
'check_command_args' => $response->checkCommandArgs,
'event_handler_command_args' => $response->eventHandlerCommandArgs,
'categories' => array_map(
fn (array $category) => [
'id' => $category['id'],
'name' => $category['name'],
],
$response->categories
),
'groups' => array_map(
fn (array $group) => [
'id' => $group['id'],
'name' => $group['name'],
],
$response->groups
),
'templates' => array_map(
fn (array $template) => [
'id' => $template['id'],
'name' => $template['name'],
],
$response->templates
),
'macros' => array_map(
fn (array $macro) => [
'id' => $macro['id'],
'name' => $macro['name'],
'value' => $macro['isPassword'] ? null : $macro['value'],
'is_password' => $macro['isPassword'],
'description' => $this->emptyStringAsNull($macro['description']),
],
$response->macros
),
'add_inherited_contact_group' => $response->addInheritedContactGroup,
'add_inherited_contact' => $response->addInheritedContact,
'is_activated' => $response->isActivated,
]
)
);
// NOT setting location as required route does not currently exist
}
}
}
| 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/DeleteHost/DeleteHostController.php | centreon/src/Core/Host/Infrastructure/API/DeleteHost/DeleteHostController.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\DeleteHost;
use Centreon\Application\Controller\AbstractController;
use Core\Host\Application\UseCase\DeleteHost\DeleteHost;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Symfony\Component\HttpFoundation\Response;
final class DeleteHostController extends AbstractController
{
public function __invoke(
DeleteHost $useCase,
DefaultPresenter $presenter,
int $hostId,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($hostId, $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/Host/Infrastructure/API/FindRealTimeHostStatusesCount/FindRealTimeHostStatusesCountController.php | centreon/src/Core/Host/Infrastructure/API/FindRealTimeHostStatusesCount/FindRealTimeHostStatusesCountController.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\FindRealTimeHostStatusesCount;
use Centreon\Application\Controller\AbstractController;
use Core\Host\Application\UseCase\FindRealTimeHostStatusesCount\FindRealTimeHostStatusesCount;
use Core\Host\Application\UseCase\FindRealTimeHostStatusesCount\FindRealTimeHostStatusesCountPresenterInterface;
use Symfony\Component\HttpFoundation\Response;
final class FindRealTimeHostStatusesCountController extends AbstractController
{
/**
* @param FindRealTimeHostStatusesCount $useCase
* @param FindRealTimeHostStatusesCountPresenterInterface $presenter
*
* @return Response
*/
public function __invoke(
FindRealTimeHostStatusesCount $useCase,
FindRealTimeHostStatusesCountPresenterInterface $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiRealtime();
$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/Host/Infrastructure/API/FindRealTimeHostStatusesCount/FindRealTimeHostStatusesCountPresenter.php | centreon/src/Core/Host/Infrastructure/API/FindRealTimeHostStatusesCount/FindRealTimeHostStatusesCountPresenter.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\FindRealTimeHostStatusesCount;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Host\Application\UseCase\FindRealTimeHostStatusesCount\FindRealTimeHostStatusesCountPresenterInterface;
use Core\Host\Application\UseCase\FindRealTimeHostStatusesCount\FindRealTimeHostStatusesCountResponse;
class FindRealTimeHostStatusesCountPresenter extends AbstractPresenter implements FindRealTimeHostStatusesCountPresenterInterface
{
/**
* @param FindRealTimeHostStatusesCountResponse|ResponseStatusInterface $response
*/
public function presentResponse(FindRealTimeHostStatusesCountResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
$this->present([
'up' => ['total' => $response->upStatuses],
'down' => ['total' => $response->downStatuses],
'unreachable' => ['total' => $response->unreachableStatuses],
'pending' => ['total' => $response->pendingStatuses],
'total' => $response->total,
]);
}
}
}
| 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/FindHosts/FindHostsSaasPresenter.php | centreon/src/Core/Host/Infrastructure/API/FindHosts/FindHostsSaasPresenter.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 FindHostsSaasPresenter 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,
'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/FindHosts/FindHostsController.php | centreon/src/Core/Host/Infrastructure/API/FindHosts/FindHostsController.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\Application\Controller\AbstractController;
use Core\Host\Application\UseCase\FindHosts\FindHosts;
use Symfony\Component\HttpFoundation\Response;
final class FindHostsController extends AbstractController
{
public function __invoke(
FindHosts $useCase,
FindHostsOnPremPresenter $onPremPresenter,
FindHostsSaasPresenter $saasPresenter,
bool $isCloudPlatform,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
$presenter = $isCloudPlatform ? $saasPresenter : $onPremPresenter;
$useCase($presenter);
return $presenter->show();
}
}
| 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.