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/Application/UseCase/AddDashboard/AddDashboardResponse.php | centreon/src/Core/Dashboard/Application/UseCase/AddDashboard/AddDashboardResponse.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\Application\UseCase\AddDashboard;
use Core\Dashboard\Domain\Model\Refresh\RefreshType;
use Core\Dashboard\Domain\Model\Role\DashboardSharingRole;
final class AddDashboardResponse
{
/**
* @param int $id
* @param string $name
* @param string|null $description
* @param array{id:int, name:string} $createdBy
* @param array{id:int, name:string} $updatedBy
* @param \DateTimeImmutable $createdAt
* @param \DateTimeImmutable $updatedAt
* @param DashboardSharingRole $ownRole
* @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: array<mixed>,
* }> $panels,
* @param array{type: RefreshType, interval: int|null} $refresh
*/
public function __construct(
public int $id = 0,
public string $name = '',
public ?string $description = null,
public array $createdBy = ['id' => 0, 'name' => ''],
public array $updatedBy = ['id' => 0, 'name' => ''],
public \DateTimeImmutable $createdAt = new \DateTimeImmutable(),
public \DateTimeImmutable $updatedAt = new \DateTimeImmutable(),
public DashboardSharingRole $ownRole = DashboardSharingRole::Viewer,
public array $panels = [],
public array $refresh = [
'type' => RefreshType::Global,
'interval' => 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/Application/UseCase/AddDashboard/AddDashboard.php | centreon/src/Core/Dashboard/Application/UseCase/AddDashboard/AddDashboard.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\Application\UseCase\AddDashboard;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\Repository\ReadDashboardPanelRepositoryInterface;
use Core\Dashboard\Application\Repository\ReadDashboardRepositoryInterface;
use Core\Dashboard\Application\Repository\WriteDashboardPanelRepositoryInterface;
use Core\Dashboard\Application\Repository\WriteDashboardRepositoryInterface;
use Core\Dashboard\Application\Repository\WriteDashboardShareRepositoryInterface;
use Core\Dashboard\Domain\Model\Dashboard;
use Core\Dashboard\Domain\Model\DashboardPanel;
use Core\Dashboard\Domain\Model\DashboardRights;
use Core\Dashboard\Domain\Model\NewDashboard;
use Core\Dashboard\Domain\Model\NewDashboardPanel;
use Core\Dashboard\Domain\Model\Refresh;
use Core\Dashboard\Domain\Model\Role\DashboardSharingRole;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
final class AddDashboard
{
use LoggerTrait;
public const AUTHORIZED_ACL_GROUPS = ['customer_admin_acl'];
public function __construct(
private readonly ReadDashboardRepositoryInterface $readDashboardRepository,
private readonly WriteDashboardRepositoryInterface $writeDashboardRepository,
private readonly WriteDashboardShareRepositoryInterface $writeDashboardShareRepository,
private readonly DataStorageEngineInterface $dataStorageEngine,
private readonly DashboardRights $rights,
private readonly ContactInterface $contact,
private readonly WriteDashboardPanelRepositoryInterface $writeDashboardPanelRepository,
private readonly ReadDashboardPanelRepositoryInterface $readDashboardPanelRepository,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly bool $isCloudPlatform,
) {
}
public function __invoke(
AddDashboardRequest $request,
AddDashboardPresenterInterface $presenter,
): void {
try {
if (! $this->isAuthorized()) {
$this->error(
"User doesn't have sufficient rights to add dashboards",
['user_id' => $this->contact->getId()]
);
$presenter->presentResponse(
new ForbiddenResponse(DashboardException::accessNotAllowedForWriting())
);
return;
}
$dashboard = $this->createDashboard($request);
$panels = $this->createPanels($request->panels);
$dashboardId = $this->addDashboard($dashboard, $panels);
$foundDashboard = $this->readDashboardRepository->findOneByContact($dashboardId, $this->contact);
if ($foundDashboard === null) {
throw DashboardException::errorWhileRetrievingJustCreated();
}
$foundPanels = $this->readDashboardPanelRepository->findPanelsByDashboardId($dashboardId);
$presenter->presentResponse($this->createResponse($foundDashboard, $foundPanels));
} catch (AssertionFailedException|\InvalidArgumentException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->presentResponse(new InvalidArgumentResponse($ex));
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->presentResponse(new ErrorResponse(
$ex instanceof DashboardException
? $ex
: DashboardException::errorWhileAdding()
));
}
}
/**
* @param NewDashboard $dashboard
* @param NewDashboardPanel[] $panels;
*
* @throws \Throwable
*
* @return int
*/
private function addDashboard(NewDashboard $dashboard, array $panels): int
{
try {
$this->dataStorageEngine->startTransaction();
$newDashboardId = $this->writeDashboardRepository->add($dashboard);
$this->writeDashboardShareRepository->upsertShareWithContact(
$this->contact->getId(),
$newDashboardId,
DashboardSharingRole::Editor
);
foreach ($panels as $panel) {
$this->writeDashboardPanelRepository->addPanel($newDashboardId, $panel);
}
$this->dataStorageEngine->commitTransaction();
} catch (\Throwable $ex) {
$this->error("Rollback of 'Add Dashboard' transaction.");
$this->dataStorageEngine->rollbackTransaction();
throw $ex;
}
return $newDashboardId;
}
/**
* @param AddDashboardRequest $request
*
* @throws AssertionFailedException
*
* @return NewDashboard
*/
private function createDashboard(AddDashboardRequest $request): NewDashboard
{
$refresh = new Refresh($request->refresh['type'], $request->refresh['interval']);
$dashboard = new NewDashboard(
$request->name,
$this->contact->getId(),
$refresh
);
$dashboard->setDescription($request->description);
return $dashboard;
}
/**
* @param PanelRequest[] $requestPanels
*
* @throws AssertionFailedException
*
* @return NewDashboardPanel[]
*/
private function createPanels(array $requestPanels): array
{
$panels = [];
foreach ($requestPanels as $panel) {
$newPanel = new NewDashboardPanel($panel->name, $panel->widgetType);
$newPanel->setWidgetSettings($panel->widgetSettings);
$newPanel->setLayoutHeight($panel->layout->height);
$newPanel->setLayoutMinHeight($panel->layout->minHeight);
$newPanel->setLayoutWidth($panel->layout->width);
$newPanel->setLayoutMinWidth($panel->layout->minWidth);
$newPanel->setLayoutX($panel->layout->xAxis);
$newPanel->setLayoutY($panel->layout->yAxis);
$panels[] = $newPanel;
}
return $panels;
}
/**
* @param Dashboard $dashboard
* @param DashboardPanel[] $panels
*
* @return AddDashboardResponse
*/
private function createResponse(Dashboard $dashboard, array $panels): AddDashboardResponse
{
$author = [
'id' => $this->contact->getId(),
'name' => $this->contact->getName(),
];
$panelsResponse = array_map(static fn (DashboardPanel $panel): array => [
'id' => $panel->getId(),
'name' => $panel->getName(),
'layout' => [
'x' => $panel->getLayoutX(),
'y' => $panel->getLayoutY(),
'width' => $panel->getLayoutWidth(),
'height' => $panel->getLayoutHeight(),
'min_width' => $panel->getLayoutMinWidth(),
'min_height' => $panel->getLayoutMinHeight(),
],
'widget_type' => $panel->getWidgetType(),
'widget_settings' => $panel->getWidgetSettings(),
], $panels);
$refreshResponse = [
'type' => $dashboard->getRefresh()->getRefreshType(),
'interval' => $dashboard->getRefresh()->getRefreshInterval(),
];
return new AddDashboardResponse(
$dashboard->getId(),
$dashboard->getName(),
$dashboard->getDescription(),
$author,
$author,
$dashboard->getCreatedAt(),
$dashboard->getUpdatedAt(),
DashboardSharingRole::Editor,
$panelsResponse,
$refreshResponse
);
}
private function isAuthorized(): bool
{
if ($this->rights->hasCreatorRole()) {
return true;
}
$userAccessGroupNames = array_map(
static fn (AccessGroup $accessGroup): string => $accessGroup->getName(),
$this->readAccessGroupRepository->findByContact($this->contact)
);
return ! (empty(array_intersect($userAccessGroupNames, self::AUTHORIZED_ACL_GROUPS)))
&& $this->isCloudPlatform;
}
}
| 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/Application/UseCase/AddDashboard/PanelRequest.php | centreon/src/Core/Dashboard/Application/UseCase/AddDashboard/PanelRequest.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\Application\UseCase\AddDashboard;
final class PanelRequest
{
public string $name = '';
public string $widgetType = '';
/** @var array<mixed> */
public array $widgetSettings = [];
public function __construct(public LayoutRequest $layout)
{
}
}
| 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/Application/UseCase/AddDashboard/AddDashboardPresenterInterface.php | centreon/src/Core/Dashboard/Application/UseCase/AddDashboard/AddDashboardPresenterInterface.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\Application\UseCase\AddDashboard;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface AddDashboardPresenterInterface
{
public function presentResponse(AddDashboardResponse|ResponseStatusInterface $data): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Application/UseCase/AddDashboard/LayoutRequest.php | centreon/src/Core/Dashboard/Application/UseCase/AddDashboard/LayoutRequest.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\Application\UseCase\AddDashboard;
final class LayoutRequest
{
public int $xAxis = 0;
public int $yAxis = 0;
public int $width = 0;
public int $height = 0;
public int $minWidth = 0;
public int $minHeight = 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/Dashboard/Application/UseCase/AddDashboard/Response/UserResponseDto.php | centreon/src/Core/Dashboard/Application/UseCase/AddDashboard/Response/UserResponseDto.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\Application\UseCase\AddDashboard\Response;
final class UserResponseDto
{
public function __construct(
public int $id = 0,
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/Dashboard/Application/UseCase/FindPerformanceMetricsData/FindPerformanceMetricsDataRequestDto.php | centreon/src/Core/Dashboard/Application/UseCase/FindPerformanceMetricsData/FindPerformanceMetricsDataRequestDto.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\Application\UseCase\FindPerformanceMetricsData;
final class FindPerformanceMetricsDataRequestDto
{
/**
* @param \DateTimeInterface $startDate
* @param \DateTimeInterface $endDate
* @param string[] $metricNames
*/
public function __construct(
public readonly \DateTimeInterface $startDate,
public readonly \DateTimeInterface $endDate,
public readonly array $metricNames = [],
) {
}
}
| 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/Application/UseCase/FindPerformanceMetricsData/FindPerformanceMetricsDataPresenterInterface.php | centreon/src/Core/Dashboard/Application/UseCase/FindPerformanceMetricsData/FindPerformanceMetricsDataPresenterInterface.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\Application\UseCase\FindPerformanceMetricsData;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface FindPerformanceMetricsDataPresenterInterface
{
public function presentResponse(FindPerformanceMetricsDataResponse|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/Dashboard/Application/UseCase/FindPerformanceMetricsData/FindPerformanceMetricsDataRequest.php | centreon/src/Core/Dashboard/Application/UseCase/FindPerformanceMetricsData/FindPerformanceMetricsDataRequest.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\Application\UseCase\FindPerformanceMetricsData;
use Core\Common\Infrastructure\Validator\DateFormat;
use Symfony\Component\Validator\Constraints as Assert;
final class FindPerformanceMetricsDataRequest
{
/**
* @param string $start
* @param string $end
* @param string[] $metricNames
*/
public function __construct(
#[Assert\NotBlank]
#[Assert\DateTime(
format: DateFormat::ISO8601,
message: DateFormat::INVALID_DATE_MESSAGE
)]
public readonly mixed $start,
#[Assert\NotBlank]
#[Assert\DateTime(
format: DateFormat::ISO8601,
message: DateFormat::INVALID_DATE_MESSAGE
)]
public readonly mixed $end,
#[Assert\NotNull]
#[Assert\Sequentially([
new Assert\Type('array'),
new Assert\All(
[new Assert\Type('string')]
),
])]
public readonly mixed $metricNames,
) {
}
/**
* @return FindPerformanceMetricsDataRequestDto
*/
public function toDto(): FindPerformanceMetricsDataRequestDto
{
return new FindPerformanceMetricsDataRequestDto(
startDate: new \DateTimeImmutable($this->start),
endDate: new \DateTimeImmutable($this->end),
metricNames: $this->sanitizeMetricNames()
);
}
/**
* @return string[]
*/
private function sanitizeMetricNames(): array
{
return array_map(
static fn (string $metricName): string => \trim($metricName, '"'),
$this->metricNames
);
}
}
| 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/Application/UseCase/FindPerformanceMetricsData/PerformanceMetricsDataFactory.php | centreon/src/Core/Dashboard/Application/UseCase/FindPerformanceMetricsData/PerformanceMetricsDataFactory.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\Application\UseCase\FindPerformanceMetricsData;
use Centreon\Domain\Common\Assertion\AssertionException;
use Centreon\Domain\Log\LoggerTrait;
use Core\Dashboard\Domain\Model\Metric\PerformanceMetricsData;
use Core\Metric\Application\Exception\MetricException;
use Core\Metric\Domain\Model\MetricInformation\DataSource;
use Core\Metric\Domain\Model\MetricInformation\GeneralInformation;
use Core\Metric\Domain\Model\MetricInformation\MetricInformation;
use Core\Metric\Domain\Model\MetricInformation\RealTimeDataInformation;
use Core\Metric\Domain\Model\MetricInformation\ThresholdInformation;
/**
* @phpstan-type _Metrics array{
* index_id: int,
* metric_id: int,
* metric: string,
* metric_legend: string,
* unit: string,
* hidden: int,
* host_name: ?string,
* service_name: ?string,
* legend: string,
* virtual: int,
* stack: int,
* ds_order: int,
* ds_data: array{
* ds_min: ?string,
* ds_max: ?string,
* ds_minmax_int: ?string,
* ds_last: ?string,
* ds_average: ?string,
* ds_total: ?string,
* ds_tickness: int,
* ds_color_line_mode: int,
* ds_color_line: string,
* ds_transparency: ?float,
* ds_color_area: ?string,
* ds_color_area_warn?: string,
* ds_color_area_crit?: string,
* legend: ?string,
* ds_filled: ?int,
* ds_invert: ?int,
* ds_stack: ?int,
* ds_order: ?int,
* },
* warn: ?float,
* warn_low: ?float,
* crit: ?float,
* crit_low: ?float,
* ds_color_area_warn?: string,
* ds_color_area_crit?: string,
* data: array<float|null>,
* prints: array<array<string>>,
* min: ?float,
* max: ?float,
* last_value: ?float,
* minimum_value: ?float,
* maximum_value: ?float,
* average_value: ?float
* }
* @phpstan-type _MetricData array{
* global: array{
* base: int|null,
* title: string,
* host_name: string,
* service_description: string
* },
* metrics: array<_Metrics>,
* times: string[]
* }
* @phpstan-type _DataSourceData array{
* ds_min: ?string,
* ds_max: ?string,
* ds_minmax_int: ?string,
* ds_last: ?string,
* ds_average: ?string,
* ds_total: ?string,
* ds_tickness: int,
* ds_color_line_mode: int,
* ds_color_line: string,
* ds_transparency: ?float,
* ds_color_area_warn?: string,
* ds_color_area_crit?: string,
* ds_color_area: ?string,
* legend: ?string,
* ds_filled: ?int,
* ds_invert: ?int,
* ds_stack: ?int,
* ds_order: ?int
* }
*/
class PerformanceMetricsDataFactory
{
use LoggerTrait;
/**
* @param array<_MetricData> $metricsData
* @param string[] $metricNames
*
* @throws MetricException
*
* @return PerformanceMetricsData
*/
public function createFromRecords(array $metricsData, array $metricNames): PerformanceMetricsData
{
$metricBases = [];
$metrics = [];
$times = [];
foreach ($metricsData as $index => $metricData) {
$metricBases[] = $metricData['global']['base'];
$metrics[
'index:' . $index . ';host_name:' . $metricData['global']['host_name'] . ';service_name:'
. $metricData['global']['service_description']
] = $metricData['metrics'];
$times[] = $metricData['times'];
}
$base = $metricBases !== [] ? $this->getHighestBase($metricBases) : PerformanceMetricsData::DEFAULT_BASE;
$metricsInfo = $metrics !== [] ? $this->createMetricInformations($metrics, $metricNames) : [];
$times = $times !== [] ? $this->getTimes($times) : [];
return new PerformanceMetricsData($base, $metricsInfo, $times);
}
/**
* Get The highest base of all metrics.
*
* @param array<int, int|null> $bases
*
* @return int
*/
private function getHighestBase(array $bases): int
{
return max($bases) ?? PerformanceMetricsData::DEFAULT_BASE;
}
/**
* @param string $property
* @param _DataSourceData $data
*
* @return bool
*/
private function propertyDefinedAndNotNull(string $property, array $data): bool
{
return isset($data[$property]) && $data[$property] !== null;
}
/**
* Filter the metrics to keep only the needed metrics.
*
* @param array<string,array<_Metrics>> $metricsData
* @param string[] $metricNames
*
* @return array<_Metrics>
*/
private function filterMetricsByMetricName(array $metricsData, array $metricNames): array
{
$metrics = [];
foreach ($metricsData as $hostName => $metricData) {
\preg_match('/^index:\d+;host_name:([[:ascii:]]+);service_name:([[:ascii:]]+)$/', $hostName, $matches);
// Regarding this, currently if hostname is empty it means that we are dealing with a metaservice
$hostName = '';
$serviceName = '';
if ($matches !== []) {
$hostName = $matches[1];
$serviceName = $matches[2];
}
foreach ($metricData as $metric) {
if (in_array($metric['metric'], $metricNames, true)) {
$metric['metric_legend'] = ! empty($hostName)
? $hostName . ': ' . $metric['metric_legend']
: $metric['metric_legend'];
$metric['legend'] = ! empty($hostName)
? $hostName . ': ' . $metric['legend']
: $metric['legend'];
$metric['host_name'] = empty($hostName) ? null : $hostName;
$metric['service_name'] = empty($serviceName) ? null : $serviceName;
$metrics[] = $metric;
}
}
}
return $metrics;
}
/**
* Get the different times of metric.
*
* @param array<array<string>> $times
*
* @return \DateTimeImmutable[]
*/
private function getTimes(array $times): array
{
return array_map(fn (string $time): \DateTimeImmutable => (new \DateTimeImmutable())->setTimestamp((int) $time), $times[0]);
}
/**
* Create Metric Information.
*
* @param array<string,array<_Metrics>> $metricData
* @param string[] $metricNames
*
* @throws MetricException
*
* @return MetricInformation[]
*/
private function createMetricInformations(array $metricData, array $metricNames): array
{
$metrics = $this->filterMetricsByMetricName($metricData, $metricNames);
$metricsInformation = [];
foreach ($metrics as $metric) {
try {
$generalInformation = new GeneralInformation(
$metric['index_id'],
$metric['metric_id'],
$metric['metric'],
$metric['metric_legend'],
$metric['unit'],
(bool) $metric['hidden'],
$metric['host_name'],
$metric['service_name'],
$metric['legend'],
(bool) $metric['virtual'],
(bool) $metric['stack'],
$metric['ds_order']
);
/** @var _DataSourceData $dsData */
$dsData = $metric['ds_data'];
$dataSource = new DataSource(
$this->propertyDefinedAndNotNull('ds_min', $dsData) ? (int) $dsData['ds_min'] : null,
$this->propertyDefinedAndNotNull('ds_max', $dsData) ? (int) $dsData['ds_max'] : null,
$this->propertyDefinedAndNotNull('ds_minmax_int', $dsData) ? (int) $dsData['ds_minmax_int'] : null,
$this->propertyDefinedAndNotNull('ds_last', $dsData) ? (int) $dsData['ds_last'] : null,
$this->propertyDefinedAndNotNull('ds_average', $dsData) ? (int) $dsData['ds_average'] : null,
$this->propertyDefinedAndNotNull('ds_total', $dsData) ? (int) $dsData['ds_total'] : null,
$this->propertyDefinedAndNotNull('ds_transparency', $dsData) ? (float) $dsData['ds_transparency'] : null,
$this->propertyDefinedAndNotNull('ds_color_area', $dsData) ? $dsData['ds_color_area'] : null,
$this->propertyDefinedAndNotNull('ds_filled', $dsData) ? (int) $dsData['ds_filled'] === 1 : false,
$this->propertyDefinedAndNotNull('ds_invert', $dsData) ? (int) $dsData['ds_invert'] === 1 : false,
$this->propertyDefinedAndNotNull('legend', $dsData) ? $dsData['legend'] : null,
$this->propertyDefinedAndNotNull('ds_stack', $dsData) ? (int) $dsData['ds_stack'] === 1 : false,
$this->propertyDefinedAndNotNull('ds_order', $dsData) ? (int) $dsData['ds_order'] : null,
(int) $dsData['ds_tickness'],
(int) $dsData['ds_color_line_mode'],
$dsData['ds_color_line'],
);
$thresholdInformation = new ThresholdInformation(
$metric['warn'] !== null ? (float) $metric['warn'] : null,
$metric['warn_low'] !== null ? (float) $metric['warn_low'] : null,
$metric['crit'] !== null ? (float) $metric['crit'] : null,
$metric['crit_low'] !== null ? (float) $metric['crit_low'] : null,
$metric['ds_color_area_warn'] ?? $dsData['ds_color_area_warn'] ?? '',
$metric['ds_color_area_crit'] ?? $dsData['ds_color_area_crit'] ?? ''
);
$realTimeDataInformation = new RealTimeDataInformation(
$metric['data'],
$metric['prints'],
$metric['min'] !== null ? (float) $metric['min'] : null,
$metric['max'] !== null ? (float) $metric['max'] : null,
$metric['minimum_value'] !== null ? (float) $metric['minimum_value'] : null,
$metric['maximum_value'] !== null ? (float) $metric['maximum_value'] : null,
$metric['last_value'] !== null ? (float) $metric['last_value'] : null,
$metric['average_value'] !== null ? (float) $metric['average_value'] : null
);
$metricsInformation[] = new MetricInformation(
$generalInformation,
$dataSource,
$thresholdInformation,
$realTimeDataInformation
);
} catch (\TypeError|AssertionException $ex) {
$this->error('Metric data are not correctly formatted', ['trace' => (string) $ex]);
throw MetricException::invalidMetricFormat();
}
}
return $metricsInformation;
}
}
| 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/Application/UseCase/FindPerformanceMetricsData/FindPerformanceMetricsDataResponse.php | centreon/src/Core/Dashboard/Application/UseCase/FindPerformanceMetricsData/FindPerformanceMetricsDataResponse.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\Application\UseCase\FindPerformanceMetricsData;
use Core\Metric\Domain\Model\MetricInformation\MetricInformation;
final class FindPerformanceMetricsDataResponse
{
public int $base;
/** @var MetricInformation[] */
public array $metricsInformation;
/** @var \DateTimeImmutable[] */
public array $times;
}
| 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/Application/UseCase/FindPerformanceMetricsData/FindPerformanceMetricsData.php | centreon/src/Core/Dashboard/Application/UseCase/FindPerformanceMetricsData/FindPerformanceMetricsData.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\Application\UseCase\FindPerformanceMetricsData;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Monitoring\Metric\Interfaces\MetricRepositoryInterface;
use Centreon\Domain\Monitoring\Service;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\{ErrorResponse, ForbiddenResponse, InvalidArgumentResponse};
use Core\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Domain\Model\DashboardRights;
use Core\Dashboard\Domain\Model\Metric\PerformanceMetricsData;
use Core\Metric\Application\Exception\MetricException;
use Core\Metric\Application\Repository\ReadMetricRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
/**
* @phpstan-import-type _MetricData from PerformanceMetricsDataFactory
*/
final class FindPerformanceMetricsData
{
use LoggerTrait;
public const AUTHORIZED_ACL_GROUPS = ['customer_admin_acl'];
public function __construct(
private readonly ContactInterface $user,
private readonly RequestParametersInterface $requestParameters,
private readonly MetricRepositoryInterface $metricRepositoryLegacy,
private readonly ReadMetricRepositoryInterface $metricRepository,
private readonly ReadAccessGroupRepositoryInterface $accessGroupRepository,
private readonly DashboardRights $rights,
private readonly bool $isCloudPlatform,
) {
}
public function __invoke(
FindPerformanceMetricsDataPresenterInterface $presenter,
FindPerformanceMetricsDataRequestDto $request,
): void {
try {
if ($this->isUserAdmin()) {
$this->info('Retrieving metrics data for admin user', [
'user_id' => $this->user->getId(),
'metric_names' => implode(', ', $request->metricNames),
]);
$performanceMetricsData = $this->findPerformanceMetricsDataAsAdmin($request);
} elseif ($this->rights->canAccess()) {
$this->info('Retrieving metrics data for non admin user', [
'user_id' => $this->user->getId(),
'metric_names' => implode(', ', $request->metricNames),
]);
$accessGroups = $this->accessGroupRepository->findByContact($this->user);
$performanceMetricsData = $this->findPerformanceMetricsDataAsNonAdmin($request, $accessGroups);
} else {
$presenter->presentResponse(new ForbiddenResponse(
DashboardException::accessNotAllowed()->getMessage()
));
return;
}
$presenter->presentResponse($this->createResponse($performanceMetricsData));
} catch (MetricException $ex) {
$this->error('Metric from RRD are not correctly formatted', ['trace' => (string) $ex]);
$presenter->presentResponse(new InvalidArgumentResponse($ex->getMessage()));
} catch (\Throwable $ex) {
$this->error('An error occurred while retrieving metrics data', ['trace' => (string) $ex]);
$presenter->presentResponse(new ErrorResponse('An error occurred while retrieving metrics data'));
}
}
/**
* find Performance Metrics Data for an admin user.
*
* @param FindPerformanceMetricsDataRequestDto $request
*
* @throws MetricException
* @throws \Throwable
*
* @return PerformanceMetricsData
*/
private function findPerformanceMetricsDataAsAdmin(
FindPerformanceMetricsDataRequestDto $request,
): PerformanceMetricsData {
$services = $this->metricRepository->findServicesByMetricNamesAndRequestParameters(
$request->metricNames,
$this->requestParameters
);
return $this->createPerformanceMetricsData($services, $request);
}
/**
* find Performance Metrics Data for an admin user.
*
* @param FindPerformanceMetricsDataRequestDto $request
* @param AccessGroup[] $accessGroups
*
* @throws MetricException
* @throws \Throwable
*
* @return PerformanceMetricsData
*/
private function findPerformanceMetricsDataAsNonAdmin(
FindPerformanceMetricsDataRequestDto $request,
array $accessGroups,
): PerformanceMetricsData {
$services = $this->metricRepository->findServicesByMetricNamesAndAccessGroupsAndRequestParameters(
$request->metricNames,
$accessGroups,
$this->requestParameters
);
return $this->createPerformanceMetricsData($services, $request);
}
private function createResponse(PerformanceMetricsData $performanceMetricsData): FindPerformanceMetricsDataResponse
{
$response = new FindPerformanceMetricsDataResponse();
$response->base = $performanceMetricsData->getBase();
$response->metricsInformation = $performanceMetricsData->getMetricsInformation();
$response->times = $performanceMetricsData->getTimes();
return $response;
}
/**
* @param Service[] $services
* @param FindPerformanceMetricsDataRequestDto $request
*
* @throws MetricException|\Exception
*
* @return PerformanceMetricsData
*/
private function createPerformanceMetricsData(
array $services,
FindPerformanceMetricsDataRequestDto $request,
): PerformanceMetricsData {
$metricsData = [];
$this->metricRepositoryLegacy->setContact($this->user);
foreach ($services as $service) {
/** @var _MetricData $data */
$data = $this->metricRepositoryLegacy->findMetricsByService(
$service,
$request->startDate,
$request->endDate
);
$metricsData[] = $data;
}
return (new PerformanceMetricsDataFactory())
->createFromRecords($metricsData, $request->metricNames);
}
/**
* @throws \Throwable
*
* @return bool
*/
private function isUserAdmin(): bool
{
if ($this->rights->hasAdminRole()) {
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)))
&& $this->isCloudPlatform;
}
}
| 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/Application/UseCase/FindFavoriteDashboards/FindFavoriteDashboardsResponse.php | centreon/src/Core/Dashboard/Application/UseCase/FindFavoriteDashboards/FindFavoriteDashboardsResponse.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\Application\UseCase\FindFavoriteDashboards;
use Core\Application\Common\UseCase\ListingResponseInterface;
use Core\Dashboard\Application\UseCase\FindFavoriteDashboards\Response\DashboardResponseDto;
final class FindFavoriteDashboardsResponse implements ListingResponseInterface
{
/**
* @param DashboardResponseDto[] $dashboards
*/
public function __construct(
public array $dashboards,
) {
}
/**
* @inheritDoc
*/
public function getData(): mixed
{
return $this->dashboards;
}
}
| 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/Application/UseCase/FindFavoriteDashboards/FindFavoriteDashboards.php | centreon/src/Core/Dashboard/Application/UseCase/FindFavoriteDashboards/FindFavoriteDashboards.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\Application\UseCase\FindFavoriteDashboards;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Contact\Application\Repository\ReadContactRepositoryInterface;
use Core\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\Repository\ReadDashboardRepositoryInterface;
use Core\Dashboard\Application\Repository\ReadDashboardShareRepositoryInterface;
use Core\Dashboard\Application\UseCase\FindFavoriteDashboards\Response\DashboardResponseDto;
use Core\Dashboard\Application\UseCase\FindFavoriteDashboards\Response\ThumbnailResponseDto;
use Core\Dashboard\Application\UseCase\FindFavoriteDashboards\Response\UserResponseDto;
use Core\Dashboard\Domain\Model\Dashboard;
use Core\Dashboard\Domain\Model\DashboardRights;
use Core\Dashboard\Domain\Model\Role\DashboardSharingRole;
use Core\Dashboard\Domain\Model\Share\DashboardContactGroupShare;
use Core\Dashboard\Domain\Model\Share\DashboardContactShare;
use Core\Dashboard\Domain\Model\Share\DashboardSharingRoles;
use Core\Media\Domain\Model\Media;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Core\UserProfile\Application\Repository\ReadUserProfileRepositoryInterface;
use Throwable;
final class FindFavoriteDashboards
{
use LoggerTrait;
public const AUTHORIZED_ACL_GROUPS = ['customer_admin_acl'];
/** @var int[] */
private array $usersFavoriteDashboards;
/**
* @param RequestParametersInterface $requestParameters
* @param ReadDashboardRepositoryInterface $dashboardReader
* @param ReadUserProfileRepositoryInterface $userProfileReader
* @param ContactInterface $contact
* @param DashboardRights $rights
* @param ReadAccessGroupRepositoryInterface $readAccessGroupRepository
* @param ReadContactRepositoryInterface $readContactRepository
* @param ReadDashboardShareRepositoryInterface $readDashboardShareRepository
* @param bool $isCloudPlatform
*/
public function __construct(
private readonly RequestParametersInterface $requestParameters,
private readonly ReadDashboardRepositoryInterface $dashboardReader,
private readonly ReadUserProfileRepositoryInterface $userProfileReader,
private readonly ContactInterface $contact,
private readonly DashboardRights $rights,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly ReadContactRepositoryInterface $readContactRepository,
private readonly ReadDashboardShareRepositoryInterface $readDashboardShareRepository,
private readonly bool $isCloudPlatform,
) {
}
/**
* @return FindFavoriteDashboardsResponse|ResponseStatusInterface
*/
public function __invoke(): FindFavoriteDashboardsResponse|ResponseStatusInterface
{
try {
$profile = $this->userProfileReader->findByContact($this->contact);
$this->usersFavoriteDashboards = $profile !== null ? $profile->getFavoriteDashboards() : [];
if ($this->usersFavoriteDashboards === []) {
return new FindFavoriteDashboardsResponse([]);
}
// Hack to benifit from existing code.
$search = $this->requestParameters->getSearch();
$search = ['id' => ['$in' => $this->usersFavoriteDashboards], ...$search];
$this->requestParameters->setSearch(json_encode($search, JSON_THROW_ON_ERROR) ?: '');
return $this->isUserAdmin() ? $this->findDashboardAsAdmin() : $this->findDashboardAsViewer();
} catch (Throwable $ex) {
$this->error(
"Error while searching favorite dashboards : {$ex->getMessage()}",
[
'contact_id' => $this->contact->getId(),
'favorite_dashboards' => $this->usersFavoriteDashboards,
'request_parameters' => $this->requestParameters->toArray(),
'exception' => ['message' => $ex->getMessage(), 'trace' => $ex->getTraceAsString()],
]
);
return new ErrorResponse(DashboardException::errorWhileSearching());
}
}
/**
* @throws Throwable
*
* @return FindFavoriteDashboardsResponse
*/
private function findDashboardAsAdmin(): FindFavoriteDashboardsResponse
{
$dashboards = $this->dashboardReader->findByRequestParameter($this->requestParameters);
$dashboardIds = array_map(
static fn (Dashboard $dashboard): int => $dashboard->getId(),
$dashboards
);
$thumbnails = $this->dashboardReader->findThumbnailsByDashboardIds($dashboardIds);
$contactIds = $this->extractAllContactIdsFromDashboards($dashboards);
return $this->createResponse(
dashboards: $dashboards,
contactNames: $this->readContactRepository->findNamesByIds(...$contactIds),
sharingRolesList: $this->readDashboardShareRepository->getMultipleSharingRoles($this->contact, ...$dashboards),
contactShares: $this->readDashboardShareRepository->findDashboardsContactShares(...$dashboards),
contactGroupShares: $this->readDashboardShareRepository->findDashboardsContactGroupShares(...$dashboards),
defaultRole: DashboardSharingRole::Editor,
thumbnails: $thumbnails
);
}
/**
* @throws Throwable
*
* @return FindFavoriteDashboardsResponse
*/
private function findDashboardAsViewer(): FindFavoriteDashboardsResponse
{
$dashboards = $this->dashboardReader->findByRequestParameterAndContact(
$this->requestParameters,
$this->contact,
);
$dashboardIds = array_map(
static fn (Dashboard $dashboard): int => $dashboard->getId(),
$dashboards
);
$thumbnails = $this->dashboardReader->findThumbnailsByDashboardIds($dashboardIds);
$editorIds = $this->extractAllContactIdsFromDashboards($dashboards);
$userAccessGroups = $this->readAccessGroupRepository->findByContact($this->contact);
$accessGroupsIds = array_map(
static fn (AccessGroup $accessGroup): int => $accessGroup->getId(),
$userAccessGroups
);
$userInCurrentUserAccessGroups = $this->readContactRepository->findContactIdsByAccessGroups($accessGroupsIds);
return $this->createResponse(
dashboards: $dashboards,
contactNames: $this->readContactRepository->findNamesByIds(...$editorIds),
sharingRolesList: $this->readDashboardShareRepository->getMultipleSharingRoles($this->contact, ...$dashboards),
contactShares: $this->readDashboardShareRepository->findDashboardsContactSharesByContactIds(
$userInCurrentUserAccessGroups,
...$dashboards
),
contactGroupShares: $this->readDashboardShareRepository->findDashboardsContactGroupSharesByContact($this->contact, ...$dashboards),
defaultRole: DashboardSharingRole::Viewer,
thumbnails: $thumbnails
);
}
/**
* @param list<Dashboard> $dashboards
*
* @return int[]
*/
private function extractAllContactIdsFromDashboards(array $dashboards): array
{
$contactIds = [];
foreach ($dashboards as $dashboard) {
if ($id = $dashboard->getCreatedBy()) {
$contactIds[] = $id;
}
if ($id = $dashboard->getUpdatedBy()) {
$contactIds[] = $id;
}
}
return $contactIds;
}
/**
* @throws Throwable
*
* @return bool
*/
private function isUserAdmin(): bool
{
if ($this->rights->hasAdminRole()) {
return true;
}
$userAccessGroupNames = array_map(
static fn (AccessGroup $accessGroup): string => $accessGroup->getName(),
$this->readAccessGroupRepository->findByContact($this->contact)
);
return ! (empty(array_intersect($userAccessGroupNames, self::AUTHORIZED_ACL_GROUPS)))
&& $this->isCloudPlatform;
}
/**
* @param list<Dashboard> $dashboards
* @param array<int, array{id: int, name: string}> $contactNames
* @param array<int, DashboardSharingRoles> $sharingRolesList
* @param array<int, array<DashboardContactShare>> $contactShares
* @param array<int, array<DashboardContactGroupShare>> $contactGroupShares
* @param DashboardSharingRole $defaultRole
* @param array<int, Media> $thumbnails
*
* @return FindFavoriteDashboardsResponse
*/
private function createResponse(
array $dashboards,
array $contactNames,
array $sharingRolesList,
array $contactShares,
array $contactGroupShares,
DashboardSharingRole $defaultRole,
array $thumbnails,
): FindFavoriteDashboardsResponse {
$dashboardsResponse = [];
foreach ($dashboards as $dashboard) {
$sharingRoles = $sharingRolesList[$dashboard->getId()] ?? null;
$ownRole = $defaultRole->getTheMostPermissiveOfBoth($sharingRoles?->getTheMostPermissiveRole());
$thumbnail = $thumbnails[$dashboard->getId()] ?? null;
$dto = new DashboardResponseDto();
$dto->id = $dashboard->getId();
$dto->name = $dashboard->getName();
$dto->description = $dashboard->getDescription();
$dto->createdAt = $dashboard->getCreatedAt();
$dto->updatedAt = $dashboard->getUpdatedAt();
$dto->ownRole = $ownRole;
if (null !== ($contactId = $dashboard->getCreatedBy())) {
$dto->createdBy = new UserResponseDto();
$dto->createdBy->id = $contactId;
$dto->createdBy->name = $contactNames[$contactId]['name'] ?? '';
}
if (null !== ($contactId = $dashboard->getCreatedBy())) {
$dto->updatedBy = new UserResponseDto();
$dto->updatedBy->id = $contactId;
$dto->updatedBy->name = $contactNames[$contactId]['name'] ?? '';
}
// Add shares only if the user if editor, as the viewers should not be able to see shares.
if ($ownRole === DashboardSharingRole::Editor && array_key_exists($dashboard->getId(), $contactShares)) {
$dto->shares['contacts'] = array_map(static fn (DashboardContactShare $contactShare): array => [
'id' => $contactShare->getContactId(),
'name' => $contactShare->getContactName(),
'email' => $contactShare->getContactEmail(),
'role' => $contactShare->getRole(),
], $contactShares[$dashboard->getId()]);
}
if ($ownRole === DashboardSharingRole::Editor && array_key_exists($dashboard->getId(), $contactGroupShares)) {
$dto->shares['contact_groups'] = array_map(
static fn (DashboardContactGroupShare $contactGroupShare): array => [
'id' => $contactGroupShare->getContactGroupId(),
'name' => $contactGroupShare->getContactGroupName(),
'role' => $contactGroupShare->getRole(),
],
$contactGroupShares[$dashboard->getId()]
);
}
if ($thumbnail !== null) {
$dto->thumbnail = new ThumbnailResponseDto(
$thumbnail->getId(),
$thumbnail->getFilename(),
$thumbnail->getDirectory()
);
}
if (in_array($dto->id, $this->usersFavoriteDashboards, true)) {
$dto->isFavorite = true;
}
$dashboardsResponse[] = $dto;
}
return new FindFavoriteDashboardsResponse(dashboards: $dashboardsResponse);
}
}
| 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/Application/UseCase/FindFavoriteDashboards/Response/ThumbnailResponseDto.php | centreon/src/Core/Dashboard/Application/UseCase/FindFavoriteDashboards/Response/ThumbnailResponseDto.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\Application\UseCase\FindFavoriteDashboards\Response;
final class ThumbnailResponseDto
{
public function __construct(
public int $id = 0,
public string $name = '',
public string $directory = '',
) {
}
}
| 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/Application/UseCase/FindFavoriteDashboards/Response/UserResponseDto.php | centreon/src/Core/Dashboard/Application/UseCase/FindFavoriteDashboards/Response/UserResponseDto.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\Application\UseCase\FindFavoriteDashboards\Response;
final class UserResponseDto
{
public function __construct(
public int $id = 0,
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/Dashboard/Application/UseCase/FindFavoriteDashboards/Response/DashboardResponseDto.php | centreon/src/Core/Dashboard/Application/UseCase/FindFavoriteDashboards/Response/DashboardResponseDto.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\Application\UseCase\FindFavoriteDashboards\Response;
use Core\Dashboard\Domain\Model\Role\DashboardSharingRole;
use DateTimeImmutable;
final class DashboardResponseDto
{
/**
* @param int $id
* @param string $name
* @param string|null $description
* @param UserResponseDto|null $createdBy
* @param UserResponseDto|null $updatedBy
* @param DateTimeImmutable $createdAt
* @param DateTimeImmutable $updatedAt
* @param DashboardSharingRole $ownRole
* @param array{
* contacts: array<array{
* id: int,
* name: string,
* email: string,
* role: DashboardSharingRole
* }>,
* contact_groups: array<array{
* id: int,
* name: string,
* role: DashboardSharingRole
* }>
* } $shares
* @param ThumbnailResponseDto $thumbnail
* @param bool $isFavorite
*/
public function __construct(
public int $id = 0,
public string $name = '',
public ?string $description = null,
public ?UserResponseDto $createdBy = null,
public ?UserResponseDto $updatedBy = null,
public DateTimeImmutable $createdAt = new DateTimeImmutable(),
public DateTimeImmutable $updatedAt = new DateTimeImmutable(),
public DashboardSharingRole $ownRole = DashboardSharingRole::Viewer,
public array $shares = ['contacts' => [], 'contact_groups' => []],
public ?ThumbnailResponseDto $thumbnail = null,
public bool $isFavorite = 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/Dashboard/Application/UseCase/FindDashboardContactGroups/FindDashboardContactGroupsResponse.php | centreon/src/Core/Dashboard/Application/UseCase/FindDashboardContactGroups/FindDashboardContactGroupsResponse.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\Application\UseCase\FindDashboardContactGroups;
use Core\Application\Common\UseCase\ListingResponseInterface;
use Core\Dashboard\Application\UseCase\FindDashboardContactGroups\Response\ContactGroupsResponseDto;
final class FindDashboardContactGroupsResponse implements ListingResponseInterface
{
/**
* @param ContactGroupsResponseDto[] $contactGroups
*/
public function __construct(
public array $contactGroups = [],
) {
}
/**
* @return ContactGroupsResponseDto[]
*/
public function getData(): array
{
return $this->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/Application/UseCase/FindDashboardContactGroups/FindDashboardContactGroups.php | centreon/src/Core/Dashboard/Application/UseCase/FindDashboardContactGroups/FindDashboardContactGroups.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\Application\UseCase\FindDashboardContactGroups;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Repository\RepositoryException;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\Repository\ReadDashboardShareRepositoryInterface;
use Core\Dashboard\Application\UseCase\FindDashboardContactGroups\Response\ContactGroupsResponseDto;
use Core\Dashboard\Domain\Model\DashboardRights;
use Core\Dashboard\Domain\Model\Role\DashboardContactGroupRole;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
final class FindDashboardContactGroups
{
use LoggerTrait;
public const AUTHORIZED_ACL_GROUPS = ['customer_admin_acl'];
public function __construct(
private readonly RequestParametersInterface $requestParameters,
private readonly DashboardRights $rights,
private readonly ContactInterface $contact,
private readonly ReadDashboardShareRepositoryInterface $readDashboardShareRepository,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly bool $isCloudPlatform,
) {
}
/**
* @return FindDashboardContactGroupsResponse|ResponseStatusInterface
*/
public function __invoke(): FindDashboardContactGroupsResponse|ResponseStatusInterface
{
try {
$this->info('Find dashboard contact groups', ['request' => $this->requestParameters->toArray()]);
return $this->isUserAdmin()
? $this->createResponse($this->findContactGroupsAsAdmin())
: $this->createResponse($this->findContactGroupsAsContact());
} catch (RepositoryException $ex) {
$this->error(
$ex->getMessage(),
[
'contact_id' => $this->contact->getId(),
'request_parameters' => $this->requestParameters->toArray(),
'exception' => [
'message' => $ex->getPrevious()?->getMessage(),
'trace' => $ex->getPrevious()?->getTraceAsString(),
],
]
);
return new ErrorResponse(DashboardException::errorWhileSearchingSharableContactGroups());
} catch (\Throwable $ex) {
$this->error(
"Error while retrieving contact groups allowed to receive a dashboard share : {$ex->getMessage()}",
[
'contact_id' => $this->contact->getId(),
'request_parameters' => $this->requestParameters->toArray(),
'exception' => [
'message' => $ex->getMessage(),
'trace' => $ex->getTraceAsString(),
],
]
);
return new ErrorResponse(DashboardException::errorWhileSearchingSharableContactGroups());
}
}
/**
* Cloud UseCase - ACL groups are not linked to contact groups.
* Therefore, we need to retrieve all contact groups as admin.
* Those contact groups will have as most permissive role 'Viewer'.
* No checks will be done regarding Dashboard Rights when sharing to the contact groups selected
* however it will be not possible for contacts belonging to these contact groups
* to have more rights than configured through their ACLs as user dashboard rights will
* be applied for the user that reaches Dashboard.
*
* OnPremise
*
* Retrieve contact groups having access to Dashboard.
*
* @throws \Throwable
*
* @return DashboardContactGroupRole[]
*/
private function findContactGroupsAsAdmin(): array
{
return $this->isCloudPlatform
? $this->readDashboardShareRepository->findContactGroupsByRequestParameters($this->requestParameters)
: $this->readDashboardShareRepository->findContactGroupsWithAccessRightByRequestParameters(
$this->requestParameters
);
}
/**
* Cloud
*
* ACL groups are not linked to contact groups.
* Therefore, we need to retrieve all contact groups to which belongs the current user.
* Those contact groups will have as most permissive role 'Viewer'.
* No checks will be done regarding Dashboard Rights when sharing to the contact groups selected
* however it will be not possible for contacts belonging to these contact groups
* to have more rights than configured through their ACLs as user dashboard rights will
* be applied for the user that reaches Dashboard.
*
* OnPremise
*
* Retrieve contact groups to which belongs the current user and having access to Dashboard.
*
* @throws \Throwable
*
* @return DashboardContactGroupRole[]
*/
private function findContactGroupsAsContact(): array
{
if ($this->isCloudPlatform === true) {
return $this->readDashboardShareRepository->findContactGroupsByUserAndRequestParameters(
$this->requestParameters,
$this->contact->getId()
);
}
return $this->readDashboardShareRepository->findContactGroupsWithAccessRightByUserAndRequestParameters(
$this->requestParameters,
$this->contact->getId()
);
}
/**
* @param DashboardContactGroupRole[] $groups
*/
private function createResponse(array $groups): FindDashboardContactGroupsResponse
{
$response = new FindDashboardContactGroupsResponse();
foreach ($groups as $group) {
$response->contactGroups[] = new ContactGroupsResponseDto(
$group->getContactGroupId(),
$group->getContactGroupName(),
$group->getMostPermissiverole()
);
}
return $response;
}
/**
* @throws \Throwable
*
* @return bool
*/
private function isUserAdmin(): bool
{
if ($this->rights->hasAdminRole()) {
return true;
}
$userAccessGroupNames = array_map(
static fn (AccessGroup $accessGroup): string => $accessGroup->getName(),
$this->readAccessGroupRepository->findByContact($this->contact)
);
return ! (empty(array_intersect($userAccessGroupNames, self::AUTHORIZED_ACL_GROUPS)))
&& $this->isCloudPlatform;
}
}
| 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/Application/UseCase/FindDashboardContactGroups/Response/ContactGroupsResponseDto.php | centreon/src/Core/Dashboard/Application/UseCase/FindDashboardContactGroups/Response/ContactGroupsResponseDto.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\Application\UseCase\FindDashboardContactGroups\Response;
use Core\Dashboard\Domain\Model\Role\DashboardGlobalRole;
final class ContactGroupsResponseDto
{
public function __construct(
public int $id = 0,
public string $name = '',
public DashboardGlobalRole $mostPermissiveRole = DashboardGlobalRole::Viewer,
) {
}
}
| 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/Application/UseCase/AddDashboardThumbnail/AddDashboardThumbnailRequest.php | centreon/src/Core/Dashboard/Application/UseCase/AddDashboardThumbnail/AddDashboardThumbnailRequest.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\Application\UseCase\AddDashboardThumbnail;
final readonly class AddDashboardThumbnailRequest
{
public function __construct(
public int $dashboardId,
public string $directory,
public string $filename,
public string $content,
) {
}
}
| 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/Application/UseCase/AddDashboardThumbnail/AddDashboardThumbnailPresenterInterface.php | centreon/src/Core/Dashboard/Application/UseCase/AddDashboardThumbnail/AddDashboardThumbnailPresenterInterface.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\Application\UseCase\AddDashboardThumbnail;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface AddDashboardThumbnailPresenterInterface
{
/**
* @param NoContentResponse|ResponseStatusInterface $data
*/
public function presentResponse(NoContentResponse|ResponseStatusInterface $data): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Application/UseCase/AddDashboardThumbnail/AddDashboardThumbnail.php | centreon/src/Core/Dashboard/Application/UseCase/AddDashboardThumbnail/AddDashboardThumbnail.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\Application\UseCase\AddDashboardThumbnail;
use Assert\AssertionFailedException;
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\NoContentResponse;
use Core\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\Repository\ReadDashboardRepositoryInterface;
use Core\Dashboard\Application\Repository\WriteDashboardRepositoryInterface;
use Core\Media\Application\Repository\WriteMediaRepositoryInterface;
use Core\Media\Domain\Model\NewMedia;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
final class AddDashboardThumbnail
{
use LoggerTrait;
/**
* @param WriteDashboardRepositoryInterface $writeDashboardRepository
* @param WriteMediaRepositoryInterface $writeMediaRepository
* @param ReadDashboardRepositoryInterface $readDashboardRepository
* @param DataStorageEngineInterface $dataStorageEngine
* @param ContactInterface $user
*/
public function __construct(
private readonly WriteDashboardRepositoryInterface $writeDashboardRepository,
private readonly WriteMediaRepositoryInterface $writeMediaRepository,
private readonly ReadDashboardRepositoryInterface $readDashboardRepository,
private readonly DataStorageEngineInterface $dataStorageEngine,
private readonly ContactInterface $user,
) {
}
/**
* @param AddDashboardThumbnailRequest $request
* @param AddDashboardThumbnailPresenterInterface $presenter
*/
public function __invoke(
AddDashboardThumbnailRequest $request,
AddDashboardThumbnailPresenterInterface $presenter,
): void {
try {
$dashboard = $this->user->isAdmin()
? $this->readDashboardRepository->findOne($request->dashboardId)
: $this->readDashboardRepository->findOneByContact($request->dashboardId, $this->user);
if ($dashboard === null) {
$presenter->presentResponse(new ErrorResponse(
DashboardException::theDashboardDoesNotExist($request->dashboardId),
));
return;
}
$media = $this->createMediaFromRequest($request);
$mediaId = $this->addThumbnail($media);
$this->writeDashboardRepository->addThumbnailRelation($dashboard->getId(), $mediaId);
$presenter->presentResponse(new NoContentResponse());
} catch (\Throwable $exception) {
$this->error($exception->getMessage(), ['trace' => $exception->getTraceAsString()]);
$presenter->presentResponse(new ErrorResponse(DashboardException::errorWhileThumbnailToDashboard()));
}
}
/**
* @param AddDashboardThumbnailRequest $request
* @throws FileException
* @throws AssertionFailedException
* @return NewMedia
*/
private function createMediaFromRequest(AddDashboardThumbnailRequest $request): NewMedia
{
return new NewMedia($request->filename, $request->directory, $request->content);
}
/**
* @param NewMedia $thumbnail
*
* @throws \Throwable
* @return int
*/
private function addThumbnail(NewMedia $thumbnail): int
{
try {
$this->dataStorageEngine->startTransaction();
$mediaId = $this->writeMediaRepository->add($thumbnail);
$this->dataStorageEngine->commitTransaction();
} catch (\Throwable $exception) {
$this->dataStorageEngine->rollbackTransaction();
throw $exception;
}
return $mediaId;
}
}
| 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/Application/UseCase/FindPerformanceMetrics/FindPerformanceMetrics.php | centreon/src/Core/Dashboard/Application/UseCase/FindPerformanceMetrics/FindPerformanceMetrics.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\Application\UseCase\FindPerformanceMetrics;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\Repository\ReadDashboardPerformanceMetricRepositoryInterface;
use Core\Dashboard\Domain\Model\DashboardRights;
use Core\Dashboard\Domain\Model\Metric\PerformanceMetric;
use Core\Dashboard\Domain\Model\Metric\ResourceMetric;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
final readonly class FindPerformanceMetrics
{
public const AUTHORIZED_ACL_GROUPS = ['customer_admin_acl'];
/**
* @param ContactInterface $user
* @param RequestParametersInterface $requestParameters
* @param ReadAccessGroupRepositoryInterface $accessGroupRepository
* @param ReadDashboardPerformanceMetricRepositoryInterface $dashboardMetricRepository
* @param DashboardRights $rights
* @param bool $isCloudPlatform
*/
public function __construct(
private ContactInterface $user,
private RequestParametersInterface $requestParameters,
private ReadAccessGroupRepositoryInterface $accessGroupRepository,
private ReadDashboardPerformanceMetricRepositoryInterface $dashboardMetricRepository,
private DashboardRights $rights,
private bool $isCloudPlatform,
) {
}
/**
* @param FindPerformanceMetricsPresenterInterface $presenter
*/
public function __invoke(FindPerformanceMetricsPresenterInterface $presenter): void
{
try {
if ($this->isUserAdmin()) {
$resourceMetrics = $this->dashboardMetricRepository->findByRequestParameters($this->requestParameters);
} elseif ($this->rights->canAccess()) {
$accessGroups = $this->accessGroupRepository->findByContact($this->user);
$resourceMetrics = $this->dashboardMetricRepository->findByRequestParametersAndAccessGroups(
$this->requestParameters,
$accessGroups
);
} else {
$presenter->presentResponse(new ForbiddenResponse(
DashboardException::accessNotAllowed()->getMessage()
));
return;
}
$presenter->presentResponse($this->createResponse($resourceMetrics));
} catch (RepositoryException $e) {
$presenter->presentResponse(
new ErrorResponse(
message: 'An error occured while retrieving metrics',
context: [
'request_parameters' => $this->requestParameters->toArray(),
'user_id' => $this->user->getId(),
'is_admin' => $this->user->isAdmin(),
'access_groups' => $accessGroups ?? null,
],
exception: $e
)
);
return;
}
}
/**
* Create Response.
*
* @param ResourceMetric[] $resourceMetrics
*
* @return FindPerformanceMetricsResponse
*/
private function createResponse(array $resourceMetrics): FindPerformanceMetricsResponse
{
$response = new FindPerformanceMetricsResponse();
$resourceMetricsResponse = [];
foreach ($resourceMetrics as $resourceMetric) {
$resourceMetricDto = new ResourceMetricDto();
$resourceMetricDto->serviceId = $resourceMetric->getServiceId();
$resourceMetricDto->resourceName = $resourceMetric->getResourceName();
$resourceMetricDto->parentName = $resourceMetric->getParentName();
$resourceMetricDto->parentId = $resourceMetric->getParentId();
$resourceMetricDto->metrics = array_map(
fn (PerformanceMetric $metric) => [
'id' => $metric->getId(),
'name' => $metric->getName(),
'unit' => $metric->getUnit(),
'warning_high_threshold' => $metric->getWarningHighThreshold(),
'critical_high_threshold' => $metric->getCriticalHighThreshold(),
'warning_low_threshold' => $metric->getWarningLowThreshold(),
'critical_low_threshold' => $metric->getCriticalLowThreshold(),
],
$resourceMetric->getMetrics()
);
$resourceMetricsResponse[] = $resourceMetricDto;
}
$response->resourceMetrics = $resourceMetricsResponse;
return $response;
}
/**
* @throws RepositoryException
*
* @return bool
*/
private function isUserAdmin(): bool
{
if ($this->rights->hasAdminRole()) {
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)))
&& $this->isCloudPlatform;
}
}
| 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/Application/UseCase/FindPerformanceMetrics/FindPerformanceMetricsPresenterInterface.php | centreon/src/Core/Dashboard/Application/UseCase/FindPerformanceMetrics/FindPerformanceMetricsPresenterInterface.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\Application\UseCase\FindPerformanceMetrics;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface FindPerformanceMetricsPresenterInterface
{
public function presentResponse(FindPerformanceMetricsResponse|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/Dashboard/Application/UseCase/FindPerformanceMetrics/FindPerformanceMetricsResponse.php | centreon/src/Core/Dashboard/Application/UseCase/FindPerformanceMetrics/FindPerformanceMetricsResponse.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\Application\UseCase\FindPerformanceMetrics;
final class FindPerformanceMetricsResponse
{
/** @var ResourceMetricDto[] */
public array $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/Application/UseCase/FindPerformanceMetrics/ResourceMetricDto.php | centreon/src/Core/Dashboard/Application/UseCase/FindPerformanceMetrics/ResourceMetricDto.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\Application\UseCase\FindPerformanceMetrics;
class ResourceMetricDto
{
public int $serviceId = 0;
public string $resourceName = '';
public string $parentName = '';
public int $parentId = 0;
/**
* @var array<
* array{
* id: int,
* name: string,
* unit: string
* }
* >
*/
public array $metrics = [];
}
| 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/Application/UseCase/FindDashboardContacts/FindDashboardContacts.php | centreon/src/Core/Dashboard/Application/UseCase/FindDashboardContacts/FindDashboardContacts.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\Application\UseCase\FindDashboardContacts;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Contact\Application\Repository\ReadContactGroupRepositoryInterface;
use Core\Contact\Application\Repository\ReadContactRepositoryInterface;
use Core\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\Repository\ReadDashboardShareRepositoryInterface;
use Core\Dashboard\Application\UseCase\FindDashboardContacts\Response\ContactsResponseDto;
use Core\Dashboard\Domain\Model\DashboardRights;
use Core\Dashboard\Domain\Model\Role\DashboardContactRole;
use Core\Dashboard\Domain\Model\Role\DashboardGlobalRole;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
final class FindDashboardContacts
{
use LoggerTrait;
public const AUTHORIZED_ACL_GROUPS = ['customer_admin_acl'];
/**
* @param RequestParametersInterface $requestParameters
* @param DashboardRights $rights
* @param ContactInterface $contact
* @param ReadDashboardShareRepositoryInterface $readDashboardShareRepository
* @param ReadAccessGroupRepositoryInterface $readAccessGroupRepository
* @param ReadContactRepositoryInterface $readContactRepository
* @param bool $isCloudPlatform
* @param ReadContactGroupRepositoryInterface $readContactGroupRepository
*/
public function __construct(
private readonly RequestParametersInterface $requestParameters,
private readonly DashboardRights $rights,
private readonly ContactInterface $contact,
private readonly ReadDashboardShareRepositoryInterface $readDashboardShareRepository,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly ReadContactRepositoryInterface $readContactRepository,
private readonly ReadContactGroupRepositoryInterface $readContactGroupRepository,
private readonly bool $isCloudPlatform,
) {
}
/**
* @return FindDashboardContactsResponse|ResponseStatusInterface
*/
public function __invoke(): FindDashboardContactsResponse|ResponseStatusInterface
{
try {
return $this->isUserAdmin()
? $this->createResponse($this->findContactAsAdmin())
: $this->createResponse($this->findContactsAsNonAdmin());
} catch (RepositoryException $ex) {
$this->error(
$ex->getMessage(),
[
'contact_id' => $this->contact->getId(),
'request_parameters' => $this->requestParameters->toArray(),
'exception' => [
'message' => $ex->getPrevious()?->getMessage(),
'trace' => $ex->getPrevious()?->getTraceAsString(),
],
]
);
return new ErrorResponse(DashboardException::errorWhileSearchingSharableContacts());
} catch (\Throwable $ex) {
$this->error(
"Error while retrieving contacts allowed to receive a dashboard share : {$ex->getMessage()}",
[
'contact_id' => $this->contact->getId(),
'request_parameters' => $this->requestParameters->toArray(),
'exception' => [
'message' => $ex->getMessage(),
'trace' => $ex->getTraceAsString(),
],
]
);
return new ErrorResponse(DashboardException::errorWhileSearchingSharableContacts());
}
}
/**
* @param DashboardContactRole[] $users
*/
private function createResponse(array $users): FindDashboardContactsResponse
{
$response = new FindDashboardContactsResponse();
foreach ($users as $user) {
$response->contacts[] = new ContactsResponseDto(
$user->getContactId(),
$user->getContactName(),
$user->getContactEmail(),
$user->getMostPermissiveRole()
);
}
return $response;
}
/**
* Find contacts with their Dashboards roles.
* Cloud - Return all users with Dashboard access rights (including cloud administrators linked to customer_admin_acl).
* OnPremise - Return all users with Dashboard access rights and administrators (not link with ACL Groups onPremise).
*
* @throws \Throwable
*
* @return DashboardContactRole[]
*/
private function findContactAsAdmin(): array
{
$users = $this->readDashboardShareRepository->findContactsWithAccessRightByRequestParameters(
$this->requestParameters
);
if ($this->isCloudPlatform === false) {
$total = $this->requestParameters->getTotal();
$admins = $this->readContactRepository->findAdminWithRequestParameters(
$this->requestParameters
);
$this->requestParameters->setTotal($total + $this->requestParameters->getTotal());
$adminContactRoles = [];
foreach ($admins as $admin) {
$adminContactRoles[] = new DashboardContactRole(
$admin->getId(),
$admin->getName(),
$admin->getEmail(),
[DashboardGlobalRole::Administrator]
);
}
return [...$users, ...$adminContactRoles];
}
return $users;
}
/**
* Find contacts with their Dashboards roles.
* Cloud - Return users that are part of the same contact groups as the current user.
* OnPrem - Return users that are part of the same access groups as the current user.
*
* @throws \Throwable
*
* @return DashboardContactRole[]
*/
private function findContactsAsNonAdmin(): array
{
if ($this->isCloudPlatform === true) {
$contactGroups = $this->readContactGroupRepository->findAllByUserId($this->contact->getId());
return $this->readDashboardShareRepository->findContactsWithAccessRightsByContactGroupsAndRequestParameters(
$contactGroups,
$this->requestParameters
);
}
$accessGroups = $this->readAccessGroupRepository->findByContact($this->contact);
$accessGroupIds = array_map(static fn (AccessGroup $accessGroup): int => $accessGroup->getId(), $accessGroups);
return $this->readDashboardShareRepository->findContactsWithAccessRightByACLGroupsAndRequestParameters(
$this->requestParameters,
$accessGroupIds
);
}
/**
* @throws \Throwable
*
* @return bool
*/
private function isUserAdmin(): bool
{
if ($this->rights->hasAdminRole()) {
return true;
}
$userAccessGroupNames = array_map(
static fn (AccessGroup $accessGroup): string => $accessGroup->getName(),
$this->readAccessGroupRepository->findByContact($this->contact)
);
return ! (empty(array_intersect($userAccessGroupNames, self::AUTHORIZED_ACL_GROUPS)))
&& $this->isCloudPlatform;
}
}
| 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/Application/UseCase/FindDashboardContacts/FindDashboardContactsResponse.php | centreon/src/Core/Dashboard/Application/UseCase/FindDashboardContacts/FindDashboardContactsResponse.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\Application\UseCase\FindDashboardContacts;
use Core\Application\Common\UseCase\ListingResponseInterface;
use Core\Dashboard\Application\UseCase\FindDashboardContacts\Response\ContactsResponseDto;
final class FindDashboardContactsResponse implements ListingResponseInterface
{
/**
* @param ContactsResponseDto[] $contacts
*/
public function __construct(
public array $contacts = [],
) {
}
/**
* @return ContactsResponseDto[]
*/
public function getData(): array
{
return $this->contacts;
}
}
| 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/Application/UseCase/FindDashboardContacts/Response/ContactsResponseDto.php | centreon/src/Core/Dashboard/Application/UseCase/FindDashboardContacts/Response/ContactsResponseDto.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\Application\UseCase\FindDashboardContacts\Response;
use Core\Dashboard\Domain\Model\Role\DashboardGlobalRole;
final class ContactsResponseDto
{
/**
* @param int $id
* @param string $name
* @param string $email
* @param DashboardGlobalRole $mostPermissiveRole
*/
public function __construct(
public int $id = 0,
public string $name = '',
public string $email = '',
public DashboardGlobalRole $mostPermissiveRole = DashboardGlobalRole::Viewer,
) {
}
}
| 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/Application/UseCase/DeleteContactDashboardShare/DeleteContactDashboardSharePresenterInterface.php | centreon/src/Core/Dashboard/Application/UseCase/DeleteContactDashboardShare/DeleteContactDashboardSharePresenterInterface.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\Application\UseCase\DeleteContactDashboardShare;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface DeleteContactDashboardSharePresenterInterface
{
public function presentResponse(NoContentResponse|ResponseStatusInterface $data): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Application/UseCase/DeleteContactDashboardShare/DeleteContactDashboardShare.php | centreon/src/Core/Dashboard/Application/UseCase/DeleteContactDashboardShare/DeleteContactDashboardShare.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\Application\UseCase\DeleteContactDashboardShare;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Contact\Interfaces\ContactRepositoryInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Contact\Application\Repository\ReadContactRepositoryInterface;
use Core\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\Repository\ReadDashboardRepositoryInterface;
use Core\Dashboard\Application\Repository\ReadDashboardShareRepositoryInterface;
use Core\Dashboard\Application\Repository\WriteDashboardShareRepositoryInterface;
use Core\Dashboard\Domain\Model\Dashboard;
use Core\Dashboard\Domain\Model\DashboardRights;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
final class DeleteContactDashboardShare
{
use LoggerTrait;
public const AUTHORIZED_ACL_GROUPS = ['customer_admin_acl'];
public function __construct(
private readonly ReadDashboardShareRepositoryInterface $readDashboardShareRepository,
private readonly ReadDashboardRepositoryInterface $readDashboardRepository,
private readonly WriteDashboardShareRepositoryInterface $writeDashboardShareRepository,
private readonly ContactRepositoryInterface $contactRepository,
private readonly DashboardRights $rights,
private readonly ContactInterface $contact,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly ReadContactRepositoryInterface $readContactRepository,
private readonly bool $isCloudPlatform,
) {
}
public function __invoke(
int $dashboardId,
int $contactId,
DeleteContactDashboardSharePresenterInterface $presenter,
): void {
try {
if ($this->isUserAdmin()) {
if ($dashboard = $this->readDashboardRepository->findOne($dashboardId)) {
$this->info('Delete a contact share for dashboard', ['id' => $dashboardId, 'contact_id' => $contactId]);
$response = $this->deleteContactShareAsAdmin($dashboard, $contactId);
} else {
$this->warning('Dashboard (%s) not found', ['id' => $dashboardId]);
$response = new NotFoundResponse('Dashboard');
}
} elseif ($this->rights->canCreate()) {
if ($dashboard = $this->readDashboardRepository->findOneByContact($dashboardId, $this->contact)) {
$this->info('Delete a contact share for dashboard', ['id' => $dashboardId, 'contact_id' => $contactId]);
$response = $this->deleteContactShareAsContact($dashboard, $contactId);
} else {
$this->warning('Dashboard (%s) not found', ['id' => $dashboardId]);
$response = new NotFoundResponse('Dashboard');
}
} else {
$this->error(
"User doesn't have sufficient rights to see dashboards",
['user_id' => $this->contact->getId()]
);
$response = new ForbiddenResponse(DashboardException::accessNotAllowedForWriting());
}
$presenter->presentResponse($response);
} catch (AssertionFailedException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->presentResponse(new InvalidArgumentResponse($ex));
} catch (DashboardException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->presentResponse(new ErrorResponse($ex));
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->presentResponse(new ErrorResponse('Error while deleting the dashboard share'));
}
}
/**
* @param Dashboard $dashboard
* @param int $contactId
*
* @throws \Throwable
*
* @return ResponseStatusInterface
*/
private function deleteContactShareAsAdmin(Dashboard $dashboard, int $contactId): ResponseStatusInterface
{
$contact = $this->contactRepository->findById($contactId);
if ($contact === null) {
$this->warning('Contact (%s) not found', ['id' => $contactId]);
return new NotFoundResponse('Contact');
}
if (! $this->writeDashboardShareRepository->deleteContactShare($contact->getId(), $dashboard->getId())) {
return new NotFoundResponse('Dashboard share');
}
return new NoContentResponse();
}
/**
* @param Dashboard $dashboard
* @param int $contactId
*
* @throws \Throwable
*
* @return ResponseStatusInterface
*/
private function deleteContactShareAsContact(Dashboard $dashboard, int $contactId): ResponseStatusInterface
{
$contact = $this->contactRepository->findById($contactId);
if ($contact === null) {
$this->warning('Contact (%s) not found', ['id' => $contactId]);
return new NotFoundResponse('Contact');
}
$sharingRoles = $this->readDashboardShareRepository->getOneSharingRoles($this->contact, $dashboard);
if (! $this->rights->canDeleteShare($sharingRoles)) {
return new ForbiddenResponse(
DashboardException::dashboardAccessRightsNotAllowedForWriting($dashboard->getId())
);
}
$accessGroups = $this->readAccessGroupRepository->findByContact($this->contact);
$accessGroupIds = array_map(static fn (AccessGroup $accessGroup): int => $accessGroup->getId(), $accessGroups);
if (! $this->readContactRepository->existInAccessGroups($contact->getId(), $accessGroupIds)) {
return new NotFoundResponse('Contact');
}
if (! $this->writeDashboardShareRepository->deleteContactShare($contact->getId(), $dashboard->getId())) {
return new NotFoundResponse('Dashboard share');
}
return new NoContentResponse();
}
/**
* @throws \Throwable
*
* @return bool
*/
private function isUserAdmin(): bool
{
if ($this->rights->hasAdminRole()) {
return true;
}
$userAccessGroupNames = array_map(
static fn (AccessGroup $accessGroup): string => $accessGroup->getName(),
$this->readAccessGroupRepository->findByContact($this->contact)
);
return ! (empty(array_intersect($userAccessGroupNames, self::AUTHORIZED_ACL_GROUPS)))
&& $this->isCloudPlatform;
}
}
| 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/Application/UseCase/AddDashboardToFavorites/AddDashboardToFavorites.php | centreon/src/Core/Dashboard/Application/UseCase/AddDashboardToFavorites/AddDashboardToFavorites.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\Application\UseCase\AddDashboardToFavorites;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ConflictResponse;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\Repository\ReadDashboardRepositoryInterface;
use Core\UserProfile\Application\Repository\ReadUserProfileRepositoryInterface;
use Core\UserProfile\Application\Repository\WriteUserProfileRepositoryInterface;
use InvalidArgumentException;
use Throwable;
final class AddDashboardToFavorites
{
use LoggerTrait;
/**
* @param ReadUserProfileRepositoryInterface $userProfileReader
* @param WriteUserProfileRepositoryInterface $userProfileWriter
* @param ReadDashboardRepositoryInterface $dashboardReader
* @param ContactInterface $user
*/
public function __construct(
private readonly ReadUserProfileRepositoryInterface $userProfileReader,
private readonly WriteUserProfileRepositoryInterface $userProfileWriter,
private readonly ReadDashboardRepositoryInterface $dashboardReader,
private readonly ContactInterface $user,
) {
}
/**
* @param AddDashboardToFavoritesRequest $request
* @return ResponseStatusInterface
*/
public function __invoke(AddDashboardToFavoritesRequest $request): ResponseStatusInterface
{
try {
$this->assertDashboardId($request);
$favorites = [];
$profileId = $this->addDefaultUserProfileForUser();
$profile = $this->userProfileReader->findByContact($this->user);
if (! is_null($profile)) {
$favorites = $profile->getFavoriteDashboards();
$profileId = $profile->getId();
}
if (in_array($request->dashboardId, $favorites, true)) {
$this->error(
'Dashboard already set as favorite for user',
[
'dashboard_id' => $request->dashboardId,
'user_id' => $this->user->getId(),
]
);
return new ConflictResponse(DashboardException::dashboardAlreadySetAsFavorite($request->dashboardId));
}
$this->userProfileWriter->addDashboardAsFavorites(
profileId: $profileId,
dashboardId: $request->dashboardId,
);
return new NoContentResponse();
} catch (InvalidArgumentException $exception) {
$this->error($exception->getMessage());
$this->error(
"Error while adding dashboard as favorite for user : {$exception->getMessage()}",
[
'user_id' => $this->user->getId(),
'dashboard_id' => $request->dashboardId,
'favorite_dashboards' => $favorites ?? [],
'exception' => ['message' => $exception->getMessage(), 'trace' => $exception->getTraceAsString()],
]
);
return new InvalidArgumentResponse($exception);
} catch (Throwable $exception) {
$this->error(
"Error while adding dashboard as favorite for user : {$exception->getMessage()}",
[
'user_id' => $this->user->getId(),
'dashboard_id' => $request->dashboardId,
'profile_id' => $profileId ?? null,
'favorite_dashboards' => $favorites ?? [],
'exception' => ['message' => $exception->getMessage(), 'trace' => $exception->getTraceAsString()],
]
);
return new ErrorResponse($exception);
}
}
/**
* @throws Throwable
* @return int
*/
private function addDefaultUserProfileForUser(): int
{
return $this->userProfileWriter->addDefaultProfileForUser(contact: $this->user);
}
/**
* @param AddDashboardToFavoritesRequest $request
*
* @throws Throwable
* @throws DashboardException
*/
private function assertDashboardId(AddDashboardToFavoritesRequest $request): void
{
if (! $this->dashboardReader->existsOne($request->dashboardId)) {
throw DashboardException::theDashboardDoesNotExist($request->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/Application/UseCase/AddDashboardToFavorites/AddDashboardToFavoritesRequest.php | centreon/src/Core/Dashboard/Application/UseCase/AddDashboardToFavorites/AddDashboardToFavoritesRequest.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\Application\UseCase\AddDashboardToFavorites;
final readonly class AddDashboardToFavoritesRequest
{
/**
* @param int $dashboardId
*/
public function __construct(public int $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/Application/UseCase/DeleteContactGroupDashboardShare/DeleteContactGroupDashboardSharePresenterInterface.php | centreon/src/Core/Dashboard/Application/UseCase/DeleteContactGroupDashboardShare/DeleteContactGroupDashboardSharePresenterInterface.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\Application\UseCase\DeleteContactGroupDashboardShare;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface DeleteContactGroupDashboardSharePresenterInterface
{
public function presentResponse(NoContentResponse|ResponseStatusInterface $data): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Application/UseCase/DeleteContactGroupDashboardShare/DeleteContactGroupDashboardShare.php | centreon/src/Core/Dashboard/Application/UseCase/DeleteContactGroupDashboardShare/DeleteContactGroupDashboardShare.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\Application\UseCase\DeleteContactGroupDashboardShare;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Contact\Application\Repository\ReadContactGroupRepositoryInterface;
use Core\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\Repository\ReadDashboardRepositoryInterface;
use Core\Dashboard\Application\Repository\ReadDashboardShareRepositoryInterface;
use Core\Dashboard\Application\Repository\WriteDashboardShareRepositoryInterface;
use Core\Dashboard\Domain\Model\Dashboard;
use Core\Dashboard\Domain\Model\DashboardRights;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
final class DeleteContactGroupDashboardShare
{
use LoggerTrait;
public const AUTHORIZED_ACL_GROUPS = ['customer_admin_acl'];
public function __construct(
private readonly ReadDashboardShareRepositoryInterface $readDashboardShareRepository,
private readonly ReadDashboardRepositoryInterface $readDashboardRepository,
private readonly WriteDashboardShareRepositoryInterface $writeDashboardShareRepository,
private readonly ReadContactGroupRepositoryInterface $readContactGroupRepository,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly DashboardRights $rights,
private readonly ContactInterface $contact,
private readonly bool $isCloudPlatform,
) {
}
public function __invoke(
int $dashboardId,
int $contactGroupId,
DeleteContactGroupDashboardSharePresenterInterface $presenter,
): void {
try {
if ($this->isUserAdmin()) {
if ($dashboard = $this->readDashboardRepository->findOne($dashboardId)) {
$this->info(
'Delete a contact group share for dashboard',
['id' => $dashboardId, 'contact_id' => $contactGroupId]
);
$response = $this->deleteContactGroupShareAsAdmin($dashboard, $contactGroupId);
} else {
$this->warning('Dashboard (%s) not found', ['id' => $dashboardId]);
$response = new NotFoundResponse('Dashboard');
}
} elseif ($this->rights->canCreate()) {
if ($dashboard = $this->readDashboardRepository->findOneByContact($dashboardId, $this->contact)) {
$this->info(
'Delete a contact contact group for dashboard',
['id' => $dashboardId, 'contact_id' => $contactGroupId]
);
$response = $this->deleteContactGroupShareAsContact($dashboard, $contactGroupId);
} else {
$this->warning('Dashboard (%s) not found', ['id' => $dashboardId]);
$response = new NotFoundResponse('Dashboard');
}
} else {
$this->error(
"User doesn't have sufficient rights to see dashboards",
['user_id' => $this->contact->getId()]
);
$response = new ForbiddenResponse(DashboardException::accessNotAllowedForWriting());
}
$presenter->presentResponse($response);
} catch (AssertionFailedException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->presentResponse(new InvalidArgumentResponse($ex));
} catch (DashboardException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->presentResponse(new ErrorResponse($ex));
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->presentResponse(new ErrorResponse('Error while deleting the dashboard share'));
}
}
/**
* @param Dashboard $dashboard
* @param int $contactGroupId
*
* @throws \Throwable
*
* @return ResponseStatusInterface
*/
private function deleteContactGroupShareAsAdmin(Dashboard $dashboard, int $contactGroupId): ResponseStatusInterface
{
$group = $this->readContactGroupRepository->find($contactGroupId);
if ($group === null) {
$this->warning('Contact group (%s) not found', ['id' => $contactGroupId]);
return new NotFoundResponse('Contact');
}
if (! $this->writeDashboardShareRepository->deleteContactGroupShare($group->getId(), $dashboard->getId())) {
return new NotFoundResponse('Dashboard share');
}
return new NoContentResponse();
}
/**
* @param Dashboard $dashboard
* @param int $contactGroupId
*
* @throws \Throwable
*
* @return ResponseStatusInterface
*/
private function deleteContactGroupShareAsContact(Dashboard $dashboard, int $contactGroupId): ResponseStatusInterface
{
$group = $this->readContactGroupRepository->find($contactGroupId);
if ($group === null) {
$this->warning('Contact group (%s) not found', ['id' => $contactGroupId]);
return new NotFoundResponse('Contact');
}
$sharingRoles = $this->readDashboardShareRepository->getOneSharingRoles($this->contact, $dashboard);
if (! $this->rights->canDeleteShare($sharingRoles)) {
return new ForbiddenResponse(
DashboardException::dashboardAccessRightsNotAllowedForWriting($dashboard->getId())
);
}
$accessGroups = $this->readAccessGroupRepository->findByContact($this->contact);
$accessGroupIds = array_map(static fn (AccessGroup $accessGroup): int => $accessGroup->getId(), $accessGroups);
if (! $this->readContactGroupRepository->existsInAccessGroups($group->getId(), $accessGroupIds)) {
return new NotFoundResponse('Contact Group');
}
if (! $this->writeDashboardShareRepository->deleteContactGroupShare($group->getId(), $dashboard->getId())) {
return new NotFoundResponse('Dashboard share');
}
return new NoContentResponse();
}
/**
* @throws \Throwable
*
* @return bool
*/
private function isUserAdmin(): bool
{
if ($this->rights->hasAdminRole()) {
return true;
}
$userAccessGroupNames = array_map(
static fn (AccessGroup $accessGroup): string => $accessGroup->getName(),
$this->readAccessGroupRepository->findByContact($this->contact)
);
return ! (empty(array_intersect($userAccessGroupNames, self::AUTHORIZED_ACL_GROUPS)))
&& $this->isCloudPlatform;
}
}
| 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/Application/UseCase/PartialUpdateDashboard/PartialUpdateDashboard.php | centreon/src/Core/Dashboard/Application/UseCase/PartialUpdateDashboard/PartialUpdateDashboard.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\Application\UseCase\PartialUpdateDashboard;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Common\Application\Type\NoValue;
use Core\Dashboard\Application\Event\DashboardUpdatedEvent;
use Core\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\Repository\ReadDashboardPanelRepositoryInterface;
use Core\Dashboard\Application\Repository\ReadDashboardRepositoryInterface;
use Core\Dashboard\Application\Repository\ReadDashboardShareRepositoryInterface;
use Core\Dashboard\Application\Repository\WriteDashboardPanelRepositoryInterface;
use Core\Dashboard\Application\Repository\WriteDashboardRepositoryInterface;
use Core\Dashboard\Application\UseCase\PartialUpdateDashboard\Request\ThumbnailRequestDto;
use Core\Dashboard\Domain\Model\Dashboard;
use Core\Dashboard\Domain\Model\DashboardRights;
use Core\Dashboard\Domain\Model\Refresh;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
final class PartialUpdateDashboard
{
use LoggerTrait;
public const AUTHORIZED_ACL_GROUPS = ['customer_admin_acl'];
public function __construct(
private readonly ReadDashboardRepositoryInterface $readDashboardRepository,
private readonly WriteDashboardRepositoryInterface $writeDashboardRepository,
private readonly ReadDashboardPanelRepositoryInterface $readDashboardPanelRepository,
private readonly ReadDashboardShareRepositoryInterface $readDashboardShareRepository,
private readonly WriteDashboardPanelRepositoryInterface $writeDashboardPanelRepository,
private readonly DataStorageEngineInterface $dataStorageEngine,
private readonly DashboardRights $rights,
private readonly ContactInterface $contact,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly EventDispatcherInterface $dispatcher,
private readonly bool $isCloudPlatform,
) {
}
/**
* @param int $dashboardId
* @param PartialUpdateDashboardRequest $request
* @param PartialUpdateDashboardPresenterInterface $presenter
*/
public function __invoke(
int $dashboardId,
PartialUpdateDashboardRequest $request,
PartialUpdateDashboardPresenterInterface $presenter,
): void {
try {
if ($this->isUserAdmin()) {
$response = $this->partialUpdateDashboardAsAdmin($dashboardId, $request);
} elseif ($this->rights->canCreate()) {
$response = $this->partialUpdateDashboardAsContact($dashboardId, $request);
} else {
$response = new ForbiddenResponse(DashboardException::accessNotAllowedForWriting());
}
if ($response instanceof NoContentResponse) {
$this->info('Update dashboard', ['request' => $request]);
} elseif ($response instanceof NotFoundResponse) {
$this->warning('Dashboard (%s) not found', ['id' => $dashboardId]);
} else {
$this->error(
"User doesn't have sufficient rights to update dashboards",
['user_id' => $this->contact->getId()]
);
}
// dispatch DashboardUpdatedEvent that will be handled by a subscriber
if (! $request->thumbnail instanceof NoValue) {
$this->updateOrCreateDashboardThumbnail($dashboardId, $request->thumbnail);
}
$presenter->presentResponse($response);
} catch (AssertionFailedException $ex) {
$presenter->presentResponse(new InvalidArgumentResponse($ex));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (DashboardException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->presentResponse(new ErrorResponse($ex));
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->presentResponse(new ErrorResponse(DashboardException::errorWhileUpdating()));
}
}
/**
* @param int $dashboardId
* @param ThumbnailRequestDto $request
* @throws FileException
* @throws \Throwable
*/
private function updateOrCreateDashboardThumbnail(int $dashboardId, ThumbnailRequestDto $request): void
{
$thumbnail = $this->readDashboardRepository->findThumbnailByDashboardId($dashboardId);
if ($thumbnail !== null) {
$event = new DashboardUpdatedEvent(
dashboardId: $dashboardId,
directory: $thumbnail->getDirectory(),
content: $request->content,
filename: $thumbnail->getFilename(),
thumbnailId: $thumbnail->getId()
);
} else {
$event = new DashboardUpdatedEvent(
dashboardId: $dashboardId,
directory: $request->directory,
content: $request->content,
filename: $request->name
);
}
$this->dispatcher->dispatch($event);
}
/**
* @param PartialUpdateDashboardRequest $request
* @param int $dashboardId
*
* @throws DashboardException
* @throws \Throwable
* @return NoContentResponse|NotFoundResponse
*/
private function partialUpdateDashboardAsAdmin(
int $dashboardId,
PartialUpdateDashboardRequest $request,
): NoContentResponse|NotFoundResponse {
$dashboard = $this->readDashboardRepository->findOne($dashboardId);
if ($dashboard === null) {
return new NotFoundResponse('Dashboard');
}
$this->updateDashboardAndSave($dashboard, $request);
return new NoContentResponse();
}
/**
* @param PartialUpdateDashboardRequest $request
* @param int $dashboardId
*
* @throws DashboardException
* @throws \Throwable
* @return NoContentResponse|NotFoundResponse|ForbiddenResponse
*/
private function partialUpdateDashboardAsContact(
int $dashboardId,
PartialUpdateDashboardRequest $request,
): NoContentResponse|NotFoundResponse|ForbiddenResponse {
$dashboard = $this->readDashboardRepository->findOneByContact($dashboardId, $this->contact);
if ($dashboard === null) {
return new NotFoundResponse('Dashboard');
}
$sharingRoles = $this->readDashboardShareRepository->getOneSharingRoles($this->contact, $dashboard);
if (! $this->rights->canUpdate($sharingRoles)) {
return new ForbiddenResponse(DashboardException::dashboardAccessRightsNotAllowedForWriting($dashboardId));
}
$this->updateDashboardAndSave($dashboard, $request);
return new NoContentResponse();
}
/**
* @param Dashboard $dashboard
* @param PartialUpdateDashboardRequest $request
*
* @throws AssertionFailedException|\Throwable
*/
private function updateDashboardAndSave(Dashboard $dashboard, PartialUpdateDashboardRequest $request): void
{
// Build of the new domain objects.
$updatedDashboard = $this->getUpdatedDashboard($dashboard, $request);
$panelsDifference = null;
if (! ($request->panels instanceof NoValue)) {
$panelIdsFromRepository = $this->readDashboardPanelRepository->findPanelIdsByDashboardId($dashboard->getId());
$panelsDifference = new PartialUpdateDashboardPanelsDifference($panelIdsFromRepository, $request->panels);
}
// Store the objects into the repositories.
try {
$this->dataStorageEngine->startTransaction();
$this->writeDashboardRepository->update($updatedDashboard);
if ($panelsDifference !== null) {
foreach ($panelsDifference->getPanelIdsToDelete() as $id) {
$this->writeDashboardPanelRepository->deletePanel($id);
}
foreach ($panelsDifference->getPanelsToCreate() as $panel) {
$this->writeDashboardPanelRepository->addPanel($dashboard->getId(), $panel);
}
foreach ($panelsDifference->getPanelsToUpdate() as $panel) {
$this->writeDashboardPanelRepository->updatePanel($dashboard->getId(), $panel);
}
}
$this->dataStorageEngine->commitTransaction();
} catch (\Throwable $ex) {
$this->error("Rollback of 'Partial Update Dashboard' transaction.");
$this->dataStorageEngine->rollbackTransaction();
throw $ex;
}
}
/**
* @param Dashboard $dashboard
* @param PartialUpdateDashboardRequest $request
*
* @throws AssertionFailedException
* @return Dashboard
*/
private function getUpdatedDashboard(Dashboard $dashboard, PartialUpdateDashboardRequest $request): Dashboard
{
return (new Dashboard(
id: $dashboard->getId(),
name: NoValue::coalesce($request->name, $dashboard->getName()),
createdBy: $dashboard->getCreatedBy(),
updatedBy: $this->contact->getId(),
createdAt: $dashboard->getCreatedAt(),
updatedAt: new \DateTimeImmutable(),
refresh: ($request->refresh instanceof NoValue)
? new Refresh(
$dashboard->getRefresh()->getRefreshType(),
$dashboard->getRefresh()->getRefreshInterval()
)
: new Refresh($request->refresh->refreshType, $request->refresh->refreshInterval)
))->setDescription(
NoValue::coalesce(
$request->description !== '' ? $request->description : null,
$dashboard->getDescription(),
),
);
}
/**
* @throws \Throwable
*
* @return bool
*/
private function isUserAdmin(): bool
{
if ($this->rights->hasAdminRole()) {
return true;
}
$userAccessGroupNames = array_map(
static fn (AccessGroup $accessGroup): string => $accessGroup->getName(),
$this->readAccessGroupRepository->findByContact($this->contact)
);
return ! (empty(array_intersect($userAccessGroupNames, self::AUTHORIZED_ACL_GROUPS)))
&& $this->isCloudPlatform;
}
}
| 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/Application/UseCase/PartialUpdateDashboard/PartialUpdateDashboardPanelsDifference.php | centreon/src/Core/Dashboard/Application/UseCase/PartialUpdateDashboard/PartialUpdateDashboardPanelsDifference.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\Application\UseCase\PartialUpdateDashboard;
use Assert\AssertionFailedException;
use Core\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\UseCase\PartialUpdateDashboard\Request\PanelRequestDto;
use Core\Dashboard\Domain\Model\DashboardPanel;
use Core\Dashboard\Domain\Model\NewDashboardPanel;
/**
* The goal of this class is to know how to make the different repository calls depending on update data.
*/
final class PartialUpdateDashboardPanelsDifference
{
/** @var array<NewDashboardPanel> */
private ?array $panelsToCreate = null;
/** @var array<DashboardPanel> */
private ?array $panelsToUpdate = null;
/** @var array<int> */
private ?array $panelIdsToDelete = null;
/**
* @param array<int> $panelIdsFromRepository
* @param array<PanelRequestDto> $panelsFromRequest
*
* @throws DashboardException
*/
public function __construct(
private readonly array $panelIdsFromRepository,
private readonly array $panelsFromRequest,
) {
foreach ($this->panelsFromRequest as $dtoPanel) {
if ($dtoPanel->id && ! \in_array($dtoPanel->id, $this->panelIdsFromRepository, true)) {
throw DashboardException::errorTryingToUpdateAPanelWhichDoesNotBelongsToTheDashboard();
}
}
}
/**
* @throws AssertionFailedException
*
* @return list<NewDashboardPanel>
*/
public function getPanelsToCreate(): array
{
if ($this->panelsToCreate === null) {
$this->panelsToCreate = [];
foreach ($this->panelsFromRequest as $dtoPanel) {
if (empty($dtoPanel->id)) {
$this->panelsToCreate[] = $this->createNewDashboardPanel($dtoPanel);
}
}
}
return $this->panelsToCreate;
}
/**
* @throws AssertionFailedException
*
* @return list<DashboardPanel>
*/
public function getPanelsToUpdate(): array
{
if ($this->panelsToUpdate === null) {
$this->panelsToUpdate = [];
foreach ($this->panelsFromRequest as $dtoPanel) {
if (\in_array($dtoPanel->id, $this->panelIdsFromRepository, true)) {
$this->panelsToUpdate[] = $this->createDashboardPanel($dtoPanel->id, $dtoPanel);
}
}
}
return $this->panelsToUpdate;
}
/**
* @return array<int>
*/
public function getPanelIdsToDelete(): array
{
if ($this->panelIdsToDelete === null) {
$this->panelIdsToDelete = [];
$panelDtoIds = array_map(
static fn (PanelRequestDto $dtoPanel): ?int => $dtoPanel->id,
$this->panelsFromRequest
);
foreach ($this->panelIdsFromRepository as $id) {
if (! \in_array($id, $panelDtoIds, true)) {
$this->panelIdsToDelete[] = $id;
}
}
}
return $this->panelIdsToDelete;
}
/**
* @param PanelRequestDto $dtoPanel
*
* @throws AssertionFailedException
*
* @return NewDashboardPanel
*/
private function createNewDashboardPanel(PanelRequestDto $dtoPanel): NewDashboardPanel
{
$panel = new NewDashboardPanel($dtoPanel->name, $dtoPanel->widgetType);
$panel->setWidgetSettings($dtoPanel->widgetSettings);
$panel->setLayoutX($dtoPanel->layout->posX);
$panel->setLayoutY($dtoPanel->layout->posY);
$panel->setLayoutWidth($dtoPanel->layout->width);
$panel->setLayoutHeight($dtoPanel->layout->height);
$panel->setLayoutMinWidth($dtoPanel->layout->minWidth);
$panel->setLayoutMinHeight($dtoPanel->layout->minHeight);
return $panel;
}
/**
* @param int $id
* @param PanelRequestDto $dtoPanel
*
* @throws AssertionFailedException
*
* @return DashboardPanel
*/
private function createDashboardPanel(int $id, PanelRequestDto $dtoPanel): DashboardPanel
{
return new DashboardPanel(
id: $id,
name: $dtoPanel->name,
widgetType: $dtoPanel->widgetType,
widgetSettings: $dtoPanel->widgetSettings,
layoutX: $dtoPanel->layout->posX,
layoutY: $dtoPanel->layout->posY,
layoutWidth: $dtoPanel->layout->width,
layoutHeight: $dtoPanel->layout->height,
layoutMinWidth: $dtoPanel->layout->minWidth,
layoutMinHeight: $dtoPanel->layout->minHeight
);
}
}
| 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/Application/UseCase/PartialUpdateDashboard/PartialUpdateDashboardRequest.php | centreon/src/Core/Dashboard/Application/UseCase/PartialUpdateDashboard/PartialUpdateDashboardRequest.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\Application\UseCase\PartialUpdateDashboard;
use Core\Common\Application\Type\NoValue;
use Core\Dashboard\Application\UseCase\PartialUpdateDashboard\Request\PanelRequestDto;
use Core\Dashboard\Application\UseCase\PartialUpdateDashboard\Request\RefreshRequestDto;
use Core\Dashboard\Application\UseCase\PartialUpdateDashboard\Request\ThumbnailRequestDto;
final class PartialUpdateDashboardRequest
{
/**
* @param NoValue|string $name
* @param NoValue|string $description
* @param NoValue|array<PanelRequestDto> $panels
* @param NoValue|RefreshRequestDto $refresh
* @param NoValue|ThumbnailRequestDto $thumbnail
*/
public function __construct(
public NoValue|string $name = new NoValue(),
public NoValue|string $description = new NoValue(),
public NoValue|array $panels = new NoValue(),
public NoValue|RefreshRequestDto $refresh = new NoValue(),
public NoValue|ThumbnailRequestDto $thumbnail = 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/Dashboard/Application/UseCase/PartialUpdateDashboard/PartialUpdateDashboardPresenterInterface.php | centreon/src/Core/Dashboard/Application/UseCase/PartialUpdateDashboard/PartialUpdateDashboardPresenterInterface.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\Application\UseCase\PartialUpdateDashboard;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface PartialUpdateDashboardPresenterInterface
{
public function presentResponse(NoContentResponse|ResponseStatusInterface $data): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Application/UseCase/PartialUpdateDashboard/Request/PanelLayoutRequestDto.php | centreon/src/Core/Dashboard/Application/UseCase/PartialUpdateDashboard/Request/PanelLayoutRequestDto.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\Application\UseCase\PartialUpdateDashboard\Request;
final class PanelLayoutRequestDto
{
public function __construct(
public int $posX = 0,
public int $posY = 0,
public int $width = 0,
public int $height = 0,
public int $minWidth = 0,
public int $minHeight = 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/Dashboard/Application/UseCase/PartialUpdateDashboard/Request/PanelRequestDto.php | centreon/src/Core/Dashboard/Application/UseCase/PartialUpdateDashboard/Request/PanelRequestDto.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\Application\UseCase\PartialUpdateDashboard\Request;
final class PanelRequestDto
{
/**
* @param int|null $id
* @param string $name
* @param PanelLayoutRequestDto $layout
* @param string $widgetType
* @param array<mixed> $widgetSettings
*/
public function __construct(
public ?int $id = null,
public string $name = '',
public PanelLayoutRequestDto $layout = new PanelLayoutRequestDto(),
public string $widgetType = '',
public array $widgetSettings = [],
) {
}
}
| 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/Application/UseCase/PartialUpdateDashboard/Request/ThumbnailRequestDto.php | centreon/src/Core/Dashboard/Application/UseCase/PartialUpdateDashboard/Request/ThumbnailRequestDto.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\Application\UseCase\PartialUpdateDashboard\Request;
final class ThumbnailRequestDto
{
public string $content;
public function __construct(
public ?int $id,
public string $directory,
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/Dashboard/Application/UseCase/PartialUpdateDashboard/Request/RefreshRequestDto.php | centreon/src/Core/Dashboard/Application/UseCase/PartialUpdateDashboard/Request/RefreshRequestDto.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\Application\UseCase\PartialUpdateDashboard\Request;
use Core\Dashboard\Domain\Model\Refresh\RefreshType;
final class RefreshRequestDto
{
public function __construct(
public RefreshType $refreshType = RefreshType::Global,
public ?int $refreshInterval = 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/Application/UseCase/FindDashboard/FindDashboardFactory.php | centreon/src/Core/Dashboard/Application/UseCase/FindDashboard/FindDashboardFactory.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\Application\UseCase\FindDashboard;
use Core\Dashboard\Application\UseCase\FindDashboard\Response\{PanelResponseDto, RefreshResponseDto, ThumbnailResponseDto, UserResponseDto};
use Core\Dashboard\Domain\Model\Dashboard;
use Core\Dashboard\Domain\Model\DashboardPanel;
use Core\Dashboard\Domain\Model\Role\DashboardSharingRole;
use Core\Dashboard\Domain\Model\Share\DashboardContactGroupShare;
use Core\Dashboard\Domain\Model\Share\DashboardContactShare;
use Core\Dashboard\Domain\Model\Share\DashboardSharingRoles;
final class FindDashboardFactory
{
/**
* @param Dashboard $dashboard
* @param array<int, array{id: int, name: string}> $contactNames
* @param array<DashboardPanel> $panels
* @param DashboardSharingRoles $sharingRoles
* @param array<int, array<DashboardContactShare>> $contactShares
* @param array<int, array<DashboardContactGroupShare>> $contactGroupShares
* @param DashboardSharingRole $defaultRole
*
* @return FindDashboardResponse
*/
public static function createResponse(
Dashboard $dashboard,
array $contactNames,
array $panels,
DashboardSharingRoles $sharingRoles,
array $contactShares,
array $contactGroupShares,
DashboardSharingRole $defaultRole,
): FindDashboardResponse {
$ownRole = $defaultRole->getTheMostPermissiveOfBoth($sharingRoles->getTheMostPermissiveRole());
$response = new FindDashboardResponse();
$response->id = $dashboard->getId();
$response->name = $dashboard->getName();
$response->description = $dashboard->getDescription();
$response->createdAt = $dashboard->getCreatedAt();
$response->updatedAt = $dashboard->getUpdatedAt();
$response->ownRole = $ownRole;
if (null !== ($contactId = $dashboard->getCreatedBy())) {
$response->createdBy = new UserResponseDto();
$response->createdBy->id = $contactId;
$response->createdBy->name = $contactNames[$contactId]['name'] ?? '';
}
if (null !== ($contactId = $dashboard->getUpdatedBy())) {
$response->updatedBy = new UserResponseDto();
$response->updatedBy->id = $contactId;
$response->updatedBy->name = $contactNames[$contactId]['name'] ?? '';
}
// Add shares only if the user if editor, as the viewers should not be able to see shares.
if ($ownRole === DashboardSharingRole::Editor && array_key_exists($dashboard->getId(), $contactShares)) {
$response->shares['contacts'] = array_map(
static fn (DashboardContactShare $contactShare): array => [
'id' => $contactShare->getContactId(),
'name' => $contactShare->getContactName(),
'email' => $contactShare->getContactEmail(),
'role' => $contactShare->getRole(),
],
$contactShares[$dashboard->getId()]
);
}
if ($ownRole === DashboardSharingRole::Editor && array_key_exists($dashboard->getId(), $contactGroupShares)) {
$response->shares['contact_groups'] = array_map(
static fn (DashboardContactGroupShare $contactGroupShare): array => [
'id' => $contactGroupShare->getContactGroupId(),
'name' => $contactGroupShare->getContactGroupName(),
'role' => $contactGroupShare->getRole(),
],
$contactGroupShares[$dashboard->getId()]
);
}
$response->panels = array_map(self::dashboardPanelToDto(...), $panels);
$response->refresh = new RefreshResponseDto();
$response->refresh->refreshType = $dashboard->getRefresh()->getRefreshType();
$response->refresh->refreshInterval = $dashboard->getRefresh()->getRefreshInterval();
if ($dashboard->getThumbnail() !== null) {
$response->thumbnail = new ThumbnailResponseDto(
$dashboard->getThumbnail()->getId(),
$dashboard->getThumbnail()->getFilename(),
$dashboard->getThumbnail()->getDirectory()
);
}
return $response;
}
private static function dashboardPanelToDto(DashboardPanel $panel): PanelResponseDto
{
$dto = new PanelResponseDto();
$dto->id = $panel->getId();
$dto->name = $panel->getName();
$dto->widgetType = $panel->getWidgetType();
$dto->layout->posX = $panel->getLayoutX();
$dto->layout->posY = $panel->getLayoutY();
$dto->layout->width = $panel->getLayoutWidth();
$dto->layout->height = $panel->getLayoutHeight();
$dto->layout->minWidth = $panel->getLayoutMinWidth();
$dto->layout->minHeight = $panel->getLayoutMinHeight();
$dto->widgetSettings = $panel->getWidgetSettings();
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/Dashboard/Application/UseCase/FindDashboard/FindDashboardResponse.php | centreon/src/Core/Dashboard/Application/UseCase/FindDashboard/FindDashboardResponse.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\Application\UseCase\FindDashboard;
use Core\Dashboard\Application\UseCase\FindDashboard\Response\{PanelResponseDto, RefreshResponseDto, ThumbnailResponseDto, UserResponseDto};
use Core\Dashboard\Domain\Model\Role\DashboardSharingRole;
final class FindDashboardResponse
{
public int $id = 0;
public string $name = '';
public ?string $description = null;
public ?UserResponseDto $createdBy = null;
public ?UserResponseDto $updatedBy = null;
public \DateTimeImmutable $createdAt;
public \DateTimeImmutable $updatedAt;
/** @var array<PanelResponseDto> */
public array $panels = [];
public DashboardSharingRole $ownRole = DashboardSharingRole::Viewer;
public RefreshResponseDto $refresh;
public ?ThumbnailResponseDto $thumbnail = null;
/**
* @var array{
* contacts: array<array{
* id: int,
* name: string,
* email: string,
* role: DashboardSharingRole
* }>,
* contact_groups: array<array{
* id: int,
* name: string,
* role: DashboardSharingRole
* }>
* }
*/
public array $shares = ['contacts' => [], 'contact_groups' => []];
public bool $isFavorite = false;
public function __construct()
{
$this->createdAt = new \DateTimeImmutable();
$this->updatedAt = new \DateTimeImmutable();
$this->refresh = new RefreshResponseDto();
}
}
| 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/Application/UseCase/FindDashboard/FindDashboardPresenterInterface.php | centreon/src/Core/Dashboard/Application/UseCase/FindDashboard/FindDashboardPresenterInterface.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\Application\UseCase\FindDashboard;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface FindDashboardPresenterInterface
{
public function presentResponse(FindDashboardResponse|ResponseStatusInterface $data): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Application/UseCase/FindDashboard/FindDashboard.php | centreon/src/Core/Dashboard/Application/UseCase/FindDashboard/FindDashboard.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\Application\UseCase\FindDashboard;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Contact\Application\Repository\ReadContactRepositoryInterface;
use Core\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\Repository\ReadDashboardPanelRepositoryInterface;
use Core\Dashboard\Application\Repository\ReadDashboardRepositoryInterface;
use Core\Dashboard\Application\Repository\ReadDashboardShareRepositoryInterface;
use Core\Dashboard\Domain\Model\Dashboard;
use Core\Dashboard\Domain\Model\DashboardRights;
use Core\Dashboard\Domain\Model\Role\DashboardSharingRole;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Core\UserProfile\Application\Repository\ReadUserProfileRepositoryInterface;
final class FindDashboard
{
use LoggerTrait;
public const AUTHORIZED_ACL_GROUPS = ['customer_admin_acl'];
public function __construct(
private readonly ReadDashboardRepositoryInterface $readDashboardRepository,
private readonly ReadDashboardPanelRepositoryInterface $readDashboardPanelRepository,
private readonly ReadDashboardShareRepositoryInterface $readDashboardShareRepository,
private readonly ReadContactRepositoryInterface $readContactRepository,
private readonly DashboardRights $rights,
private readonly ContactInterface $contact,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly ReadUserProfileRepositoryInterface $userProfileReader,
private readonly bool $isCloudPlatform,
) {
}
/**
* @param int $dashboardId
* @param FindDashboardPresenterInterface $presenter
*/
public function __invoke(int $dashboardId, FindDashboardPresenterInterface $presenter): void
{
try {
$response = $this->isUserAdmin() ? $this->findDashboardAsAdmin($dashboardId) : $this->findDashboardAsViewer($dashboardId);
if ($response instanceof NotFoundResponse) {
$this->warning('Dashboard (%s) not found', ['id' => $dashboardId]);
$presenter->presentResponse($response);
return;
}
$this->info('Find dashboard', ['id' => $dashboardId]);
$profile = $this->userProfileReader->findByContact($this->contact);
$response->isFavorite = in_array($dashboardId, $profile !== null ? $profile->getFavoriteDashboards() : [], true);
$presenter->presentResponse($response);
} catch (\Throwable $ex) {
$presenter->presentResponse(new ErrorResponse(DashboardException::errorWhileRetrieving()));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
}
}
/**
* @param int $dashboardId
*
* @throws \Throwable
*
* @return FindDashboardResponse|NotFoundResponse
*/
private function findDashboardAsAdmin(int $dashboardId): FindDashboardResponse|NotFoundResponse
{
$dashboard = $this->readDashboardRepository->findOne($dashboardId);
if ($dashboard === null) {
return new NotFoundResponse('Dashboard');
}
$dashboard->setThumbnail(
$this->readDashboardRepository->findThumbnailByDashboardId($dashboard->getId()),
);
return $this->createResponse($dashboard, DashboardSharingRole::Editor);
}
/**
* @param int $dashboardId
*
* @throws \Throwable
*
* @return FindDashboardResponse|NotFoundResponse
*/
private function findDashboardAsViewer(int $dashboardId): FindDashboardResponse|NotFoundResponse
{
$dashboard = $this->readDashboardRepository->findOneByContact($dashboardId, $this->contact);
if ($dashboard === null) {
return new NotFoundResponse('Dashboard');
}
$dashboard->setThumbnail(
$this->readDashboardRepository->findThumbnailByDashboardId($dashboard->getId()),
);
return $this->createResponseAsNonAdmin($dashboard, DashboardSharingRole::Viewer);
}
/**
* @param Dashboard $dashboard
* @param DashboardSharingRole $defaultRole
*
* @throws \Throwable
*
* @return FindDashboardResponse
*/
private function createResponse(Dashboard $dashboard, DashboardSharingRole $defaultRole): FindDashboardResponse
{
$contactIds = $this->extractAllContactIdsFromDashboard($dashboard);
return FindDashboardFactory::createResponse(
$dashboard,
$this->readContactRepository->findNamesByIds(...$contactIds),
$this->readDashboardPanelRepository->findPanelsByDashboardId($dashboard->getId()),
$this->readDashboardShareRepository->getOneSharingRoles($this->contact, $dashboard),
$this->readDashboardShareRepository->findDashboardsContactShares($dashboard),
$this->readDashboardShareRepository->findDashboardsContactGroupShares($dashboard),
$defaultRole
);
}
/**
* @param Dashboard $dashboard
* @param DashboardSharingRole $defaultRole
*
* @throws \Throwable
*
* @return FindDashboardResponse
*/
private function createResponseAsNonAdmin(Dashboard $dashboard, DashboardSharingRole $defaultRole): FindDashboardResponse
{
$editorIds = $this->extractAllContactIdsFromDashboard($dashboard);
$userAccessGroups = $this->readAccessGroupRepository->findByContact($this->contact);
$accessGroupsIds = array_map(
static fn (AccessGroup $accessGroup): int => $accessGroup->getId(),
$userAccessGroups
);
$userInCurrentUserAccessGroups = $this->readContactRepository->findContactIdsByAccessGroups($accessGroupsIds);
return FindDashboardFactory::createResponse(
$dashboard,
$this->readContactRepository->findNamesByIds(...$editorIds),
$this->readDashboardPanelRepository->findPanelsByDashboardId($dashboard->getId()),
$this->readDashboardShareRepository->getOneSharingRoles($this->contact, $dashboard),
$this->readDashboardShareRepository->findDashboardsContactSharesByContactIds(
$userInCurrentUserAccessGroups,
$dashboard
),
$this->readDashboardShareRepository->findDashboardsContactGroupSharesByContact(
$this->contact,
$dashboard
),
$defaultRole
);
}
/**
* @param Dashboard $dashboard
*
* @return int[]
*/
private function extractAllContactIdsFromDashboard(Dashboard $dashboard): array
{
$contactIds = [];
if ($id = $dashboard->getCreatedBy()) {
$contactIds[] = $id;
}
if ($id = $dashboard->getUpdatedBy()) {
$contactIds[] = $id;
}
return $contactIds;
}
/**
* @throws \Throwable
*
* @return bool
*/
private function isUserAdmin(): bool
{
if ($this->rights->hasAdminRole()) {
return true;
}
$userAccessGroupNames = array_map(
static fn (AccessGroup $accessGroup): string => $accessGroup->getName(),
$this->readAccessGroupRepository->findByContact($this->contact)
);
return ! (empty(array_intersect($userAccessGroupNames, self::AUTHORIZED_ACL_GROUPS)))
&& $this->isCloudPlatform;
}
}
| 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/Application/UseCase/FindDashboard/Response/PanelLayoutResponseDto.php | centreon/src/Core/Dashboard/Application/UseCase/FindDashboard/Response/PanelLayoutResponseDto.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\Application\UseCase\FindDashboard\Response;
final class PanelLayoutResponseDto
{
public function __construct(
public int $posX = 0,
public int $posY = 0,
public int $width = 0,
public int $height = 0,
public int $minWidth = 0,
public int $minHeight = 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/Dashboard/Application/UseCase/FindDashboard/Response/ThumbnailResponseDto.php | centreon/src/Core/Dashboard/Application/UseCase/FindDashboard/Response/ThumbnailResponseDto.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\Application\UseCase\FindDashboard\Response;
final readonly class ThumbnailResponseDto
{
public function __construct(
public int $id = 0,
public string $name = '',
public string $directory = '',
) {
}
}
| 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/Application/UseCase/FindDashboard/Response/UserResponseDto.php | centreon/src/Core/Dashboard/Application/UseCase/FindDashboard/Response/UserResponseDto.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\Application\UseCase\FindDashboard\Response;
final class UserResponseDto
{
public function __construct(
public int $id = 0,
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/Dashboard/Application/UseCase/FindDashboard/Response/RefreshResponseDto.php | centreon/src/Core/Dashboard/Application/UseCase/FindDashboard/Response/RefreshResponseDto.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\Application\UseCase\FindDashboard\Response;
use Core\Dashboard\Domain\Model\Refresh\RefreshType;
final class RefreshResponseDto
{
public RefreshType $refreshType = RefreshType::Global;
public ?int $refreshInterval = 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/Application/UseCase/FindDashboard/Response/PanelResponseDto.php | centreon/src/Core/Dashboard/Application/UseCase/FindDashboard/Response/PanelResponseDto.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\Application\UseCase\FindDashboard\Response;
final class PanelResponseDto
{
/**
* @param int $id
* @param string $name
* @param PanelLayoutResponseDto $layout
* @param string $widgetType
* @param array<mixed> $widgetSettings
*/
public function __construct(
public int $id = 0,
public string $name = '',
public PanelLayoutResponseDto $layout = new PanelLayoutResponseDto(),
public string $widgetType = '',
public array $widgetSettings = [],
) {
}
}
| 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/Application/UseCase/DeleteDashboard/DeleteDashboardPresenterInterface.php | centreon/src/Core/Dashboard/Application/UseCase/DeleteDashboard/DeleteDashboardPresenterInterface.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\Application\UseCase\DeleteDashboard;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface DeleteDashboardPresenterInterface
{
public function presentResponse(NoContentResponse|ResponseStatusInterface $data): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Application/UseCase/DeleteDashboard/DeleteDashboard.php | centreon/src/Core/Dashboard/Application/UseCase/DeleteDashboard/DeleteDashboard.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\Application\UseCase\DeleteDashboard;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\Repository\ReadDashboardRepositoryInterface;
use Core\Dashboard\Application\Repository\ReadDashboardShareRepositoryInterface;
use Core\Dashboard\Application\Repository\WriteDashboardRepositoryInterface;
use Core\Dashboard\Domain\Model\DashboardRights;
use Core\Media\Application\Repository\WriteMediaRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Throwable;
final class DeleteDashboard
{
use LoggerTrait;
public const AUTHORIZED_ACL_GROUPS = ['customer_admin_acl'];
public function __construct(
private readonly ReadDashboardRepositoryInterface $readDashboardRepository,
private readonly WriteDashboardRepositoryInterface $writeDashboardRepository,
private readonly ReadDashboardShareRepositoryInterface $readDashboardShareRepository,
private readonly DashboardRights $rights,
private readonly ContactInterface $contact,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly WriteMediaRepositoryInterface $mediaRepository,
private readonly bool $isCloudPlatform,
) {
}
public function __invoke(int $dashboardId, DeleteDashboardPresenterInterface $presenter): void
{
try {
if ($this->isUserAdmin()) {
$presenter->presentResponse($this->deleteDashboardAsAdmin($dashboardId));
} elseif ($this->rights->canCreate()) {
$presenter->presentResponse($this->deleteDashboardAsContact($dashboardId));
} else {
$this->error(
"User doesn't have sufficient rights to see dashboards",
['user_id' => $this->contact->getId()]
);
$presenter->presentResponse(
new ForbiddenResponse(DashboardException::accessNotAllowedForWriting())
);
}
} catch (Throwable $ex) {
$presenter->presentResponse(new ErrorResponse(DashboardException::errorWhileDeleting()));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
}
}
/**
* @param int $dashboardId
*
* @throws Throwable
*
* @return ResponseStatusInterface
*/
private function deleteDashboardAsAdmin(int $dashboardId): ResponseStatusInterface
{
if ($this->readDashboardRepository->existsOne($dashboardId)) {
if (($thumbail = $this->readDashboardRepository->findThumbnailByDashboardId($dashboardId)) !== null) {
$this->mediaRepository->delete($thumbail);
}
$this->writeDashboardRepository->delete($dashboardId);
return new NoContentResponse();
}
$this->warning('Dashboard (%s) not found', ['id' => $dashboardId]);
return new NotFoundResponse('Dashboard');
}
/**
* @param int $dashboardId
*
* @throws Throwable
*
* @return ResponseStatusInterface
*/
private function deleteDashboardAsContact(int $dashboardId): ResponseStatusInterface
{
$dashboard = $this->readDashboardRepository->findOneByContact($dashboardId, $this->contact);
if ($dashboard === null) {
$this->warning('Dashboard (%s) not found', ['id' => $dashboardId]);
return new NotFoundResponse('Dashboard');
}
$sharingRoles = $this->readDashboardShareRepository->getOneSharingRoles($this->contact, $dashboard);
if (! $this->rights->canDelete($sharingRoles)) {
return new ForbiddenResponse(DashboardException::dashboardAccessRightsNotAllowedForWriting($dashboardId));
}
if (($thumbail = $this->readDashboardRepository->findThumbnailByDashboardId($dashboardId)) !== null) {
$this->mediaRepository->delete($thumbail);
}
$this->writeDashboardRepository->delete($dashboardId);
return new NoContentResponse();
}
/**
* @throws Throwable
*
* @return bool
*/
private function isUserAdmin(): bool
{
if ($this->rights->hasAdminRole()) {
return true;
}
$userAccessGroupNames = array_map(
static fn (AccessGroup $accessGroup): string => $accessGroup->getName(),
$this->readAccessGroupRepository->findByContact($this->contact)
);
return ! (empty(array_intersect($userAccessGroupNames, self::AUTHORIZED_ACL_GROUPS)))
&& $this->isCloudPlatform;
}
}
| 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/Application/Exception/DashboardException.php | centreon/src/Core/Dashboard/Application/Exception/DashboardException.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\Application\Exception;
class DashboardException extends \Exception
{
public const CODE_NOT_FOUND = 1;
public const CODE_FORBIDDEN = 2;
public const CODE_CONFLICT = 3;
/**
* @return self
*/
public static function errorWhileSearching(): self
{
return new self(_('Error while searching for dashboards'));
}
/**
* @return self
*/
public static function errorWhileSearchingFavorites(): self
{
return new self(_('Error while searching for user favorite dashboards'));
}
/**
* @return self
*/
public static function accessNotAllowed(): self
{
return new self(_('You are not allowed to access dashboards'));
}
/**
* @return self
*/
public static function accessNotAllowedForWriting(): self
{
return new self(_('You are not allowed to perform write operations on dashboards'));
}
/**
* @param int $dashboardId
*
* @return self
*/
public static function dashboardAccessRightsNotAllowed(int $dashboardId): self
{
return new self(
sprintf(
_('You cannot view access rights on the dashboard #%d'),
$dashboardId
)
);
}
/**
* @param int $dashboardId
*
* @return self
*/
public static function dashboardAccessRightsNotAllowedForWriting(int $dashboardId): self
{
return new self(
sprintf(
_('You are not allowed to edit access rights on the dashboard #%d'),
$dashboardId
),
self::CODE_FORBIDDEN
);
}
/**
* @return self
*/
public static function errorWhileAdding(): self
{
return new self(_('Error while adding a dashboard'));
}
/**
* @return self
*/
public static function errorWhileRetrievingJustCreated(): self
{
return new self(_('Error while retrieving newly created dashboard'));
}
/**
* @return self
*/
public static function errorWhileRetrieving(): self
{
return new self(_('Error while retrieving a dashboard'));
}
/**
* @return self
*/
public static function errorWhileSearchingSharableContacts(): self
{
return new self(_('Error while retrieving contacts allowed to receive a dashboard share'));
}
/**
* @return self
*/
public static function errorWhileSearchingSharableContactGroups(): self
{
return new self(_('Error while retrieving contact groups allowed to receive a dashboard share'));
}
/**
* @return self
*/
public static function errorWhileDeleting(): self
{
return new self(_('Error while deleting a dashboard'));
}
/**
* @return self
*/
public static function errorWhileUpdating(): self
{
return new self(_('Error while updating a dashboard'));
}
/**
* @return self
*/
public static function errorWhileUpdatingDashboardShare(): self
{
return new self(_('Error while updating the dashboard share'));
}
/**
* @return self
*/
public static function errorWhileThumbnailToDashboard(): self
{
return new self(_('Error while linking a dashboard to its thumbnail'));
}
/**
* @return self
*/
public static function errorTryingToUpdateAPanelWhichDoesNotBelongsToTheDashboard(): self
{
return new self(_('Error while trying to update a widget which belongs to another dashboard'));
}
/**
* @param int $dashboardId
*
* @return self
*/
public static function theDashboardDoesNotExist(int $dashboardId): self
{
return new self(sprintf(_('The dashboard [%d] does not exist'), $dashboardId), self::CODE_NOT_FOUND);
}
/**
* @param int $dashboardId
*
* @return self
*/
public static function dashboardAlreadySetAsFavorite(int $dashboardId): self
{
return new self(sprintf(_('The dashboard [%d] is already set as favorite'), $dashboardId), self::CODE_CONFLICT);
}
/**
* @param int[] $contactIds
*
* @return self
*/
public static function theContactsDoNotExist(array $contactIds): self
{
return new self(sprintf(_('The contacts [%s] do not exist'), implode(', ', $contactIds)));
}
/**
* @param int[] $contactGroupIds
*
* @return self
*/
public static function theContactGroupsDoNotExist(array $contactGroupIds): self
{
return new self(sprintf(_('The contact groups [%s] do not exist'), implode(', ', $contactGroupIds)));
}
/**
* @param int[] $contactIds
*
* @return self
*/
public static function theContactsDoesNotHaveDashboardAccessRights(array $contactIds): self
{
return new self(
sprintf(_('The contacts [%s] do not have any dashboard Access rights'), implode(', ', $contactIds))
);
}
/**
* @param int[] $contactGroupIds
*
* @return self
*/
public static function theContactGroupsDoesNotHaveDashboardAccessRights(array $contactGroupIds): self
{
return new self(
sprintf(
_('The contact groups [%s] do not have any dashboard Access rights'),
implode(', ', $contactGroupIds)
)
);
}
/**
* @return self
*/
public static function contactForShareShouldBeUnique(): self
{
return new self(_('You cannot share the same dashboard to a contact several times'));
}
/**
* @return self
*/
public static function contactGroupForShareShouldBeUnique(): self
{
return new self(_('You cannot share the same dashboard to a contact group several times'));
}
public static function notSufficientAccessRightForUser(string $contactName, string $role): self
{
return new self(sprintf(_('No sufficient access rights to user [%s] to give role [%s]'), $contactName, $role));
}
public static function notSufficientAccessRightForContactGroup(string $contactGroupName, string $role): self
{
return new self(
sprintf(_('No sufficient access rights to contact group [%s] to give role [%s]'), $contactGroupName, $role)
);
}
/**
* @param int[] $contactIds
*
* @return self
*/
public static function userAreNotInAccessGroups(array $contactIds): self
{
return new self(sprintf(
_('The users [%s] are not in your access groups'),
implode(', ', $contactIds)
));
}
/**
* @param int[] $contactIds
*
* @return self
*/
public static function userAreNotInContactGroups(array $contactIds): self
{
return new self(sprintf(
_('The users [%s] are not in your contact groups'),
implode(', ', $contactIds)
));
}
/**
* @param int[] $contactGroupIds
*
* @return self
*/
public static function contactGroupIsNotInUserContactGroups(array $contactGroupIds): self
{
return new self(sprintf(
_('The contact groups [%s] are not in your contact groups'),
implode(', ', $contactGroupIds)
));
}
/**
* @param int $dashboardId
*
* @return self
*/
public static function thumbnailNotFound(int $dashboardId): self
{
return new self(sprintf(
_('The thumbnail provided for dashboard [%d] was not found'),
$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/Application/Repository/ReadDashboardPerformanceMetricRepositoryInterface.php | centreon/src/Core/Dashboard/Application/Repository/ReadDashboardPerformanceMetricRepositoryInterface.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\Application\Repository;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Dashboard\Domain\Model\Metric\ResourceMetric;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
interface ReadDashboardPerformanceMetricRepositoryInterface
{
/**
* Get metrics filtered by request parameters.
*
* @param RequestParametersInterface $requestParameters
*
* @throws RepositoryException
*
* @return ResourceMetric[]
*/
public function findByRequestParameters(RequestParametersInterface $requestParameters): array;
/**
* Get metrics filtered by request parameters and accessgroups.
*
* @param RequestParametersInterface $requestParameters
* @param AccessGroup[] $accessGroups
*
* @throws RepositoryException
*
* @return ResourceMetric[]
*/
public function findByRequestParametersAndAccessGroups(RequestParametersInterface $requestParameters, array $accessGroups): array;
/**
* Get metrics filtered by request parameters.
*
* @param RequestParametersInterface $requestParameters
* @param string $metricName
*
* @throws RepositoryException
*
* @return ResourceMetric[]
*/
public function findByRequestParametersAndMetricName(RequestParametersInterface $requestParameters, string $metricName): array;
/**
* Get metrics filtered by request parameters and accessgroups.
*
* @param RequestParametersInterface $requestParameters
* @param AccessGroup[] $accessGroups
* @param string $metricName
*
* @throws RepositoryException
*
* @return ResourceMetric[]
*/
public function findByRequestParametersAndAccessGroupsAndMetricName(RequestParametersInterface $requestParameters, array $accessGroups, string $metricName): 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/Dashboard/Application/Repository/WriteDashboardShareRepositoryInterface.php | centreon/src/Core/Dashboard/Application/Repository/WriteDashboardShareRepositoryInterface.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\Application\Repository;
use Core\Dashboard\Domain\Model\Role\DashboardSharingRole;
use Core\Dashboard\Domain\Model\Role\TinyRole;
interface WriteDashboardShareRepositoryInterface
{
/**
* Create the share relation between a dashboard and a contact.
*
* @param int $contactId
* @param int $dashboardId
* @param DashboardSharingRole $role
*
* @throws \Throwable
*/
public function upsertShareWithContact(int $contactId, int $dashboardId, DashboardSharingRole $role): void;
/**
* Create the share relation between a dashboard and a contact group.
*
* @param int $contactGroupId
* @param int $dashboardId
* @param DashboardSharingRole $role
*
* @throws \Throwable
*/
public function upsertShareWithContactGroup(int $contactGroupId, int $dashboardId, DashboardSharingRole $role): void;
/**
* Delete the share relation between a dashboard and a contact.
*
* @param int $contactId
* @param int $dashboardId
*
* @throws \Throwable
*
* @return bool
*/
public function deleteContactShare(int $contactId, int $dashboardId): bool;
/**
* Delete the share relation between a dashboard and a contact group.
*
* @param int $dashboardId
* @param int $contactGroupId
*
* @throws \Throwable
*
* @return bool
*/
public function deleteContactGroupShare(int $contactGroupId, int $dashboardId): bool;
/**
* Update the share relation between a dashboard and a contact.
*
* @param int $contactId
* @param int $dashboardId
* @param DashboardSharingRole $role
*
* @throws \Throwable
*
* @return bool
*/
public function updateContactShare(int $contactId, int $dashboardId, DashboardSharingRole $role): bool;
/**
* Update the share relation between a dashboard and a contact group.
*
* @param int $contactGroupId
* @param int $dashboardId
* @param DashboardSharingRole $role
*
* @throws \Throwable
*
* @return bool
*/
public function updateContactGroupShare(int $contactGroupId, int $dashboardId, DashboardSharingRole $role): bool;
/**
* Delete all the contact and contactgroups shared on a dashboard.
*
* @param int $dashboardId
*
* @throws \Throwable
*/
public function deleteDashboardShares(int $dashboardId): void;
/**
* Delete given contacts shared on a dashboard.
*
* @param int $dashboardId
* @param int[] $contactIds
*
* @throws \Throwable
*/
public function deleteDashboardSharesByContactIds(int $dashboardId, array $contactIds): void;
/**
* Delete given contact groups shared on a dashboard.
*
* @param int $dashboardId
* @param int[] $contactGroupIds
*
* @throws \Throwable
*/
public function deleteDashboardSharesByContactGroupIds(int $dashboardId, array $contactGroupIds): void;
/**
* Add multiple contact shares on a dashboard.
*
* @param int $dashboardId
* @param TinyRole[] $contactGroupRoles
*
* @throws \Throwable
*/
public function addDashboardContactGroupShares(int $dashboardId, array $contactGroupRoles): void;
/**
* Add multiple contact group shares on a dashboard.
*
* @param int $dashboardId
* @param TinyRole[] $contactRoles
*
* @throws \Throwable
*/
public function addDashboardContactShares(int $dashboardId, array $contactRoles): 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/Dashboard/Application/Repository/WidgetDataProviderInterface.php | centreon/src/Core/Dashboard/Application/Repository/WidgetDataProviderInterface.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\Application\Repository;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Dashboard\Domain\Model\DashboardPanel;
interface WidgetDataProviderInterface
{
/**
* @param string $widgetName
*
* @return bool
*/
public function isValidFor(string $widgetName): bool;
/**
* @param DashboardPanel $panel
* @param ContactInterface $user
*
* @throws \Throwable
*
* @return ResponseStatusInterface|mixed
*/
public function getData(DashboardPanel $panel, ContactInterface $user): mixed;
}
| 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/Application/Repository/ReadDashboardRepositoryInterface.php | centreon/src/Core/Dashboard/Application/Repository/ReadDashboardRepositoryInterface.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\Application\Repository;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Dashboard\Domain\Model\Dashboard;
use Core\Media\Domain\Model\Media;
interface ReadDashboardRepositoryInterface
{
/**
* Find all dashboards.
*
* @param RequestParametersInterface|null $requestParameters
*
* @throws \Throwable
*
* @return Dashboard[]
*/
public function findByRequestParameter(?RequestParametersInterface $requestParameters): array;
/**
* Find all dashboards by contact.
*
* @param RequestParametersInterface|null $requestParameters
* @param ContactInterface $contact
*
* @throws \Throwable
*
* @return Dashboard[]
*/
public function findByRequestParameterAndContact(
?RequestParametersInterface $requestParameters,
ContactInterface $contact,
): array;
/**
* Find dashboards by their ids.
*
* @param int[] $ids
*
* @throws \Throwable
*
* @return Dashboard[]
*/
public function findByIds(array $ids): array;
/**
* @param int[] $ids
* @param int $contactId
*
* @throws \Throwable
*
* @return Dashboard[]
*/
public function findByIdsAndContactId(array $ids, int $contactId): array;
/**
* Find one dashboard without acl.
*
* @param int $dashboardId
*
* @throws \Throwable
*
* @return Dashboard|null
*/
public function findOne(int $dashboardId): ?Dashboard;
/**
* Find one dashboard with the shared contact.
*
* @param int $dashboardId
* @param ContactInterface $contact
*
* @throws \Throwable
*
* @return Dashboard|null
*/
public function findOneByContact(int $dashboardId, ContactInterface $contact): ?Dashboard;
/**
* Tells whether the dashboard exists.
*
* @param int $dashboardId
*
* @throws \Throwable
*
* @return bool
*/
public function existsOne(int $dashboardId): bool;
/**
* Tells whether the dashboard exists but with the contact.
*
* @param int $dashboardId
* @param ContactInterface $contact
*
* @throws \Throwable
*
* @return bool
*/
public function existsOneByContact(int $dashboardId, ContactInterface $contact): bool;
/**
* @param int $dashboardId
*
* @throws \Throwable
*
* @return null|Media
*/
public function findThumbnailByDashboardId(int $dashboardId): ?Media;
/**
* @param int[] $dashboardIds
*
* @return array<int, Media>
*/
public function findThumbnailsByDashboardIds(array $dashboardIds): 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/Dashboard/Application/Repository/WriteDashboardPanelRepositoryInterface.php | centreon/src/Core/Dashboard/Application/Repository/WriteDashboardPanelRepositoryInterface.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\Application\Repository;
use Core\Dashboard\Domain\Model\DashboardPanel;
use Core\Dashboard\Domain\Model\NewDashboardPanel;
interface WriteDashboardPanelRepositoryInterface
{
/**
* Delete a panel from a dashboard.
*
* @param int $panelId
*/
public function deletePanel(int $panelId): void;
/**
* Add a new panel to a dashboard.
*
* @param int $dashboardId
* @param NewDashboardPanel $newPanel
*/
public function addPanel(int $dashboardId, NewDashboardPanel $newPanel): int;
/**
* Update a panel from a dashboard.
*
* @param int $dashboardId
* @param DashboardPanel $panel
*/
public function updatePanel(int $dashboardId, DashboardPanel $panel): 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/Dashboard/Application/Repository/WriteDashboardRepositoryInterface.php | centreon/src/Core/Dashboard/Application/Repository/WriteDashboardRepositoryInterface.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\Application\Repository;
use Core\Dashboard\Domain\Model\Dashboard;
use Core\Dashboard\Domain\Model\NewDashboard;
interface WriteDashboardRepositoryInterface
{
/**
* Add a dashboard.
*
* @param NewDashboard $newDashboard
*
* @throws \Throwable
*
* @return int
*/
public function add(NewDashboard $newDashboard): int;
/**
* Delete a dashboard.
*
* @param int $dashboardId
*
* @throws \Throwable
*/
public function delete(int $dashboardId): void;
/**
* Update a dashboard.
*
* @param Dashboard $dashboard
*
* @throws \Throwable
*/
public function update(Dashboard $dashboard): void;
/**
* @param int $dashboardId
* @param int $thumbnailId
*
* @throws \Throwable
*/
public function addThumbnailRelation(int $dashboardId, int $thumbnailId): 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/Dashboard/Application/Repository/ReadDashboardPanelRepositoryInterface.php | centreon/src/Core/Dashboard/Application/Repository/ReadDashboardPanelRepositoryInterface.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\Application\Repository;
use Core\Dashboard\Domain\Model\DashboardPanel;
interface ReadDashboardPanelRepositoryInterface
{
/**
* Find all panels IDs of a specific dashboard.
*
* @param int $dashboardId
*
* @throws \Throwable
*
* @return int[]
*/
public function findPanelIdsByDashboardId(int $dashboardId): array;
/**
* Find all panels of a specific dashboard.
*
* @param int $dashboardId
*
* @throws \Throwable
*
* @return DashboardPanel[]
*/
public function findPanelsByDashboardId(int $dashboardId): 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/Dashboard/Application/Repository/ReadDashboardShareRepositoryInterface.php | centreon/src/Core/Dashboard/Application/Repository/ReadDashboardShareRepositoryInterface.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\Application\Repository;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Repository\RepositoryException;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Contact\Domain\Model\ContactGroup;
use Core\Dashboard\Domain\Model\Dashboard;
use Core\Dashboard\Domain\Model\Role\DashboardContactGroupRole;
use Core\Dashboard\Domain\Model\Role\DashboardContactRole;
use Core\Dashboard\Domain\Model\Share\DashboardContactGroupShare;
use Core\Dashboard\Domain\Model\Share\DashboardContactShare;
use Core\Dashboard\Domain\Model\Share\DashboardSharingRoles;
/** @package Core\Dashboard\Application\Repository */
interface ReadDashboardShareRepositoryInterface
{
/**
* Find all contact shares of one dashboard.
*
* @param RequestParametersInterface $requestParameters
* @param Dashboard $dashboard
*
* @throws \Throwable
*
* @return DashboardContactShare[]
*/
public function findDashboardContactSharesByRequestParameter(
Dashboard $dashboard,
RequestParametersInterface $requestParameters,
): array;
/**
* Find all contact group shares of one dashboard.
*
* @param RequestParametersInterface $requestParameters
* @param Dashboard $dashboard
*
* @throws \Throwable
*
* @return DashboardContactGroupShare[]
*/
public function findDashboardContactGroupSharesByRequestParameter(
Dashboard $dashboard,
RequestParametersInterface $requestParameters,
): array;
/**
* Retrieve the sharing roles of a dashboard.
*
* @param Dashboard $dashboard
* @param ContactInterface $contact
*
* @throws \Throwable
*/
public function getOneSharingRoles(ContactInterface $contact, Dashboard $dashboard): DashboardSharingRoles;
/**
* Retrieve the sharing roles of several dashboards.
*
* @param Dashboard ...$dashboards
* @param ContactInterface $contact
*
* @throws \Throwable
*
* @return array<int, DashboardSharingRoles>
*/
public function getMultipleSharingRoles(ContactInterface $contact, Dashboard ...$dashboards): array;
/**
* Retrieve all the contacts shares for several dashboards.
*
* @param Dashboard ...$dashboards
*
* @throws \Throwable
*
* @return array<int, array<DashboardContactShare>>
*/
public function findDashboardsContactShares(Dashboard ...$dashboards): array;
/**
* Retrieve all the contacts shares for several dashboards based on contact IDs.
*
* @param int[] $contactIds
* @param Dashboard ...$dashboards
*
* @throws \Throwable
*
* @return array<int, array<DashboardContactShare>>
*/
public function findDashboardsContactSharesByContactIds(array $contactIds, Dashboard ...$dashboards): array;
/**
* Retrieve all the contact groups shares for several dashboards.
*
* @param Dashboard ...$dashboards
*
* @throws \Throwable
*
* @return array<int, array<DashboardContactGroupShare>>
*/
public function findDashboardsContactGroupShares(Dashboard ...$dashboards): array;
/**
* Retrieve the contact groups shares for several dashboards member of contact contactgroups.
*
* @param ContactInterface $contact
* @param Dashboard ...$dashboards
*
* @throws \Throwable
*
* @return array<int, array<DashboardContactGroupShare>>
*/
public function findDashboardsContactGroupSharesByContact(ContactInterface $contact, Dashboard ...$dashboards): array;
/**
* Find users with Topology ACLs on dashboards.
* For cloud case all users with Dashboard ACLS (cloud admins included).
* For on-premise case all users with Dashboard ACLS withouth admins (as admins does not have ACLs).
*
* @param RequestParametersInterface $requestParameters
*
* @throws \Throwable|\UnexpectedValueException
*
* @return DashboardContactRole[]
*/
public function findContactsWithAccessRightByRequestParameters(
RequestParametersInterface $requestParameters,
): array;
/**
* Find users with Topology ACLs on dashboards based on given contact IDs.
*
* @param int[] $contactIds
*
* @throws \Throwable|\UnexpectedValueException
*
* @return DashboardContactRole[]
*/
public function findContactsWithAccessRightByContactIds(array $contactIds): array;
/**
* Find users with Topology ACLs on dashboards by current user ACLs.
*
* @param RequestParametersInterface $requestParameters
* @param int[] $aclGroupIds
*
* @throws \Throwable|\UnexpectedValueException
*
* @return DashboardContactRole[]
*/
public function findContactsWithAccessRightByACLGroupsAndRequestParameters(
RequestParametersInterface $requestParameters,
array $aclGroupIds,
): array;
/**
* @param ContactGroup[] $contactGroups
* @param RequestParametersInterface $requestParameters
*
* @throws RepositoryException
* @return DashboardContactRole[]
*/
public function findContactsWithAccessRightsByContactGroupsAndRequestParameters(
array $contactGroups,
RequestParametersInterface $requestParameters,
): array;
/**
* Find contact groups with Topology ACLs on dashboards.
*
* @param RequestParametersInterface $requestParameters
*
* @throws \Throwable|\UnexpectedValueException
*
* @return DashboardContactGroupRole[]
*/
public function findContactGroupsWithAccessRightByRequestParameters(
RequestParametersInterface $requestParameters,
): array;
/**
* Find all contactgroups by requestParameters (all contactgroups will have the Viewer Role by default - cloud case).
*
* @param RequestParametersInterface $requestParameters
*
* @throws RepositoryException
*
* @return DashboardContactGroupRole[]
*/
public function findContactGroupsByRequestParameters(
RequestParametersInterface $requestParameters,
): array;
/**
* Find contact groups with Topology ACLs on dashboards based on given contact group IDs.
*
* @param int[] $contactGroupIds
*
* @throws \Throwable|\UnexpectedValueException
*
* @return DashboardContactGroupRole[]
*/
public function findContactGroupsWithAccessRightByContactGroupIds(array $contactGroupIds): array;
/**
* Find contact groups with Topology ACLs on dashboards by current user ACLs.
*
* @param RequestParametersInterface $requestParameters
* @param int $contactId
*
* @throws \Throwable|\UnexpectedValueException
*
* @return DashboardContactGroupRole[]
*/
public function findContactGroupsWithAccessRightByUserAndRequestParameters(
RequestParametersInterface $requestParameters,
int $contactId,
): array;
/**
* Find contact groups for current user.
*
* @param RequestParametersInterface $requestParameters
* @param int $contactId
*
* @throws RepositoryException
*
* @return DashboardContactGroupRole[]
*/
public function findContactGroupsByUserAndRequestParameters(
RequestParametersInterface $requestParameters,
int $contactId,
): array;
/**
* Check if a user is editor on a dashboard.
*
* @param int $dashboardId
* @param ContactInterface $contact
*
* @throws \Throwable
*
* @return bool
*/
public function existsAsEditor(int $dashboardId, ContactInterface $contact): bool;
}
| 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/Domain/Model/DashboardPanel.php | centreon/src/Core/Dashboard/Domain/Model/DashboardPanel.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\Domain\Model;
use Assert\AssertionFailedException;
use Core\Dashboard\Domain\Model\Validation\DashboardPanelValidationTrait;
class DashboardPanel
{
use DashboardPanelValidationTrait;
public const MAX_NAME_LENGTH = 200;
public const MAX_WIDGET_TYPE_LENGTH = 200;
public const MAX_WIDGET_SETTINGS_LENGTH = 65535;
public const MIN_SMALL_INTEGER = -32768;
public const MAX_SMALL_INTEGER = 32767;
private readonly string $name;
private readonly string $widgetType;
/**
* @param int $id
* @param string $name
* @param string $widgetType
* @param array<mixed> $widgetSettings
* @param int $layoutX
* @param int $layoutY
* @param int $layoutWidth
* @param int $layoutHeight
* @param int $layoutMinWidth
* @param int $layoutMinHeight
*
* @throws AssertionFailedException
*/
public function __construct(
private readonly int $id,
string $name,
string $widgetType,
private readonly array $widgetSettings,
private readonly int $layoutX,
private readonly int $layoutY,
private readonly int $layoutWidth,
private readonly int $layoutHeight,
private readonly int $layoutMinWidth,
private readonly int $layoutMinHeight,
) {
$this->name = trim($name);
$this->widgetType = trim($widgetType);
$this->ensureValidName($this->name);
$this->ensureValidWidgetType($this->widgetType);
$this->ensureValidWidgetSettings($this->widgetSettings);
$this->ensureValidSmallInteger($this->layoutX, 'layoutX');
$this->ensureValidSmallInteger($this->layoutY, 'layoutY');
$this->ensureValidSmallInteger($this->layoutWidth, 'layoutWidth');
$this->ensureValidSmallInteger($this->layoutHeight, 'layoutHeight');
$this->ensureValidSmallInteger($this->layoutMinWidth, 'layoutMinWidth');
$this->ensureValidSmallInteger($this->layoutMinHeight, 'layoutMinHeight');
}
public function getId(): int
{
return $this->id;
}
public function getName(): string
{
return $this->name;
}
public function getWidgetType(): string
{
return $this->widgetType;
}
/**
* @return array<mixed>
*/
public function getWidgetSettings(): array
{
return $this->widgetSettings;
}
public function getLayoutX(): int
{
return $this->layoutX;
}
public function getLayoutY(): int
{
return $this->layoutY;
}
public function getLayoutWidth(): int
{
return $this->layoutWidth;
}
public function getLayoutHeight(): int
{
return $this->layoutHeight;
}
public function getLayoutMinWidth(): int
{
return $this->layoutMinWidth;
}
public function getLayoutMinHeight(): int
{
return $this->layoutMinHeight;
}
}
| 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/Domain/Model/DashboardRights.php | centreon/src/Core/Dashboard/Domain/Model/DashboardRights.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\Domain\Model;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Dashboard\Domain\Model\Role\DashboardGlobalRole;
use Core\Dashboard\Domain\Model\Role\DashboardSharingRole;
use Core\Dashboard\Domain\Model\Share\DashboardSharingRoles;
class DashboardRights
{
public const AUTHORIZED_ACL_GROUP = 'customer_admin_acl';
private const ROLE_VIEWER = Contact::ROLE_HOME_DASHBOARD_VIEWER;
private const ROLE_CREATOR = Contact::ROLE_HOME_DASHBOARD_CREATOR;
private const ROLE_ADMIN = Contact::ROLE_HOME_DASHBOARD_ADMIN;
public function __construct(private readonly ContactInterface $contact)
{
}
public function canCreate(): bool
{
return $this->hasAdminRole() || $this->hasCreatorRole();
}
public function canAccess(): bool
{
return $this->hasViewerRole();
}
public function canDelete(DashboardSharingRoles $roles): bool
{
return $roles->getTheMostPermissiveRole() === DashboardSharingRole::Editor;
}
public function canUpdate(DashboardSharingRoles $roles): bool
{
return $roles->getTheMostPermissiveRole() === DashboardSharingRole::Editor;
}
public function canCreateShare(DashboardSharingRoles $roles): bool
{
return $roles->getTheMostPermissiveRole() === DashboardSharingRole::Editor;
}
public function canDeleteShare(DashboardSharingRoles $roles): bool
{
return $roles->getTheMostPermissiveRole() === DashboardSharingRole::Editor;
}
public function canUpdateShare(DashboardSharingRoles $roles): bool
{
return $roles->getTheMostPermissiveRole() === DashboardSharingRole::Editor;
}
public function canAccessShare(DashboardSharingRoles $roles): bool
{
return $roles->getTheMostPermissiveRole() !== null;
}
public function hasAdminRole(): bool
{
return $this->contact->hasTopologyRole(self::ROLE_ADMIN);
}
public function hasCreatorRole(): bool
{
return $this->contact->hasTopologyRole(self::ROLE_ADMIN)
|| $this->contact->hasTopologyRole(self::ROLE_CREATOR);
}
public function hasViewerRole(): bool
{
return $this->contact->hasTopologyRole(self::ROLE_ADMIN)
|| $this->contact->hasTopologyRole(self::ROLE_CREATOR)
|| $this->contact->hasTopologyRole(self::ROLE_VIEWER);
}
public function getGlobalRole(): ?DashboardGlobalRole
{
return match (true) {
$this->hasAdminRole() => DashboardGlobalRole::Administrator,
$this->hasCreatorRole() => DashboardGlobalRole::Creator,
$this->hasViewerRole() => DashboardGlobalRole::Viewer,
default => 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/Domain/Model/Dashboard.php | centreon/src/Core/Dashboard/Domain/Model/Dashboard.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\Domain\Model;
use Assert\AssertionFailedException;
use Core\Dashboard\Domain\Model\Validation\DashboardValidationTrait;
use Core\Media\Domain\Model\Media;
/**
* @immutable
*/
class Dashboard
{
use DashboardValidationTrait;
public const MAX_NAME_LENGTH = 200;
public const MAX_DESCRIPTION_LENGTH = 65535;
public const MIN_DESCRIPTION_LENGTH = 1;
protected ?string $description = null;
protected ?Media $thumbnail = null;
private string $name = '';
/**
* @param int $id
* @param string $name
* @param ?int $createdBy
* @param ?int $updatedBy
* @param \DateTimeImmutable $createdAt
* @param \DateTimeImmutable $updatedAt
* @param Refresh $refresh
*
* @throws AssertionFailedException
*/
public function __construct(
private readonly int $id,
string $name,
private readonly ?int $createdBy,
private readonly ?int $updatedBy,
private readonly \DateTimeImmutable $createdAt,
private readonly \DateTimeImmutable $updatedAt,
private readonly Refresh $refresh,
) {
$this->name = trim($name);
$this->ensureValidName($this->name);
$this->ensureNullablePositiveInt($this->createdBy, 'createdBy');
$this->ensureNullablePositiveInt($this->updatedBy, 'updatedBy');
}
public function getId(): int
{
return $this->id;
}
public function getCreatedBy(): ?int
{
return $this->createdBy;
}
public function getUpdatedBy(): ?int
{
return $this->updatedBy;
}
public function getCreatedAt(): \DateTimeImmutable
{
return $this->createdAt;
}
public function getUpdatedAt(): \DateTimeImmutable
{
return $this->updatedAt;
}
public function getName(): string
{
return $this->name;
}
public function getDescription(): ?string
{
return $this->description;
}
/**
* @param string|null $description
*
* @throws AssertionFailedException
*
* @return $this
*/
public function setDescription(?string $description): self
{
if (! is_string($description)) {
$this->description = $description;
} else {
$this->description = trim($description);
$this->ensureValidDescription($this->description);
}
return $this;
}
public function getRefresh(): Refresh
{
return $this->refresh;
}
/**
* @return null|Media
*/
public function getThumbnail(): ?Media
{
return $this->thumbnail;
}
/**
* @param null|Media $thumbnail
*
* @return self
*/
public function setThumbnail(?Media $thumbnail): self
{
$this->thumbnail = $thumbnail;
return $this;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Domain/Model/NewDashboard.php | centreon/src/Core/Dashboard/Domain/Model/NewDashboard.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\Domain\Model;
use Assert\AssertionFailedException;
use Core\Dashboard\Domain\Model\Validation\DashboardValidationTrait;
use Core\Media\Domain\Model\Media;
class NewDashboard
{
use DashboardValidationTrait;
protected string $name;
protected ?string $description = null;
protected \DateTimeImmutable $createdAt;
protected \DateTimeImmutable $updatedAt;
protected int $createdBy;
protected int $updatedBy;
protected ?Media $thumbnail = null;
/**
* @param string $name
* @param int $createdBy
* @param Refresh $refresh
*
* @throws AssertionFailedException
*/
public function __construct(string $name, int $createdBy, private readonly Refresh $refresh)
{
$this->setName($name);
$this->setCreatedBy($createdBy);
$this->setUpdatedBy($createdBy);
$this->createdAt = new \DateTimeImmutable();
$this->updatedAt = new \DateTimeImmutable();
}
public function getCreatedBy(): int
{
return $this->createdBy;
}
public function getUpdatedBy(): int
{
return $this->updatedBy;
}
public function getCreatedAt(): \DateTimeImmutable
{
return $this->createdAt;
}
public function getUpdatedAt(): \DateTimeImmutable
{
return $this->updatedAt;
}
public function getName(): string
{
return $this->name;
}
public function getDescription(): ?string
{
return $this->description;
}
/**
* @param string $name
*
* @throws AssertionFailedException
*/
public function setName(string $name): void
{
$this->name = trim($name);
$this->ensureValidName($this->name);
}
/**
* @param string|null $description
*
* @throws AssertionFailedException
*/
public function setDescription(?string $description): void
{
if (! is_string($description)) {
$this->description = $description;
return;
}
$this->description = trim($description);
$this->ensureValidDescription($this->description);
}
/**
* @param int $userId
*
* @throws AssertionFailedException
*/
public function setCreatedBy(int $userId): void
{
$this->createdBy = $userId;
$this->ensurePositiveInt($this->createdBy, 'createdBy');
}
/**
* @param int $userId
*
* @throws AssertionFailedException
*/
public function setUpdatedBy(int $userId): void
{
$this->updatedBy = $userId;
$this->ensurePositiveInt($this->updatedBy, 'updatedBy');
}
public function getRefresh(): Refresh
{
return $this->refresh;
}
/**
* @return null|Media
*/
public function getThumbnail(): ?Media
{
return $this->thumbnail;
}
/**
* @param null|Media $thumbnail
*/
public function setThumbnail(?Media $thumbnail): void
{
$this->thumbnail = $thumbnail;
}
}
| 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/Domain/Model/NewDashboardPanel.php | centreon/src/Core/Dashboard/Domain/Model/NewDashboardPanel.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\Domain\Model;
use Assert\AssertionFailedException;
use Core\Dashboard\Domain\Model\Validation\DashboardPanelValidationTrait;
class NewDashboardPanel
{
use DashboardPanelValidationTrait;
private string $name;
private string $widgetType;
/** @var array<mixed> */
private array $widgetSettings = [];
private int $layoutX = 0;
private int $layoutY = 0;
private int $layoutWidth = 0;
private int $layoutHeight = 0;
private int $layoutMinWidth = 0;
private int $layoutMinHeight = 0;
/**
* @param string $name
* @param string $widgetType
*
* @throws AssertionFailedException
*/
public function __construct(
string $name,
string $widgetType,
) {
$this->setName($name);
$this->setWidgetType($widgetType);
}
public function getName(): string
{
return $this->name;
}
public function getWidgetType(): string
{
return $this->widgetType;
}
/**
* @return array<mixed>
*/
public function getWidgetSettings(): array
{
return $this->widgetSettings;
}
public function getLayoutX(): int
{
return $this->layoutX;
}
public function getLayoutY(): int
{
return $this->layoutY;
}
public function getLayoutWidth(): int
{
return $this->layoutWidth;
}
public function getLayoutHeight(): int
{
return $this->layoutHeight;
}
public function getLayoutMinWidth(): int
{
return $this->layoutMinWidth;
}
public function getLayoutMinHeight(): int
{
return $this->layoutMinHeight;
}
/**
* @param string $name
*
* @throws AssertionFailedException
*/
public function setName(string $name): void
{
$this->name = trim($name);
$this->ensureValidName($this->name);
}
/**
* @param string $widgetType
*
* @throws AssertionFailedException
*/
public function setWidgetType(string $widgetType): void
{
$this->widgetType = trim($widgetType);
$this->ensureValidWidgetType($this->widgetType);
}
/**
* @param array<mixed> $widgetSettings
*
* @throws AssertionFailedException
*/
public function setWidgetSettings(array $widgetSettings): void
{
$this->widgetSettings = $widgetSettings;
$this->ensureValidWidgetSettings($this->widgetSettings);
}
/**
* @param int $layoutX
*
* @throws AssertionFailedException
*/
public function setLayoutX(int $layoutX): void
{
$this->layoutX = $layoutX;
$this->ensureValidSmallInteger($this->layoutX, 'layoutX');
}
/**
* @param int $layoutY
*
* @throws AssertionFailedException
*/
public function setLayoutY(int $layoutY): void
{
$this->layoutY = $layoutY;
$this->ensureValidSmallInteger($this->layoutY, 'layoutY');
}
/**
* @param int $layoutWidth
*
* @throws AssertionFailedException
*/
public function setLayoutWidth(int $layoutWidth): void
{
$this->layoutWidth = $layoutWidth;
$this->ensureValidSmallInteger($this->layoutWidth, 'layoutWidth');
}
/**
* @param int $layoutHeight
*
* @throws AssertionFailedException
*/
public function setLayoutHeight(int $layoutHeight): void
{
$this->layoutHeight = $layoutHeight;
$this->ensureValidSmallInteger($this->layoutHeight, 'layoutHeight');
}
/**
* @param int $layoutMinWidth
*
* @throws AssertionFailedException
*/
public function setLayoutMinWidth(int $layoutMinWidth): void
{
$this->layoutMinWidth = $layoutMinWidth;
$this->ensureValidSmallInteger($this->layoutMinWidth, 'layoutMinWidth');
}
/**
* @param int $layoutMinHeight
*
* @throws AssertionFailedException
*/
public function setLayoutMinHeight(int $layoutMinHeight): void
{
$this->layoutMinHeight = $layoutMinHeight;
$this->ensureValidSmallInteger($this->layoutMinHeight, 'layoutMinHeight');
}
}
| 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/Domain/Model/Refresh.php | centreon/src/Core/Dashboard/Domain/Model/Refresh.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\Domain\Model;
use Core\Dashboard\Domain\Model\Refresh\RefreshType;
class Refresh
{
/**
* @param RefreshType $refreshType
* @param int|null $refreshInterval
*/
public function __construct(
private readonly RefreshType $refreshType,
private readonly ?int $refreshInterval,
) {
}
/**
* @return RefreshType
*/
public function getRefreshType(): RefreshType
{
return $this->refreshType;
}
/**
* @return int|null
*/
public function getRefreshInterval(): ?int
{
return $this->refreshInterval;
}
}
| 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/Domain/Model/Refresh/RefreshType.php | centreon/src/Core/Dashboard/Domain/Model/Refresh/RefreshType.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\Domain\Model\Refresh;
enum RefreshType
{
case Global;
case Manual;
}
| 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/Domain/Model/Role/DashboardSharingRole.php | centreon/src/Core/Dashboard/Domain/Model/Role/DashboardSharingRole.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\Domain\Model\Role;
enum DashboardSharingRole
{
case Viewer;
case Editor;
/**
* Simple Role comparison to check the role which has the most permissions.
*
* @param DashboardSharingRole|null $role
*
* @return bool
*/
public function hasMorePermissionsThan(?self $role): bool
{
if ($role === null) {
return true;
}
return $this === self::Editor
&& $role === self::Viewer;
}
/**
* Helper to get the most permissive role between self and the argument.
*
* @param DashboardSharingRole|null $role
*
* @return self
*/
public function getTheMostPermissiveOfBoth(?self $role): self
{
if ($role === null) {
return $this;
}
return $this->hasMorePermissionsThan($role) ? $this : $role;
}
}
| 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/Domain/Model/Role/DashboardContactRole.php | centreon/src/Core/Dashboard/Domain/Model/Role/DashboardContactRole.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\Domain\Model\Role;
class DashboardContactRole
{
/**
* @param int $contactId
* @param string $contactName
* @param string $contactEmail
* @param DashboardGlobalRole[] $roles
*/
public function __construct(
private readonly int $contactId,
private readonly string $contactName,
private readonly string $contactEmail,
private readonly array $roles,
) {
}
public function getContactId(): int
{
return $this->contactId;
}
public function getContactName(): string
{
return $this->contactName;
}
public function getContactEmail(): string
{
return $this->contactEmail;
}
/**
* @return DashboardGlobalRole[]
*/
public function getRoles(): array
{
return $this->roles;
}
/**
* Compute the most permissive role,
* Administrator | Creator are most permissive than Viewer.
*
* @return DashboardGlobalRole
*/
public function getMostPermissiveRole(): DashboardGlobalRole
{
return in_array(DashboardGlobalRole::Administrator, $this->roles, true)
|| in_array(DashboardGlobalRole::Creator, $this->roles, true)
? DashboardGlobalRole::Creator
: DashboardGlobalRole::Viewer;
}
}
| 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/Domain/Model/Role/DashboardGlobalRole.php | centreon/src/Core/Dashboard/Domain/Model/Role/DashboardGlobalRole.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\Domain\Model\Role;
enum DashboardGlobalRole
{
case Viewer;
case Creator;
case Administrator;
}
| 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/Domain/Model/Role/TinyRole.php | centreon/src/Core/Dashboard/Domain/Model/Role/TinyRole.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\Domain\Model\Role;
class TinyRole
{
/**
* @param int $id ID of the contact/contactgroup
* @param DashboardSharingRole $role
*/
public function __construct(private readonly int $id, private readonly DashboardSharingRole $role)
{
}
public function getId(): int
{
return $this->id;
}
public function getRole(): DashboardSharingRole
{
return $this->role;
}
}
| 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/Domain/Model/Role/DashboardContactGroupRole.php | centreon/src/Core/Dashboard/Domain/Model/Role/DashboardContactGroupRole.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\Domain\Model\Role;
class DashboardContactGroupRole
{
/**
* @param int $contactGroupId
* @param string $contactGroupName
* @param DashboardGlobalRole[] $roles
*/
public function __construct(
private readonly int $contactGroupId,
private readonly string $contactGroupName,
private readonly array $roles,
) {
}
public function getContactGroupId(): int
{
return $this->contactGroupId;
}
public function getContactGroupName(): string
{
return $this->contactGroupName;
}
/**
* @return DashboardGlobalRole[]
*/
public function getRoles(): array
{
return $this->roles;
}
/**
* Compute the most permissive role,
* Administrator | Creator are most permissive than Viewer.
*
* @return DashboardGlobalRole
*/
public function getMostPermissiveRole(): DashboardGlobalRole
{
return in_array(DashboardGlobalRole::Administrator, $this->roles, true)
|| in_array(DashboardGlobalRole::Creator, $this->roles, true)
? DashboardGlobalRole::Creator
: DashboardGlobalRole::Viewer;
}
}
| 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/Domain/Model/Metric/ResourceMetric.php | centreon/src/Core/Dashboard/Domain/Model/Metric/ResourceMetric.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\Domain\Model\Metric;
class ResourceMetric
{
/**
* @param int $serviceId
* @param string $resourceName
* @param string $parentName
* @param int $parentId
* @param PerformanceMetric[] $metrics
*/
public function __construct(
private readonly int $serviceId,
private readonly string $resourceName,
private readonly string $parentName,
private readonly int $parentId,
private readonly array $metrics,
) {
}
public function getServiceId(): int
{
return $this->serviceId;
}
public function getResourceName(): string
{
return $this->resourceName;
}
public function getParentName(): string
{
return $this->parentName;
}
public function getParentId(): int
{
return $this->parentId;
}
/**
* @return PerformanceMetric[]
*/
public function getMetrics(): array
{
return $this->metrics;
}
}
| 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/Domain/Model/Metric/PerformanceMetric.php | centreon/src/Core/Dashboard/Domain/Model/Metric/PerformanceMetric.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\Domain\Model\Metric;
class PerformanceMetric
{
public function __construct(
private int $id,
private string $name,
private string $unit,
private ?float $warningHighThreshold,
private ?float $criticalHighThreshold,
private ?float $warningLowThreshold,
private ?float $criticalLowThreshold,
private ?float $currentValue,
private ?float $minimumValue,
private ?float $maximumValue,
) {
}
public function getId(): int
{
return $this->id;
}
public function getName(): string
{
return $this->name;
}
public function getUnit(): string
{
return $this->unit;
}
public function getWarningHighThreshold(): ?float
{
return $this->warningHighThreshold;
}
public function getCriticalHighThreshold(): ?float
{
return $this->criticalHighThreshold;
}
public function getWarningLowThreshold(): ?float
{
return $this->warningLowThreshold;
}
public function getCriticalLowThreshold(): ?float
{
return $this->criticalLowThreshold;
}
public function getCurrentValue(): ?float
{
return $this->currentValue;
}
public function getMinimumValue(): ?float
{
return $this->minimumValue;
}
public function getMaximumValue(): ?float
{
return $this->maximumValue;
}
}
| 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/Domain/Model/Metric/PerformanceMetricsData.php | centreon/src/Core/Dashboard/Domain/Model/Metric/PerformanceMetricsData.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\Domain\Model\Metric;
use Core\Metric\Domain\Model\MetricInformation\MetricInformation;
class PerformanceMetricsData
{
public const DEFAULT_BASE = 1000;
/**
* @param int $base
* @param MetricInformation[] $metricsInformation
* @param \DateTimeImmutable[] $times
*/
public function __construct(
private readonly int $base,
private readonly array $metricsInformation,
private readonly array $times,
) {
}
public function getBase(): int
{
return $this->base;
}
/**
* @return MetricInformation[]
*/
public function getMetricsInformation(): array
{
return $this->metricsInformation;
}
/**
* @return \DateTimeImmutable[]
*/
public function getTimes(): array
{
return $this->times;
}
}
| 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/Domain/Model/Validation/DashboardValidationTrait.php | centreon/src/Core/Dashboard/Domain/Model/Validation/DashboardValidationTrait.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\Domain\Model\Validation;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Core\Dashboard\Domain\Model\Dashboard;
/**
* This trait exists only here for DRY reasons.
*
* It gathers all the guard methods of common fields from {@see Dashboard} and {@see NewDashboard} entities.
*/
trait DashboardValidationTrait
{
/**
* @param string $name
*
* @throws AssertionFailedException
*/
private function ensureValidName(string $name): void
{
$shortName = (new \ReflectionClass($this))->getShortName();
Assertion::maxLength($name, Dashboard::MAX_NAME_LENGTH, $shortName . '::name');
Assertion::notEmptyString($name, $shortName . '::name');
}
/**
* @param string $description
*
* @throws AssertionFailedException
*/
private function ensureValidDescription(string $description): void
{
$shortName = (new \ReflectionClass($this))->getShortName();
Assertion::minLength($description, Dashboard::MIN_DESCRIPTION_LENGTH, $shortName . '::description');
Assertion::maxLength($description, Dashboard::MAX_DESCRIPTION_LENGTH, $shortName . '::description');
}
/**
* @param int $value
* @param string $propertyName
*
* @throws AssertionFailedException
*/
private function ensurePositiveInt(int $value, string $propertyName): void
{
$shortName = (new \ReflectionClass($this))->getShortName();
Assertion::positiveInt($value, $shortName . '::' . $propertyName);
}
/**
* @param ?int $value
* @param string $propertyName
*
* @throws AssertionFailedException
*/
private function ensureNullablePositiveInt(?int $value, string $propertyName): void
{
if ($value !== null) {
$this->ensurePositiveInt($value, $propertyName);
}
}
}
| 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/Domain/Model/Validation/DashboardPanelValidationTrait.php | centreon/src/Core/Dashboard/Domain/Model/Validation/DashboardPanelValidationTrait.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\Domain\Model\Validation;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Core\Dashboard\Domain\Model\DashboardPanel;
/**
* This trait exists only here for DRY reasons.
*
* It gathers all the guard methods of common fields from {@see DashboardPanel} and {@see NewDashboardPanel} entities.
*/
trait DashboardPanelValidationTrait
{
/**
* @param string $name
*
* @throws AssertionFailedException
*/
private function ensureValidName(string $name): void
{
$shortName = (new \ReflectionClass($this))->getShortName();
Assertion::maxLength($name, DashboardPanel::MAX_NAME_LENGTH, $shortName . '::name');
}
/**
* @param string $widgetType
*
* @throws AssertionFailedException
*/
private function ensureValidWidgetType(string $widgetType): void
{
$shortName = (new \ReflectionClass($this))->getShortName();
Assertion::maxLength($widgetType, DashboardPanel::MAX_WIDGET_TYPE_LENGTH, $shortName . '::widgetType');
Assertion::notEmptyString($widgetType, $shortName . '::widgetType');
}
/**
* @param array<mixed> $widgetSettings
*
* @throws AssertionFailedException
*/
private function ensureValidWidgetSettings(array $widgetSettings): void
{
$shortName = (new \ReflectionClass($this))->getShortName();
Assertion::jsonEncodable(
$widgetSettings,
$shortName . '::widgetType',
DashboardPanel::MAX_WIDGET_SETTINGS_LENGTH
);
}
/**
* @param int $integer
* @param string $propertyName
*
* @throws AssertionFailedException
*/
private function ensureValidSmallInteger(int $integer, string $propertyName): void
{
$shortName = (new \ReflectionClass($this))->getShortName();
Assertion::range(
$integer,
DashboardPanel::MIN_SMALL_INTEGER,
DashboardPanel::MAX_SMALL_INTEGER,
$shortName . '::' . $propertyName
);
}
}
| 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/Domain/Model/Share/DashboardContactGroupShare.php | centreon/src/Core/Dashboard/Domain/Model/Share/DashboardContactGroupShare.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\Domain\Model\Share;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Core\Dashboard\Domain\Model\Dashboard;
use Core\Dashboard\Domain\Model\Role\DashboardSharingRole;
class DashboardContactGroupShare
{
/**
* @param Dashboard $dashboard
* @param int $contactGroupId
* @param string $contactGroupName
* @param DashboardSharingRole $role
*
* @throws AssertionFailedException
*/
public function __construct(
private readonly Dashboard $dashboard,
private readonly int $contactGroupId,
private readonly string $contactGroupName,
private readonly DashboardSharingRole $role,
) {
$shortName = (new \ReflectionClass($this))->getShortName();
Assertion::positiveInt($contactGroupId, $shortName . '::contactGroupId');
Assertion::notEmptyString($contactGroupName, $shortName . '::contactGroupName');
}
public function getDashboard(): Dashboard
{
return $this->dashboard;
}
public function getContactGroupId(): int
{
return $this->contactGroupId;
}
public function getContactGroupName(): string
{
return $this->contactGroupName;
}
public function getRole(): DashboardSharingRole
{
return $this->role;
}
}
| 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/Domain/Model/Share/DashboardSharingRoles.php | centreon/src/Core/Dashboard/Domain/Model/Share/DashboardSharingRoles.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\Domain\Model\Share;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Core\Dashboard\Domain\Model\Dashboard;
use Core\Dashboard\Domain\Model\Role\DashboardSharingRole;
class DashboardSharingRoles
{
/**
* @param Dashboard $dashboard
* @param ?DashboardContactShare $contactShare
* @param array<DashboardContactGroupShare> $contactGroupShares
*
* @throws AssertionFailedException
*/
public function __construct(
private readonly Dashboard $dashboard,
private readonly ?DashboardContactShare $contactShare,
private readonly array $contactGroupShares,
) {
$shortName = (new \ReflectionClass($this))->getShortName();
foreach ($contactGroupShares as $contactGroupShare) {
Assertion::isInstanceOf(
$contactGroupShare,
DashboardContactGroupShare::class,
"{$shortName}::contactGroupShares"
);
}
}
public function getTheMostPermissiveRole(): ?DashboardSharingRole
{
$role = $this->contactShare?->getRole();
foreach ($this->contactGroupShares as $contactGroupShare) {
$role = $contactGroupShare->getRole()->getTheMostPermissiveOfBoth($role);
}
return $role;
}
public function getDashboard(): Dashboard
{
return $this->dashboard;
}
public function getContactShare(): ?DashboardContactShare
{
return $this->contactShare;
}
/**
* @return array<DashboardContactGroupShare>
*/
public function getContactGroupShares(): array
{
return $this->contactGroupShares;
}
}
| 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/Domain/Model/Share/DashboardContactShare.php | centreon/src/Core/Dashboard/Domain/Model/Share/DashboardContactShare.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\Domain\Model\Share;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Core\Dashboard\Domain\Model\Dashboard;
use Core\Dashboard\Domain\Model\Role\DashboardSharingRole;
class DashboardContactShare
{
/**
* @param Dashboard $dashboard
* @param int $contactId
* @param string $contactName
* @param string $contactEmail
* @param DashboardSharingRole $role
*
* @throws AssertionFailedException
*/
public function __construct(
private readonly Dashboard $dashboard,
private readonly int $contactId,
private readonly string $contactName,
private readonly string $contactEmail,
private readonly DashboardSharingRole $role,
) {
$shortName = (new \ReflectionClass($this))->getShortName();
Assertion::positiveInt($contactId, $shortName . '::contactId');
Assertion::notEmptyString($contactName, $shortName . '::contactName');
Assertion::notEmptyString($contactEmail, $shortName . '::contactEmail');
}
public function getDashboard(): Dashboard
{
return $this->dashboard;
}
public function getContactId(): int
{
return $this->contactId;
}
public function getContactName(): string
{
return $this->contactName;
}
public function getContactEmail(): string
{
return $this->contactEmail;
}
public function getRole(): DashboardSharingRole
{
return $this->role;
}
}
| 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/Event/DashboardUpdatedSubscriber.php | centreon/src/Core/Dashboard/Infrastructure/Event/DashboardUpdatedSubscriber.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\Event;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Dashboard\Application\Event\DashboardUpdatedEvent;
use Core\Dashboard\Application\UseCase\AddDashboardThumbnail\AddDashboardThumbnail;
use Core\Dashboard\Application\UseCase\AddDashboardThumbnail\AddDashboardThumbnailPresenterInterface;
use Core\Dashboard\Application\UseCase\AddDashboardThumbnail\AddDashboardThumbnailRequest;
use Core\Media\Application\UseCase\UpdateMedia\UpdateMedia;
use Core\Media\Application\UseCase\UpdateMedia\UpdateMediaPresenterInterface;
use Core\Media\Application\UseCase\UpdateMedia\UpdateMediaRequest;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
final readonly class DashboardUpdatedSubscriber implements EventSubscriberInterface
{
/**
* @param UpdateMedia $thumbnailUpdater
* @param UpdateMediaPresenterInterface $thumbnailUpdaterPresenter
* @param AddDashboardThumbnail $thumbnailCreator
* @param AddDashboardThumbnailPresenterInterface $thumbnailCreatorPresenter
*/
public function __construct(
private UpdateMedia $thumbnailUpdater,
private UpdateMediaPresenterInterface $thumbnailUpdaterPresenter,
private AddDashboardThumbnail $thumbnailCreator,
private AddDashboardThumbnailPresenterInterface $thumbnailCreatorPresenter,
) {
}
/**
* @inheritDoc
*/
public static function getSubscribedEvents(): array
{
return [DashboardUpdatedEvent::class => 'createOrUpdateDashboardThumbnail'];
}
/**
* @param DashboardUpdatedEvent $event
*
* @throws \Exception
*/
public function createOrUpdateDashboardThumbnail(DashboardUpdatedEvent $event): void
{
if ($event->getThumbnailId() === null) {
($this->thumbnailCreator)(
$this->createAddDashboardThumbnailRequestFromEvent($event),
$this->thumbnailCreatorPresenter
);
/** @var AbstractPresenter $thumbnailCreatorPresenter */
$thumbnailCreatorPresenter = $this->thumbnailCreatorPresenter;
$responseStatus = $thumbnailCreatorPresenter->getResponseStatus();
if ($responseStatus !== null) {
throw new \Exception($responseStatus->getMessage());
}
} else {
($this->thumbnailUpdater)(
$event->getThumbnailId(),
$this->createUpdateMediaRequest($event),
$this->thumbnailUpdaterPresenter,
);
/** @var AbstractPresenter $mediaUpdaterPresenter */
$mediaUpdaterPresenter = $this->thumbnailUpdaterPresenter;
$responseStatus = $mediaUpdaterPresenter->getResponseStatus();
if ($responseStatus !== null) {
throw new \Exception($responseStatus->getMessage());
}
}
}
/**
* @param DashboardUpdatedEvent $event
*
* @return AddDashboardThumbnailRequest
*/
private function createAddDashboardThumbnailRequestFromEvent(
DashboardUpdatedEvent $event,
): AddDashboardThumbnailRequest {
return new AddDashboardThumbnailRequest(
$event->getDashboardId(),
$event->getDirectory(),
$event->getFilename(),
$event->getContent(),
);
}
/**
* @param DashboardUpdatedEvent $event
*
* @return UpdateMediaRequest
*/
private function createUpdateMediaRequest(DashboardUpdatedEvent $event): UpdateMediaRequest
{
if ($event->getContent() === '') {
throw new \Exception(sprintf('No data found for media %s', $event->getFilename()));
}
return new UpdateMediaRequest($event->getFilename(), $event->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/Model/DashboardSharingRoleConverter.php | centreon/src/Core/Dashboard/Infrastructure/Model/DashboardSharingRoleConverter.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\Model;
use Core\Dashboard\Domain\Model\Role\DashboardSharingRole;
class DashboardSharingRoleConverter
{
public static function toString(DashboardSharingRole $role): string
{
return match ($role) {
DashboardSharingRole::Editor => 'editor',
DashboardSharingRole::Viewer => 'viewer',
};
}
/**
* @param string $string
*
* @throws \InvalidArgumentException
*
* @return DashboardSharingRole
*/
public static function fromString(string $string): DashboardSharingRole
{
return match ($string) {
'editor' => DashboardSharingRole::Editor,
'viewer' => DashboardSharingRole::Viewer,
default => throw new \InvalidArgumentException("\"{$string}\" is not a valid string for enum DashboardSharingRole"),
};
}
}
| 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/Model/RefreshTypeConverter.php | centreon/src/Core/Dashboard/Infrastructure/Model/RefreshTypeConverter.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\Model;
use Core\Dashboard\Domain\Model\Refresh\RefreshType;
class RefreshTypeConverter
{
/**
* @param RefreshType $refreshType
*
* @return string
*/
public static function toString(RefreshType $refreshType): string
{
return match ($refreshType) {
RefreshType::Global => 'global',
RefreshType::Manual => 'manual',
};
}
/**
* @param string $refreshType
*
* @throws \InvalidArgumentException
*
* @return RefreshType
*/
public static function fromString(string $refreshType): RefreshType
{
return match ($refreshType) {
'global' => RefreshType::Global,
'manual' => RefreshType::Manual,
default => throw new \InvalidArgumentException(
"\"{$refreshType}\" is not a valid string for enum RefreshType"
),
};
}
}
| 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/Model/DashboardGlobalRoleConverter.php | centreon/src/Core/Dashboard/Infrastructure/Model/DashboardGlobalRoleConverter.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\Model;
use Core\Dashboard\Domain\Model\Role\DashboardGlobalRole;
class DashboardGlobalRoleConverter
{
public static function toString(DashboardGlobalRole $role): string
{
return match ($role) {
DashboardGlobalRole::Administrator => 'administrator',
DashboardGlobalRole::Creator => 'creator',
DashboardGlobalRole::Viewer => 'viewer',
};
}
/**
* @param string $role
*
* @throws \UnexpectedValueException
*
* @return DashboardGlobalRole
*/
public static function fromString(string $role): DashboardGlobalRole
{
return match ($role) {
'Administrator' => DashboardGlobalRole::Administrator,
'Creator' => DashboardGlobalRole::Creator,
'Viewer' => DashboardGlobalRole::Viewer,
default => throw new \UnexpectedValueException('Invalid role provided'),
};
}
}
| 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/Voters/DashboardVoter.php | centreon/src/Core/Dashboard/Infrastructure/Voters/DashboardVoter.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\Voters;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
/**
* @extends Voter<string, mixed>
*/
final class DashboardVoter extends Voter
{
public const DASHBOARD_ACCESS = 'dashboard_access';
public const DASHBOARD_ACCESS_EDITOR = 'dashboard_access_editor';
/**
* {@inheritDoc}
*/
protected function supports(string $attribute, mixed $subject): bool
{
if (
$attribute === self::DASHBOARD_ACCESS
|| $attribute === self::DASHBOARD_ACCESS_EDITOR
) {
return $subject === null;
}
return false;
}
/**
* {@inheritDoc}
*/
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (! $user instanceof ContactInterface) {
return false;
}
return match ($attribute) {
self::DASHBOARD_ACCESS => $this->checkUsersRights($user),
self::DASHBOARD_ACCESS_EDITOR => $this->checkEditorsRights($user),
default => throw new \LogicException('Action on dashboard not handled'),
};
}
/**
* @param ContactInterface $user
* @return bool
*/
private function checkUsersRights(ContactInterface $user): bool
{
return (bool) (
$user->hasTopologyRole(Contact::ROLE_HOME_DASHBOARD_ADMIN)
|| $user->hasTopologyRole(Contact::ROLE_HOME_DASHBOARD_CREATOR)
|| $user->hasTopologyRole(Contact::ROLE_HOME_DASHBOARD_VIEWER)
);
}
/**
* @param ContactInterface $user
* @return bool
*/
private function checkEditorsRights(ContactInterface $user): bool
{
return (bool) (
$user->hasTopologyRole(Contact::ROLE_HOME_DASHBOARD_ADMIN)
|| $user->hasTopologyRole(Contact::ROLE_HOME_DASHBOARD_CREATOR)
);
}
}
| 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/Serializer/DashboardContactGroupsResponseNormalizer.php | centreon/src/Core/Dashboard/Infrastructure/Serializer/DashboardContactGroupsResponseNormalizer.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\Serializer;
use Core\Dashboard\Application\UseCase\FindDashboardContactGroups\Response\ContactGroupsResponseDto;
use Core\Dashboard\Infrastructure\Model\DashboardGlobalRoleConverter;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
final class DashboardContactGroupsResponseNormalizer implements NormalizerInterface
{
public function __construct(
#[Autowire(service: 'serializer.normalizer.object')]
private readonly NormalizerInterface $normalizer,
) {
}
/**
* @param array<string, mixed> $context
* @param mixed $data
* @param ?string $format
*/
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof ContactGroupsResponseDto;
}
/**
* @param ContactGroupsResponseDto $object
* @param string|null $format
* @param array<string, mixed> $context
*
* @throws \Throwable
*
* @return array<string, mixed>
*/
public function normalize(mixed $object, ?string $format = null, array $context = []): array
{
/** @var array{
* id: int,
* name: string,
* most_permissive_role: string
* } $data
*/
$data = $this->normalizer->normalize($object, $format, $context);
$data['most_permissive_role'] = DashboardGlobalRoleConverter::toString($object->mostPermissiveRole) === 'creator'
? 'editor'
: DashboardGlobalRoleConverter::toString($object->mostPermissiveRole);
return $data;
}
/**
* @param ?string $format
* @return array<class-string|'*'|'object'|string, bool|null>
*/
public function getSupportedTypes(?string $format): array
{
return [
ContactGroupsResponseDto::class => 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/Dashboard/Infrastructure/Serializer/DashboardContactResponseNormalizer.php | centreon/src/Core/Dashboard/Infrastructure/Serializer/DashboardContactResponseNormalizer.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\Serializer;
use Core\Dashboard\Application\UseCase\FindDashboardContacts\Response\ContactsResponseDto;
use Core\Dashboard\Infrastructure\Model\DashboardGlobalRoleConverter;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
final class DashboardContactResponseNormalizer implements NormalizerInterface
{
public function __construct(
#[Autowire(service: 'serializer.normalizer.object')]
private readonly NormalizerInterface $normalizer,
) {
}
/**
* @param array<string, mixed> $context
* @param mixed $data
* @param ?string $format
*/
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof ContactsResponseDto;
}
/**
* @param ContactsResponseDto $object
* @param string|null $format
* @param array<string, mixed> $context
*
* @throws \Throwable
*
* @return array<string, mixed>
*/
public function normalize(mixed $object, ?string $format = null, array $context = []): array
{
/** @var array{
* id: int,
* name: string,
* email: string,
* most_permissive_role: string
* } $data
*/
$data = $this->normalizer->normalize($object, $format, $context);
$data['most_permissive_role'] = DashboardGlobalRoleConverter::toString($object->mostPermissiveRole) === 'creator'
? 'editor'
: DashboardGlobalRoleConverter::toString($object->mostPermissiveRole);
return $data;
}
/**
* @param ?string $format
* @return array<class-string|'*'|'object'|string, bool|null>
*/
public function getSupportedTypes(?string $format): array
{
return [
ContactsResponseDto::class => 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/Dashboard/Infrastructure/Serializer/DashboardResponseDtoNormalizer.php | centreon/src/Core/Dashboard/Infrastructure/Serializer/DashboardResponseDtoNormalizer.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\Serializer;
use Core\Dashboard\Application\UseCase\FindFavoriteDashboards\Response\DashboardResponseDto;
use Core\Dashboard\Infrastructure\Model\DashboardSharingRoleConverter;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
final class DashboardResponseDtoNormalizer implements NormalizerInterface
{
public function __construct(
#[Autowire(service: 'serializer.normalizer.object')]
private readonly NormalizerInterface $normalizer,
) {
}
/**
* @param array<string, mixed> $context
* @param mixed $data
* @param ?string $format
*/
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof DashboardResponseDto;
}
/**
* @param DashboardResponseDto $object
* @param string|null $format
* @param array<string, mixed> $context
*
* @throws \Throwable
*
* @return array<string, mixed>
*/
public function normalize(mixed $object, ?string $format = null, array $context = []): array
{
/** @var array<string, bool|float|int|string> $data */
$data = $this->normalizer->normalize($object, $format, $context);
$data['own_role'] = DashboardSharingRoleConverter::toString($object->ownRole);
/** array{
* contacts: array<array{
* id: int,
* name: string,
* email: string,
* role: DashboardSharingRole
* }>,
* contact_groups: array<array{
* id: int,
* name: string,
* role: DashboardSharingRole
* }>
* } $shares
*/
$shares = $object->shares;
foreach ($shares['contacts'] as $key => $contact) {
$data['shares']['contacts'][$key]['role'] = DashboardSharingRoleConverter::toString($contact['role']);
}
foreach ($shares['contact_groups'] as $key => $contactGroup) {
$data['shares']['contact_groups'][$key]['role'] = DashboardSharingRoleConverter::toString($contactGroup['role']);
}
return $data;
}
/**
* @param ?string $format
* @return array<class-string|'*'|'object'|string, bool|null>
*/
public function getSupportedTypes(?string $format): array
{
return [
DashboardResponseDto::class => 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/Dashboard/Infrastructure/Repository/DbWriteDashboardShareRepository.php | centreon/src/Core/Dashboard/Infrastructure/Repository/DbWriteDashboardShareRepository.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\Repository;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Core\Dashboard\Application\Repository\WriteDashboardShareRepositoryInterface;
use Core\Dashboard\Domain\Model\Role\DashboardSharingRole;
use Core\Dashboard\Infrastructure\Model\DashboardSharingRoleConverter;
class DbWriteDashboardShareRepository extends AbstractRepositoryDRB implements WriteDashboardShareRepositoryInterface
{
use LoggerTrait;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
public function deleteContactShare(int $contactId, int $dashboardId): bool
{
$query = <<<'SQL'
DELETE FROM
`:db`.`dashboard_contact_relation`
WHERE
dashboard_id = :dashboard_id
AND contact_id = :contact_id
SQL;
$statement = $this->db->prepare($this->translateDbName($query));
$statement->bindValue(':dashboard_id', $dashboardId, \PDO::PARAM_INT);
$statement->bindValue(':contact_id', $contactId, \PDO::PARAM_INT);
$statement->execute();
return $statement->rowCount() !== 0;
}
public function deleteContactGroupShare(int $contactGroupId, int $dashboardId): bool
{
$query = <<<'SQL'
DELETE FROM
`:db`.`dashboard_contactgroup_relation`
WHERE
dashboard_id = :dashboard_id
AND contactgroup_id = :contactgroup_id
SQL;
$statement = $this->db->prepare($this->translateDbName($query));
$statement->bindValue(':dashboard_id', $dashboardId, \PDO::PARAM_INT);
$statement->bindValue(':contactgroup_id', $contactGroupId, \PDO::PARAM_INT);
$statement->execute();
return $statement->rowCount() !== 0;
}
public function updateContactShare(int $contactId, int $dashboardId, DashboardSharingRole $role): bool
{
$query = <<<'SQL'
UPDATE `:db`.`dashboard_contact_relation`
SET
`role` = :contact_role
WHERE
dashboard_id = :dashboard_id
AND contact_id = :contact_id
SQL;
$statement = $this->db->prepare($this->translateDbName($query));
$statement->bindValue(':dashboard_id', $dashboardId, \PDO::PARAM_INT);
$statement->bindValue(':contact_id', $contactId, \PDO::PARAM_INT);
$statement->bindValue(':contact_role', $this->roleToString($role), \PDO::PARAM_STR);
$statement->execute();
return $statement->rowCount() !== 0;
}
public function updateContactGroupShare(int $contactGroupId, int $dashboardId, DashboardSharingRole $role): bool
{
$query = <<<'SQL'
UPDATE `:db`.`dashboard_contactgroup_relation`
SET
`role` = :contact_role
WHERE
dashboard_id = :dashboard_id
AND contactgroup_id = :contactgroup_id
SQL;
$statement = $this->db->prepare($this->translateDbName($query));
$statement->bindValue(':dashboard_id', $dashboardId, \PDO::PARAM_INT);
$statement->bindValue(':contactgroup_id', $contactGroupId, \PDO::PARAM_INT);
$statement->bindValue(':contact_role', $this->roleToString($role), \PDO::PARAM_STR);
$statement->execute();
return $statement->rowCount() !== 0;
}
public function upsertShareWithContact(int $contactId, int $dashboardId, DashboardSharingRole $role): void
{
$query = <<<'SQL'
INSERT INTO `:db`.`dashboard_contact_relation` (`dashboard_id`, `contact_id`, `role`)
VALUES (:dashboard_id, :contact_id, :contact_role)
ON DUPLICATE KEY UPDATE `role` = :contact_role
SQL;
$statement = $this->db->prepare($this->translateDbName($query));
$statement->bindValue(':dashboard_id', $dashboardId, \PDO::PARAM_INT);
$statement->bindValue(':contact_id', $contactId, \PDO::PARAM_INT);
$statement->bindValue(':contact_role', $this->roleToString($role), \PDO::PARAM_STR);
$statement->execute();
}
public function upsertShareWithContactGroup(int $contactGroupId, int $dashboardId, DashboardSharingRole $role): void
{
$query = <<<'SQL'
INSERT INTO `:db`.`dashboard_contactgroup_relation` (`dashboard_id`, `contactgroup_id`, `role`)
VALUES (:dashboard_id, :contactgroup_id, :contact_role)
ON DUPLICATE KEY UPDATE `role` = :contact_role
SQL;
$statement = $this->db->prepare($this->translateDbName($query));
$statement->bindValue(':dashboard_id', $dashboardId, \PDO::PARAM_INT);
$statement->bindValue(':contactgroup_id', $contactGroupId, \PDO::PARAM_INT);
$statement->bindValue(':contact_role', $this->roleToString($role), \PDO::PARAM_STR);
$statement->execute();
}
/**
* @inheritDoc
*/
public function deleteDashboardShares(int $dashboardId): void
{
$deleteContactSharesStatement = $this->db->prepare($this->translateDbName(
<<<'SQL'
DELETE FROM dashboard_contact_relation WHERE dashboard_id = :dashboardId
SQL
));
$deleteContactSharesStatement->bindValue(':dashboardId', $dashboardId, \PDO::PARAM_INT);
$deleteContactSharesStatement->execute();
$deleteContactGroupSharesStatement = $this->db->prepare($this->translateDbName(
<<<'SQL'
DELETE FROM dashboard_contactgroup_relation WHERE dashboard_id = :dashboardId
SQL
));
$deleteContactGroupSharesStatement->bindValue(':dashboardId', $dashboardId, \PDO::PARAM_INT);
$deleteContactGroupSharesStatement->execute();
}
/**
* @inheritDoc
*/
public function deleteDashboardSharesByContactGroupIds(int $dashboardId, array $contactGroupIds): void
{
$bind = [];
foreach ($contactGroupIds as $key => $contactGroupId) {
$bind[':contact_group' . $key] = $contactGroupId;
}
if ($bind === []) {
return;
}
$bindTokenAsString = implode(', ', array_keys($bind));
$deleteContactGroupSharesStatement = $this->db->prepare($this->translateDbName(
<<<SQL
DELETE FROM dashboard_contactgroup_relation
WHERE dashboard_id = :dashboardId
AND contactgroup_id IN ({$bindTokenAsString})
SQL
));
$deleteContactGroupSharesStatement->bindValue(':dashboardId', $dashboardId, \PDO::PARAM_INT);
foreach ($bind as $token => $contactGroupId) {
$deleteContactGroupSharesStatement->bindValue($token, $contactGroupId, \PDO::PARAM_INT);
}
$deleteContactGroupSharesStatement->execute();
}
/**
* @inheritDoc
*/
public function deleteDashboardSharesByContactIds(int $dashboardId, array $contactIds): void
{
$bind = [];
foreach ($contactIds as $key => $contactId) {
$bind[':contact' . $key] = $contactId;
}
if ($bind === []) {
return;
}
$bindTokenAsString = implode(', ', array_keys($bind));
$deleteContactGroupSharesStatement = $this->db->prepare($this->translateDbName(
<<<SQL
DELETE FROM dashboard_contact_relation
WHERE dashboard_id = :dashboardId
AND contact_id IN ({$bindTokenAsString})
SQL
));
$deleteContactGroupSharesStatement->bindValue(':dashboardId', $dashboardId, \PDO::PARAM_INT);
foreach ($bind as $token => $contactId) {
$deleteContactGroupSharesStatement->bindValue($token, $contactId, \PDO::PARAM_INT);
}
$deleteContactGroupSharesStatement->execute();
}
/**
* @inheritDoc
*/
public function addDashboardContactShares(int $dashboardId, array $contactRoles): void
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
INSERT INTO dashboard_contact_relation (`dashboard_id`,`contact_id`,`role`)
VALUES (:dashboardId,:contactId,:role)
SQL
));
$statement->bindValue(':dashboardId', $dashboardId, \PDO::PARAM_INT);
foreach ($contactRoles as $contactRole) {
$statement->bindValue(':contactId', $contactRole->getId());
$statement->bindValue(
':role',
DashboardSharingRoleConverter::toString($contactRole->getRole()),
\PDO::PARAM_STR
);
$statement->execute();
}
}
/**
* @inheritDoc
*/
public function addDashboardContactGroupShares(int $dashboardId, array $contactGroupRoles): void
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
INSERT INTO dashboard_contactgroup_relation (`dashboard_id`,`contactgroup_id`,`role`)
VALUES (:dashboardId,:contactGroupId,:role)
SQL
));
$statement->bindValue(':dashboardId', $dashboardId, \PDO::PARAM_INT);
foreach ($contactGroupRoles as $contactGroupRole) {
$statement->bindValue(':contactGroupId', $contactGroupRole->getId());
$statement->bindValue(
':role',
DashboardSharingRoleConverter::toString($contactGroupRole->getRole()),
\PDO::PARAM_STR
);
$statement->execute();
}
}
/**
* We want to make the conversion between a role and its string table representation here.
*
* @param DashboardSharingRole $role
*
* @return string
*/
private function roleToString(DashboardSharingRole $role): string
{
return DashboardSharingRoleConverter::toString($role);
}
}
| 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/Repository/DbReadDashboardShareRepository.php | centreon/src/Core/Dashboard/Infrastructure/Repository/DbReadDashboardShareRepository.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\Repository;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Repository\RepositoryException;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait;
use Core\Contact\Domain\Model\ContactGroup;
use Core\Dashboard\Application\Repository\ReadDashboardShareRepositoryInterface;
use Core\Dashboard\Domain\Model\Dashboard;
use Core\Dashboard\Domain\Model\DashboardRights;
use Core\Dashboard\Domain\Model\Role\DashboardContactGroupRole;
use Core\Dashboard\Domain\Model\Role\DashboardContactRole;
use Core\Dashboard\Domain\Model\Role\DashboardGlobalRole;
use Core\Dashboard\Domain\Model\Role\DashboardSharingRole;
use Core\Dashboard\Domain\Model\Share\DashboardContactGroupShare;
use Core\Dashboard\Domain\Model\Share\DashboardContactShare;
use Core\Dashboard\Domain\Model\Share\DashboardSharingRoles;
use Core\Dashboard\Infrastructure\Model\DashboardGlobalRoleConverter;
use Core\Dashboard\Infrastructure\Model\DashboardSharingRoleConverter;
use Utility\SqlConcatenator;
class DbReadDashboardShareRepository extends AbstractRepositoryDRB implements ReadDashboardShareRepositoryInterface
{
use LoggerTrait;
use SqlMultipleBindTrait;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
public function findDashboardContactSharesByRequestParameter(
Dashboard $dashboard,
RequestParametersInterface $requestParameters,
): array {
$requestParameters->setConcordanceStrictMode(RequestParameters::CONCORDANCE_MODE_STRICT);
$sqlTranslator = new SqlRequestParametersTranslator($requestParameters);
$sqlTranslator->setConcordanceArray([
'id' => 'c.contact_id',
'name' => 'c.contact_name',
'email' => 'c.contact_email',
]);
$concatenator = (new SqlConcatenator())
->defineSelect(
<<<'SQL'
SELECT
c.`contact_id`,
c.`contact_name`,
c.`contact_email`,
dcr.`role`
SQL
)
->defineFrom(
<<<'SQL'
FROM `:db`.`dashboard_contact_relation` dcr
SQL
)
->defineJoins(
<<<'SQL'
INNER JOIN `:db`.`contact` c ON c.`contact_id`=dcr.`contact_id`
SQL
)
->defineWhere(
<<<'SQL'
WHERE dcr.`dashboard_id` = :dashboard_id
SQL
)
->storeBindValue(':dashboard_id', $dashboard->getId(), \PDO::PARAM_INT)
->defineOrderBy(
<<<'SQL'
ORDER BY c.`contact_name` ASC
SQL
);
$sqlTranslator->translateForConcatenator($concatenator);
$statement = $this->db->prepare($this->translateDbName($concatenator->concatAll()));
$sqlTranslator->bindSearchValues($statement);
$concatenator->bindValuesToStatement($statement);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
$sqlTranslator->calculateNumberOfRows($this->db);
// Retrieve data
$shares = [];
foreach ($statement as $result) {
/** @var array{
* contact_id: int,
* contact_name: string,
* contact_email: string,
* role: string
* } $result
*/
$shares[] = new DashboardContactShare(
$dashboard,
$result['contact_id'],
$result['contact_name'],
$result['contact_email'],
$this->stringToRole($result['role'])
);
}
return $shares;
}
public function findDashboardContactGroupSharesByRequestParameter(
Dashboard $dashboard,
RequestParametersInterface $requestParameters,
): array {
$requestParameters->setConcordanceStrictMode(RequestParameters::CONCORDANCE_MODE_STRICT);
$sqlTranslator = new SqlRequestParametersTranslator($requestParameters);
$sqlTranslator->setConcordanceArray([
'id' => 'cg.cg_id',
'name' => 'cg.cg_name',
]);
$concatenator = (new SqlConcatenator())
->defineSelect(
<<<'SQL'
SELECT DISTINCT
cg.`cg_id`,
cg.`cg_name`,
dcgr.`role`
SQL
)
->defineFrom(
<<<'SQL'
FROM `:db`.`dashboard_contactgroup_relation` dcgr
SQL
)
->defineJoins(
<<<'SQL'
INNER JOIN `:db`.`contactgroup` cg ON cg.`cg_id`=dcgr.`contactgroup_id`
INNER JOIN `:db`.`contactgroup_contact_relation` cgcr ON cg.`cg_id`=cgcr.`contactgroup_cg_id`
SQL
)
->defineWhere(
<<<'SQL'
WHERE dcgr.`dashboard_id` = :dashboard_id
SQL
)
->storeBindValue(':dashboard_id', $dashboard->getId(), \PDO::PARAM_INT)
->defineOrderBy(
<<<'SQL'
ORDER BY cg.`cg_name` ASC
SQL
);
$sqlTranslator->translateForConcatenator($concatenator);
$statement = $this->db->prepare($this->translateDbName($concatenator->concatAll()));
$sqlTranslator->bindSearchValues($statement);
$concatenator->bindValuesToStatement($statement);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
$sqlTranslator->calculateNumberOfRows($this->db);
// Retrieve data
$shares = [];
foreach ($statement as $result) {
/** @var array{
* cg_id: int,
* cg_name: string,
* role: string
* } $result
*/
$shares[] = new DashboardContactGroupShare(
$dashboard,
$result['cg_id'],
$result['cg_name'],
$this->stringToRole($result['role'])
);
}
return $shares;
}
public function getOneSharingRoles(ContactInterface $contact, Dashboard $dashboard): DashboardSharingRoles
{
$contactShares = $this->getContactShares($contact, $dashboard);
$contactGroupShares = $this->getContactGroupShares($contact, $dashboard);
$dashboardId = $dashboard->getId();
return new DashboardSharingRoles(
$dashboard,
$contactShares[$dashboardId] ?? null,
$contactGroupShares[$dashboardId] ?? [],
);
}
public function getMultipleSharingRoles(ContactInterface $contact, Dashboard ...$dashboards): array
{
$contactShares = $this->getContactShares($contact, ...$dashboards);
$contactGroupShares = $this->getContactGroupShares($contact, ...$dashboards);
$objects = [];
foreach ($dashboards as $dashboard) {
$dashboardId = $dashboard->getId();
$objects[$dashboardId] = new DashboardSharingRoles(
$dashboard,
$contactShares[$dashboardId] ?? null,
$contactGroupShares[$dashboardId] ?? [],
);
}
return $objects;
}
/**
* @inheritDoc
*/
public function findDashboardsContactShares(Dashboard ...$dashboards): array
{
if ($dashboards === []) {
return [];
}
$dashboardsById = [];
foreach ($dashboards as $dashboard) {
$dashboardsById[$dashboard->getId()] = $dashboard;
}
$select = <<<'SQL'
SELECT
dcr.`dashboard_id`,
dcr.`role`,
c.`contact_id`,
c.`contact_email`,
c.`contact_name`
FROM `:db`.`dashboard_contact_relation` dcr
INNER JOIN contact c
ON dcr.contact_id = c.contact_id
WHERE dcr.`dashboard_id` IN (:dashboard_ids)
SQL;
$concatenator = (new SqlConcatenator())
->defineSelect($select)
->storeBindValueMultiple(':dashboard_ids', array_keys($dashboardsById), \PDO::PARAM_INT);
$statement = $this->db->prepare($this->translateDbName($concatenator->concatAll()));
$concatenator->bindValuesToStatement($statement);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
// Retrieve data
$shares = [];
foreach ($statement as $result) {
/** @var array{
* dashboard_id: int,
* role: string,
* contact_id: int,
* contact_email: string,
* contact_name: string
* } $result
*/
$dashboardId = $result['dashboard_id'];
$shares[$dashboardId][] = new DashboardContactShare(
$dashboardsById[$dashboardId],
$result['contact_id'],
$result['contact_name'],
$result['contact_email'],
$this->stringToRole($result['role'])
);
}
return $shares;
}
/**
* @inheritDoc
*/
public function findDashboardsContactSharesByContactIds(array $contactIds, Dashboard ...$dashboards): array
{
if ($dashboards === []) {
return [];
}
$dashboardsById = [];
foreach ($dashboards as $dashboard) {
$dashboardsById[$dashboard->getId()] = $dashboard;
}
$select = <<<'SQL'
SELECT
dcr.`dashboard_id`,
dcr.`role`,
c.`contact_id`,
c.`contact_email`,
c.`contact_name`
FROM `:db`.`dashboard_contact_relation` dcr
INNER JOIN contact c
ON dcr.contact_id = c.contact_id
WHERE dcr.`dashboard_id` IN (:dashboard_ids)
AND c.contact_id IN(:contact_ids)
SQL;
$concatenator = (new SqlConcatenator())
->defineSelect($select)
->storeBindValueMultiple(':dashboard_ids', array_keys($dashboardsById), \PDO::PARAM_INT)
->storeBindValueMultiple(':contact_ids', $contactIds, \PDO::PARAM_INT);
$statement = $this->db->prepare($this->translateDbName($concatenator->concatAll()));
$concatenator->bindValuesToStatement($statement);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
// Retrieve data
$shares = [];
foreach ($statement as $result) {
/** @var array{
* dashboard_id: int,
* role: string,
* contact_id: int,
* contact_email: string,
* contact_name: string
* } $result
*/
$dashboardId = $result['dashboard_id'];
$shares[$dashboardId][] = new DashboardContactShare(
$dashboardsById[$dashboardId],
$result['contact_id'],
$result['contact_name'],
$result['contact_email'],
$this->stringToRole($result['role'])
);
}
return $shares;
}
/**
* @inheritDoc
*/
public function findDashboardsContactGroupShares(Dashboard ...$dashboards): array
{
if ($dashboards === []) {
return [];
}
$dashboardsById = [];
foreach ($dashboards as $dashboard) {
$dashboardsById[$dashboard->getId()] = $dashboard;
}
$select = <<<'SQL'
SELECT
cg.`cg_id`,
cg.`cg_name`,
dcgr.`dashboard_id`,
dcgr.`role`
FROM `:db`.`dashboard_contactgroup_relation` dcgr
INNER JOIN `:db`.`contactgroup` cg ON cg.`cg_id`= dcgr.`contactgroup_id`
WHERE dcgr.`dashboard_id` IN (:dashboard_ids)
SQL;
$concatenator = (new SqlConcatenator())
->defineSelect($select)
->storeBindValueMultiple(':dashboard_ids', array_keys($dashboardsById), \PDO::PARAM_INT);
$statement = $this->db->prepare($this->translateDbName($concatenator->concatAll()));
$concatenator->bindValuesToStatement($statement);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
// Retrieve data
$shares = [];
foreach ($statement as $result) {
/** @var array{
* cg_id: int,
* cg_name: string,
* dashboard_id: int,
* role: string
* } $result
*/
$dashboardId = $result['dashboard_id'];
if (! isset($dashboardsById[$dashboardId])) {
continue;
}
$shares[$dashboardId][] = new DashboardContactGroupShare(
$dashboardsById[$dashboardId],
$result['cg_id'],
$result['cg_name'],
$this->stringToRole($result['role'])
);
}
return $shares;
}
/**
* @inheritDoc
*/
public function findDashboardsContactGroupSharesByContact(ContactInterface $contact, Dashboard ...$dashboards): array
{
return $this->getContactGroupShares($contact, ...$dashboards);
}
/**
* @inheritDoc
*/
public function findContactsWithAccessRightByRequestParameters(
RequestParametersInterface $requestParameters,
): array {
$sqlTranslator = new SqlRequestParametersTranslator($requestParameters);
$sqlTranslator->getRequestParameters()->setConcordanceStrictMode(RequestParameters::CONCORDANCE_MODE_STRICT);
$sqlTranslator->setConcordanceArray([
'name' => 'c.contact_name',
]);
$query = <<<'SQL_WRAP'
SELECT SQL_CALC_FOUND_ROWS
GROUP_CONCAT(topology.topology_name) as topologies,
c.contact_name,
c.contact_id,
c.contact_email
FROM `:db`.contact c
LEFT JOIN `:db`.contactgroup_contact_relation cgcr
ON cgcr.contact_contact_id = c.contact_id
LEFT JOIN `:db`.acl_group_contactgroups_relations gcgr
ON gcgr.cg_cg_id = cgcr.contactgroup_cg_id
LEFT JOIN `:db`.acl_group_contacts_relations gcr
ON gcr.contact_contact_id = c.contact_id
LEFT JOIN `:db`.acl_groups ag
ON ag.acl_group_id = gcr.acl_group_id
LEFT JOIN `:db`.acl_group_topology_relations agtr
ON agtr.acl_group_id = gcr.acl_group_id
OR agtr.acl_group_id = gcgr.acl_group_id
LEFT JOIN `:db`.acl_topology_relations acltr
ON acltr.acl_topo_id = agtr.acl_topology_id
LEFT JOIN `:db`.topology
ON topology.topology_id = acltr.topology_topology_id
LEFT JOIN `:db`.topology parent
ON topology.topology_parent = parent.topology_page
SQL_WRAP;
$searchRequest = $sqlTranslator->translateSearchParameterToSql();
$query .= $searchRequest !== null
? <<<SQL_WRAP
{$searchRequest}
AND c.contact_admin = '0'
AND c.contact_oreon = '1'
AND parent.topology_name = 'Dashboards'
AND topology.topology_name IN ('Viewer','Administrator','Creator')
AND acltr.access_right IS NOT NULL
SQL_WRAP
: <<<'SQL_WRAP'
WHERE c.contact_admin = '0'
AND c.contact_oreon = '1'
AND parent.topology_name = 'Dashboards'
AND topology.topology_name IN ('Viewer','Administrator','Creator')
AND acltr.access_right IS NOT NULL
SQL_WRAP;
$query .= ' GROUP BY c.contact_id, c.contact_name';
$query .= $sqlTranslator->translatePaginationToSql();
$statement = $this->db->prepare($this->translateDbName($query));
$sqlTranslator->bindSearchValues($statement);
$statement->execute();
$result = $this->db->query('SELECT FOUND_ROWS()');
if ($result !== false && ($total = $result->fetchColumn()) !== false) {
$sqlTranslator->getRequestParameters()->setTotal((int) $total);
}
$dashboardContactRoles = [];
foreach ($statement as $contactRole) {
/** @var array{
* topologies: string,
* contact_name: string,
* contact_id: int,
* contact_email: string
* } $contactRole
*/
$dashboardContactRoles[] = $this->createDashboardContactRole($contactRole);
}
return $dashboardContactRoles;
}
/**
* @inheritDoc
*/
public function findContactsWithAccessRightByContactIds(array $contactIds): array
{
$bind = [];
foreach ($contactIds as $key => $contactId) {
$bind[':contact_id' . $key] = $contactId;
}
if ($bind === []) {
return [];
}
$bindTokenAsString = implode(', ', array_keys($bind));
$query = <<<SQL
SELECT SQL_CALC_FOUND_ROWS GROUP_CONCAT(topology.topology_name) as topologies, c.contact_name, c.contact_id, c.contact_email
FROM `:db`.contact c
LEFT JOIN `:db`.contactgroup_contact_relation cgcr
ON cgcr.contact_contact_id = c.contact_id
LEFT JOIN `:db`.acl_group_contactgroups_relations gcgr
ON gcgr.cg_cg_id = cgcr.contactgroup_cg_id
LEFT JOIN `:db`.acl_group_contacts_relations gcr
ON gcr.contact_contact_id = c.contact_id
LEFT JOIN `:db`.acl_group_topology_relations agtr
ON agtr.acl_group_id = gcr.acl_group_id
OR agtr.acl_group_id = gcgr.acl_group_id
LEFT JOIN `:db`.acl_topology_relations acltr
ON acltr.acl_topo_id = agtr.acl_topology_id
INNER JOIN `:db`.topology
ON topology.topology_id = acltr.topology_topology_id
INNER JOIN `:db`.topology parent
ON topology.topology_parent = parent.topology_page
WHERE parent.topology_name = 'Dashboards'
AND topology.topology_name IN ('Viewer','Administrator','Creator')
AND acltr.access_right IS NOT NULL
AND c.contact_id IN ({$bindTokenAsString})
AND c.contact_admin = '0'
GROUP BY c.contact_id
SQL;
$statement = $this->db->prepare($this->translateDbName($query));
foreach ($bind as $token => $contactId) {
$statement->bindValue($token, $contactId, \PDO::PARAM_INT);
}
$statement->execute();
$dashboardContactRoles = [];
foreach ($statement as $contactRole) {
/** @var array{
* topologies: string,
* contact_name: string,
* contact_id: int,
* contact_email: string,
* acl_group_name: string|null
* } $contactRole
*/
$dashboardContactRoles[] = $this->createDashboardContactRole($contactRole);
}
return $dashboardContactRoles;
}
/**
* @inheritDoc
*/
public function findContactGroupsByRequestParameters(RequestParametersInterface $requestParameters): array
{
try {
$sqlTranslator = new SqlRequestParametersTranslator($requestParameters);
$sqlTranslator->getRequestParameters()->setConcordanceStrictMode(RequestParameters::CONCORDANCE_MODE_STRICT);
$sqlTranslator->setConcordanceArray([
'name' => 'cg.cg_name',
]);
$query = <<<'SQL_WRAP'
SELECT SQL_CALC_FOUND_ROWS
'Viewer' as topologies,
cg.cg_name,
cg.cg_id
FROM `:db`.contactgroup cg
SQL_WRAP;
$searchRequest = $sqlTranslator->translateSearchParameterToSql();
$query .= $searchRequest !== null ? ' WHERE ' . $searchRequest : '';
$query .= ' GROUP BY cg.cg_id';
$query .= $sqlTranslator->translatePaginationToSql();
$statement = $this->db->prepare($this->translateDbName($query));
$sqlTranslator->bindSearchValues($statement);
$statement->execute();
$result = $this->db->query('SELECT FOUND_ROWS()');
if ($result !== false && ($total = $result->fetchColumn()) !== false) {
$sqlTranslator->getRequestParameters()->setTotal((int) $total);
}
$dashboardContactGroupRoles = [];
foreach ($statement as $contactGroupRole) {
/** @var array{
* topologies: string,
* cg_name: string,
* cg_id: int,
* } $contactGroupRole
*/
$dashboardContactGroupRoles[] = $this->createDashboardContactGroupRole($contactGroupRole);
}
return $dashboardContactGroupRoles;
} catch (\Throwable $exception) {
throw new RepositoryException(message: 'Error while searching for contact groups', previous: $exception);
}
}
/**
* @inheritDoc
*/
public function findContactGroupsWithAccessRightByRequestParameters(RequestParametersInterface $requestParameters): array
{
$sqlTranslator = new SqlRequestParametersTranslator($requestParameters);
$sqlTranslator->getRequestParameters()->setConcordanceStrictMode(RequestParameters::CONCORDANCE_MODE_STRICT);
$sqlTranslator->setConcordanceArray([
'name' => 'cg.cg_name',
]);
$query = <<<'SQL_WRAP'
SELECT SQL_CALC_FOUND_ROWS GROUP_CONCAT(topology.topology_name) as topologies, cg.cg_name, cg.cg_id
FROM `:db`.contactgroup cg
LEFT JOIN `:db`.acl_group_contactgroups_relations gcgr
ON gcgr.cg_cg_id = cg.cg_id
LEFT JOIN `:db`.acl_group_topology_relations agtr
ON agtr.acl_group_id = gcgr.acl_group_id
LEFT JOIN `:db`.acl_topology_relations acltr
ON acltr.acl_topo_id = agtr.acl_topology_id
INNER JOIN `:db`.topology
ON topology.topology_id = acltr.topology_topology_id
INNER JOIN `:db`.topology parent
ON topology.topology_parent = parent.topology_page
SQL_WRAP;
$searchRequest = $sqlTranslator->translateSearchParameterToSql();
$query .= $searchRequest !== null
? $searchRequest . ' AND '
: ' WHERE ';
$query .= <<<'SQL'
parent.topology_name = 'Dashboards'
AND topology.topology_name IN ('Viewer','Administrator','Creator')
AND acltr.access_right IS NOT NULL
GROUP BY cg.cg_id
SQL;
$query .= $sqlTranslator->translatePaginationToSql();
$statement = $this->db->prepare($this->translateDbName($query));
foreach ($sqlTranslator->getSearchValues() as $key => $data) {
/**
* @var int
*/
$type = key($data);
$value = $data[$type];
$statement->bindValue($key, $value, $type);
}
$statement->execute();
$result = $this->db->query('SELECT FOUND_ROWS()');
if ($result !== false && ($total = $result->fetchColumn()) !== false) {
$sqlTranslator->getRequestParameters()->setTotal((int) $total);
}
$dashboardContactGroupRoles = [];
foreach ($statement as $contactGroupRole) {
/** @var array{
* topologies: string,
* cg_name: string,
* cg_id: int,
* } $contactGroupRole
*/
$dashboardContactGroupRoles[] = $this->createDashboardContactGroupRole($contactGroupRole);
}
return $dashboardContactGroupRoles;
}
public function findContactGroupsWithAccessRightByContactGroupIds(array $contactGroupIds): array
{
$bind = [];
foreach ($contactGroupIds as $key => $contactGroupId) {
$bind[':contact_group' . $key] = $contactGroupId;
}
if ($bind === []) {
return [];
}
$bindTokenAsString = implode(', ', array_keys($bind));
$query = <<<SQL
SELECT SQL_CALC_FOUND_ROWS GROUP_CONCAT(topology.topology_name) as topologies, cg.cg_name, cg.cg_id
FROM `:db`.contactgroup cg
LEFT JOIN `:db`.acl_group_contactgroups_relations gcgr
ON gcgr.cg_cg_id = cg.cg_id
LEFT JOIN `:db`.acl_group_topology_relations agtr
ON agtr.acl_group_id = gcgr.acl_group_id
LEFT JOIN `:db`.acl_topology_relations acltr
ON acltr.acl_topo_id = agtr.acl_topology_id
INNER JOIN `:db`.topology
ON topology.topology_id = acltr.topology_topology_id
INNER JOIN `:db`.topology parent
ON topology.topology_parent = parent.topology_page
WHERE parent.topology_name = 'Dashboards'
AND topology.topology_name IN ('Viewer','Administrator','Creator')
AND acltr.access_right IS NOT NULL
AND cg.cg_id IN ({$bindTokenAsString})
GROUP BY cg.cg_id
SQL;
$statement = $this->db->prepare($this->translateDbName($query));
foreach ($bind as $token => $contactGroupId) {
$statement->bindValue($token, $contactGroupId, \PDO::PARAM_INT);
}
$statement->execute();
$dashboardContactGroupRoles = [];
foreach ($statement as $contactGroupRole) {
/** @var array{
* topologies: string,
* cg_name: string,
* cg_id: int,
* } $contactGroupRole
*/
$dashboardContactGroupRoles[] = $this->createDashboardContactGroupRole($contactGroupRole);
}
return $dashboardContactGroupRoles;
}
/**
* @inheritDoc
*/
public function findContactsWithAccessRightsByContactGroupsAndRequestParameters(
array $contactGroups,
RequestParametersInterface $requestParameters,
): array {
try {
if ($contactGroups === []) {
return [];
}
$contactGroupIds = array_map(
static fn (ContactGroup $contactGroup): int => $contactGroup->getId(),
$contactGroups
);
$sqlTranslator = new SqlRequestParametersTranslator($requestParameters);
$sqlTranslator->getRequestParameters()->setConcordanceStrictMode(
RequestParameters::CONCORDANCE_MODE_STRICT
);
$sqlTranslator->setConcordanceArray([
'name' => 'c.contact_name',
]);
[$bindValues, $bindQuery] = $this->createMultipleBindQuery($contactGroupIds, ':contact_group_id');
$query = <<<SQL
SELECT
GROUP_CONCAT(topology.topology_name) as topologies,
c.contact_name,
c.contact_id,
c.contact_email
FROM `:db`.contact c
LEFT JOIN `:db`.contactgroup_contact_relation cgcr
ON cgcr.contact_contact_id = c.contact_id
LEFT JOIN `:db`.acl_group_contactgroups_relations gcgr
ON gcgr.cg_cg_id = cgcr.contactgroup_cg_id
LEFT JOIN `:db`.acl_group_contacts_relations gcr
ON gcr.contact_contact_id = c.contact_id
LEFT JOIN `:db`.acl_group_topology_relations agtr
ON agtr.acl_group_id = gcr.acl_group_id
OR agtr.acl_group_id = gcgr.acl_group_id
LEFT JOIN `:db`.acl_topology_relations acltr
ON acltr.acl_topo_id = agtr.acl_topology_id
INNER JOIN `:db`.topology
ON topology.topology_id = acltr.topology_topology_id
INNER JOIN `:db`.topology parent
ON topology.topology_parent = parent.topology_page
WHERE
c.contact_oreon = '1'
AND parent.topology_name = 'Dashboards'
AND topology.topology_name IN ('Viewer','Administrator','Creator')
AND cgcr.contactgroup_cg_id IN ({$bindQuery})
AND acltr.access_right IS NOT NULL
SQL;
$searchRequest = $sqlTranslator->translateSearchParameterToSql();
$query .= $searchRequest !== null ? ' AND ' . $searchRequest : '';
$query .= ' GROUP BY c.contact_id';
$statement = $this->db->prepare($this->translateDbName($query));
foreach ($bindValues as $token => $contactGroupId) {
$statement->bindValue($token, $contactGroupId, \PDO::PARAM_INT);
}
$sqlTranslator->bindSearchValues($statement);
$statement->execute();
$result = $this->db->query('SELECT FOUND_ROWS()');
if ($result !== false && ($total = $result->fetchColumn()) !== false) {
$sqlTranslator->getRequestParameters()->setTotal((int) $total);
}
$dashboardContactRoles = [];
foreach ($statement as $contactRole) {
/** @var array{
* topologies: string,
* contact_name: string,
* contact_id: int,
* contact_email: string
* } $contactRole
*/
$dashboardContactRoles[] = $this->createDashboardContactRole($contactRole);
}
return $dashboardContactRoles;
} catch (\Throwable $exception) {
throw new RepositoryException(
message: "Error while retrieving contacts allowed to receive a dashboard share : {$exception->getMessage()}",
previous: $exception,
);
}
}
/**
* @inheritDoc
*/
public function findContactsWithAccessRightByACLGroupsAndRequestParameters(
RequestParametersInterface $requestParameters,
array $aclGroupIds,
): array {
$sqlTranslator = new SqlRequestParametersTranslator($requestParameters);
$sqlTranslator->getRequestParameters()->setConcordanceStrictMode(
RequestParameters::CONCORDANCE_MODE_STRICT
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Infrastructure/Repository/DbWriteDashboardRepository.php | centreon/src/Core/Dashboard/Infrastructure/Repository/DbWriteDashboardRepository.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\Repository;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Common\Infrastructure\Repository\RepositoryTrait;
use Core\Dashboard\Application\Repository\WriteDashboardRepositoryInterface;
use Core\Dashboard\Domain\Model\Dashboard;
use Core\Dashboard\Domain\Model\NewDashboard;
use Core\Dashboard\Infrastructure\Model\RefreshTypeConverter;
class DbWriteDashboardRepository extends AbstractRepositoryRDB implements WriteDashboardRepositoryInterface
{
use LoggerTrait;
use RepositoryTrait;
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function addThumbnailRelation(int $dashboardId, int $thumbnailId): void
{
$request = <<<'SQL'
INSERT INTO `:db`.dashboard_thumbnail_relation
(
dashboard_id,
img_id
)
VALUES
(
:dashboardId,
:thumbnailId
)
SQL;
$statement = $this->db->prepare($this->translateDbName($request));
$statement->bindValue(':dashboardId', $dashboardId, \PDO::PARAM_INT);
$statement->bindValue(':thumbnailId', $thumbnailId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* {@inheritDoc}
*/
public function delete(int $dashboardId): void
{
$this->info('Delete dashboard', ['id' => $dashboardId]);
$query = <<<'SQL'
DELETE FROM `:db`.`dashboard`
WHERE id = :dashboard_id
SQL;
$statement = $this->db->prepare($this->translateDbName($query));
$statement->bindValue(':dashboard_id', $dashboardId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* {@inheritDoc}
*/
public function add(NewDashboard $newDashboard): int
{
$insert = <<<'SQL'
INSERT INTO `:db`.`dashboard`
(
name,
description,
created_by,
updated_by,
created_at,
updated_at,
refresh_type,
refresh_interval
)
VALUES
(
:name,
:description,
:created_by,
:updated_by,
:created_at,
:updated_at,
:refresh_type,
:refresh_interval
)
SQL;
$statement = $this->db->prepare($this->translateDbName($insert));
$this->bindValueOfDashboard($statement, $newDashboard);
$statement->execute();
return (int) $this->db->lastInsertId();
}
/**
* {@inheritDoc}
*/
public function update(Dashboard $dashboard): void
{
$update = <<<'SQL'
UPDATE `:db`.`dashboard`
SET
`name` = :name,
`description` = :description,
`updated_by` = :updated_by,
`updated_at` = :updated_at,
`refresh_type` = :refresh_type,
`refresh_interval` =:refresh_interval
WHERE
`id` = :dashboard_id
SQL;
$statement = $this->db->prepare($this->translateDbName($update));
$statement->bindValue(':dashboard_id', $dashboard->getId(), \PDO::PARAM_INT);
$statement->bindValue(
':refresh_type',
RefreshTypeConverter::toString($dashboard->getRefresh()->getRefreshType()),
\PDO::PARAM_STR
);
$statement->bindValue(
':refresh_interval',
$dashboard->getRefresh()->getRefreshInterval(),
\PDO::PARAM_INT
);
$this->bindValueOfDashboard($statement, $dashboard);
$statement->execute();
}
/**
* @param \PDOStatement $statement
* @param Dashboard|NewDashboard $dashboard
*/
private function bindValueOfDashboard(\PDOStatement $statement, Dashboard|NewDashboard $dashboard): void
{
$statement->bindValue(':name', $dashboard->getName());
$statement->bindValue(':description', $dashboard->getDescription());
$statement->bindValue(':updated_at', $dashboard->getUpdatedAt()->getTimestamp());
$statement->bindValue(':updated_by', $dashboard->getUpdatedBy());
if ($dashboard instanceof NewDashboard) {
$statement->bindValue(':created_at', $dashboard->getCreatedAt()->getTimestamp());
$statement->bindValue(':created_by', $dashboard->getCreatedBy());
$statement->bindValue(':refresh_type', RefreshTypeConverter::toString($dashboard->getRefresh()->getRefreshType()), \PDO::PARAM_STR);
$statement->bindValue(':refresh_interval', $dashboard->getRefresh()->getRefreshInterval(), \PDO::PARAM_INT);
}
}
}
| 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/Repository/DbReadDashboardPanelRepository.php | centreon/src/Core/Dashboard/Infrastructure/Repository/DbReadDashboardPanelRepository.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\Repository;
use Assert\AssertionFailedException;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Repository\RepositoryException;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Core\Dashboard\Application\Repository\ReadDashboardPanelRepositoryInterface;
use Core\Dashboard\Domain\Model\DashboardPanel;
/**
* @phpstan-type DashboardPanelResultSet array{
* id: int,
* name: string,
* layout_x: int,
* layout_y: int,
* layout_width: int,
* layout_height: int,
* layout_min_height: int,
* layout_min_width: int,
* widget_type: string,
* widget_settings: string
* }
*/
class DbReadDashboardPanelRepository extends AbstractRepositoryDRB implements ReadDashboardPanelRepositoryInterface
{
use LoggerTrait;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* {@inheritDoc}
*/
public function findPanelIdsByDashboardId(int $dashboardId): array
{
$sql = <<<'SQL'
SELECT `id`
FROM `:db`.`dashboard_panel`
WHERE `dashboard_id` = :dashboard_id
SQL;
// Prepare SQL + bind values
$statement = $this->db->prepare($this->translateDbName($sql));
$statement->bindValue(':dashboard_id', $dashboardId, \PDO::PARAM_INT);
$statement->setFetchMode(\PDO::FETCH_NUM);
$statement->execute();
// Retrieve data
$ids = [];
foreach ($statement as $result) {
/** @var array{int} $result */
$ids[] = (int) $result[0];
}
return $ids;
}
/**
* {@inheritDoc}
*/
public function findPanelsByDashboardId(int $dashboardId): array
{
$sql = <<<'SQL'
SELECT
`id`,
`name`,
`layout_x`,
`layout_y`,
`layout_width`,
`layout_height`,
`layout_min_width`,
`layout_min_height`,
`widget_type`,
`widget_settings`
FROM
`:db`.`dashboard_panel`
WHERE
`dashboard_id` = :dashboard_id
ORDER BY
`id`
SQL;
// Prepare SQL + bind values
$statement = $this->db->prepare($this->translateDbName($sql));
$statement->bindValue(':dashboard_id', $dashboardId, \PDO::PARAM_INT);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
// Retrieve data
$panels = [];
foreach ($statement as $result) {
/** @var DashboardPanelResultSet $result */
$panels[] = $this->createDashboardPanelFromArray($result);
}
return $panels;
}
/**
* @param array $result
*
* @phpstan-param DashboardPanelResultSet $result
*
* @throws RepositoryException
* @throws AssertionFailedException
*
* @return DashboardPanel
*/
private function createDashboardPanelFromArray(array $result): DashboardPanel
{
return new DashboardPanel(
id: $result['id'],
name: $result['name'],
widgetType: $result['widget_type'],
widgetSettings: $this->jsonDecodeWidgetSettings($result['widget_settings']),
layoutX: $result['layout_x'],
layoutY: $result['layout_y'],
layoutWidth: $result['layout_width'],
layoutHeight: $result['layout_height'],
layoutMinWidth: $result['layout_min_width'],
layoutMinHeight: $result['layout_min_height'],
);
}
/**
* @param string $settings
*
* @throws RepositoryException
*
* @return array<mixed>
*/
private function jsonDecodeWidgetSettings(string $settings): array
{
if ($settings === '') {
return [];
}
try {
$array = json_decode($settings, true, 512, JSON_THROW_ON_ERROR);
if (\is_array($array)) {
return $array;
}
} catch (\JsonException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
throw new RepositoryException('Dashboard widget settings could not be JSON decoded.', $ex->getCode(), $ex);
}
throw new RepositoryException('Dashboard widget settings are not stored as a valid JSON string in a valid "array" form.');
}
}
| 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/Repository/DbReadDashboardRepository.php | centreon/src/Core/Dashboard/Infrastructure/Repository/DbReadDashboardRepository.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\Repository;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Common\Infrastructure\Repository\RepositoryTrait;
use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait;
use Core\Dashboard\Application\Repository\ReadDashboardRepositoryInterface;
use Core\Dashboard\Domain\Model\Dashboard;
use Core\Dashboard\Domain\Model\Refresh;
use Core\Dashboard\Infrastructure\Model\RefreshTypeConverter;
use Core\Media\Domain\Model\Media;
use Utility\SqlConcatenator;
/**
* @phpstan-type DashboardResultSet array{
* id: int,
* name: string,
* description: ?string,
* created_by: int,
* updated_by: int,
* created_at: int,
* updated_at: int,
* refresh_type: string,
* refresh_interval: ?int
* }
* @phpstan-type _DashboardThumbnailSet array{
* dashboard_id: int,
* id: int,
* name: string,
* directory: string,
* }
*/
class DbReadDashboardRepository extends AbstractRepositoryRDB implements ReadDashboardRepositoryInterface
{
use LoggerTrait;
use RepositoryTrait;
use SqlMultipleBindTrait;
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function findThumbnailByDashboardId(int $dashboardId): ?Media
{
$query = <<<'SQL'
SELECT
images.img_id AS `id`,
images.img_path AS `name`,
directories.dir_name AS `directory`
FROM `:db`.view_img images
LEFT JOIN `:db`.dashboard_thumbnail_relation dtr
ON dtr.img_id = images.img_id
LEFT JOIN `:db`.view_img_dir_relation idr
ON idr.img_img_id = dtr.img_id
LEFT JOIN `:db`.view_img_dir directories
ON directories.dir_id = idr.dir_dir_parent_id
WHERE dtr.dashboard_id = :dashboardId
SQL;
$statement = $this->db->prepare($this->translateDbName($query));
$statement->bindValue(':dashboardId', $dashboardId, \PDO::PARAM_INT);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
/** @var null|false|_DashboardThumbnailSet $data */
$data = $statement->fetch(\PDO::FETCH_ASSOC);
return $data ? $this->createThumbnailFromArray($data) : null;
}
/**
* @inheritDoc
*/
public function findThumbnailsByDashboardIds(array $dashboardIds): array
{
$thumbnails = [];
if ($dashboardIds === []) {
return $thumbnails;
}
[$bindValues, $bindQuery] = $this->createMultipleBindQuery($dashboardIds, ':dashboard');
$query = <<<SQL
SELECT
images.img_id AS `id`,
images.img_path AS `name`,
directories.dir_name AS `directory`,
dtr.dashboard_id
FROM `:db`.view_img images
LEFT JOIN `:db`.dashboard_thumbnail_relation dtr
ON dtr.img_id = images.img_id
LEFT JOIN `:db`.view_img_dir_relation idr
ON idr.img_img_id = dtr.img_id
LEFT JOIN `:db`.view_img_dir directories
ON directories.dir_id = idr.dir_dir_parent_id
WHERE dtr.dashboard_id IN ({$bindQuery})
SQL;
$statement = $this->db->prepare($this->translateDbName($query));
foreach ($bindValues as $index => $value) {
$statement->bindValue($index, $value, \PDO::PARAM_INT);
}
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
foreach ($statement as $record) {
/** @var _DashboardThumbnailSet $record */
$thumbnails[(int) $record['dashboard_id']] = $this->createThumbnailFromArray($record);
}
return $thumbnails;
}
/**
* @inheritDoc
*/
public function existsOne(int $dashboardId): bool
{
$query = <<<'SQL'
SELECT
1
FROM
`:db`.`dashboard` d
WHERE
d.id = :dashboard_id
SQL;
$statement = $this->db->prepare($this->translateDbName($query));
$statement->bindValue(':dashboard_id', $dashboardId, \PDO::PARAM_INT);
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* @inheritDoc
*/
public function findOne(int $dashboardId): ?Dashboard
{
$query = <<<'SQL'
SELECT
d.id,
d.name,
d.description,
d.created_by,
d.updated_by,
d.created_at,
d.updated_at,
d.refresh_type,
d.refresh_interval
FROM
`:db`.`dashboard` d
WHERE
d.id = :dashboard_id
SQL;
$statement = $this->db->prepare($this->translateDbName($query));
$statement->bindValue(':dashboard_id', $dashboardId, \PDO::PARAM_INT);
$statement->execute();
/** @var null|false|DashboardResultSet $data */
$data = $statement->fetch(\PDO::FETCH_ASSOC);
return $data ? $this->createDashboardFromArray($data) : null;
}
/**
* @inheritDoc
*/
public function existsOneByContact(int $dashboardId, ContactInterface $contact): bool
{
$query = <<<'SQL'
SELECT
1
FROM `:db`.`dashboard` d
LEFT JOIN (
SELECT DISTINCT dcgr.`dashboard_id` as `id`
FROM `:db`.`dashboard_contactgroup_relation` dcgr
INNER JOIN `:db`.`contactgroup` cg ON cg.`cg_id`=dcgr.`contactgroup_id`
INNER JOIN `:db`.`contactgroup_contact_relation` cgcr ON cg.`cg_id`=cgcr.`contactgroup_cg_id`
WHERE dcgr.`dashboard_id` = :dashboard_id
AND cgcr.`contact_contact_id` = :contact_id
) has_contactgroup_share USING (`id`)
LEFT JOIN (
SELECT dcr.`dashboard_id` as `id`
FROM `:db`.`dashboard_contact_relation` dcr
WHERE dcr.`dashboard_id` = :dashboard_id
AND dcr.`contact_id` = :contact_id
) has_contact_share USING (`id`)
WHERE
d.id = :dashboard_id
AND (has_contact_share.id IS NOT NULL OR has_contactgroup_share.id IS NOT NULL)
SQL;
$statement = $this->db->prepare($this->translateDbName($query));
$statement->bindValue(':dashboard_id', $dashboardId, \PDO::PARAM_INT);
$statement->bindValue(':contact_id', $contact->getId(), \PDO::PARAM_INT);
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* @inheritDoc
*/
public function findOneByContact(int $dashboardId, ContactInterface $contact): ?Dashboard
{
$query = <<<'SQL'
SELECT
d.id,
d.name,
d.description,
d.created_by,
d.updated_by,
d.created_at,
d.updated_at,
d.refresh_type,
d.refresh_interval
FROM `:db`.`dashboard` d
LEFT JOIN (
SELECT DISTINCT dcgr.`dashboard_id` as `id`
FROM `:db`.`dashboard_contactgroup_relation` dcgr
INNER JOIN `:db`.`contactgroup` cg ON cg.`cg_id`=dcgr.`contactgroup_id`
INNER JOIN `:db`.`contactgroup_contact_relation` cgcr ON cg.`cg_id`=cgcr.`contactgroup_cg_id`
WHERE dcgr.`dashboard_id` = :dashboard_id
AND cgcr.`contact_contact_id` = :contact_id
) has_contactgroup_share USING (`id`)
LEFT JOIN (
SELECT dcr.`dashboard_id` as `id`
FROM `:db`.`dashboard_contact_relation` dcr
WHERE dcr.`dashboard_id` = :dashboard_id
AND dcr.`contact_id` = :contact_id
) has_contact_share USING (`id`)
WHERE
d.id = :dashboard_id
AND (has_contact_share.id IS NOT NULL OR has_contactgroup_share.id IS NOT NULL)
SQL;
$statement = $this->db->prepare($this->translateDbName($query));
$statement->bindValue(':dashboard_id', $dashboardId, \PDO::PARAM_INT);
$statement->bindValue(':contact_id', $contact->getId(), \PDO::PARAM_INT);
$statement->execute();
/** @var null|false|DashboardResultSet $data */
$data = $statement->fetch(\PDO::FETCH_ASSOC);
return $data ? $this->createDashboardFromArray($data) : null;
}
/**
* @inheritDoc
*/
public function findByRequestParameter(
?RequestParametersInterface $requestParameters,
): array {
return $this->findDashboards(
$this->getFindDashboardConcatenator(null),
$requestParameters
);
}
/**
* @inheritDoc
*/
public function findByRequestParameterAndContact(
?RequestParametersInterface $requestParameters,
ContactInterface $contact,
): array {
return $this->findDashboards(
$this->getFindDashboardConcatenator($contact->getId()),
$requestParameters
);
}
/**
* @inheritDoc
*/
public function findByIds(array $ids): array
{
$bind = [];
foreach ($ids as $key => $id) {
$bind[':id_' . $key] = $id;
}
if ($bind === []) {
return [];
}
$dashboardIdsAsString = implode(', ', array_keys($bind));
$query = <<<SQL
SELECT
d.id,
d.name,
d.description,
d.created_by,
d.updated_by,
d.created_at,
d.updated_at,
d.refresh_type,
d.refresh_interval
FROM `:db`.`dashboard` d
WHERE d.id IN ({$dashboardIdsAsString})
SQL;
$statement = $this->db->prepare($this->translateDbName($query));
foreach ($bind as $token => $id) {
$statement->bindValue($token, $id, \PDO::PARAM_INT);
}
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
// Retrieve data
$dashboards = [];
foreach ($statement as $result) {
/** @var DashboardResultSet $result */
$dashboards[] = $this->createDashboardFromArray($result);
}
return $dashboards;
}
/**
* @inheritDoc
*/
public function findByIdsAndContactId(array $dashboardIds, int $contactId): array
{
$bind = [];
foreach ($dashboardIds as $key => $id) {
$bind[':id_' . $key] = $id;
}
if ($bind === []) {
return [];
}
$dashboardIdsAsString = implode(', ', array_keys($bind));
$query = <<<SQL
SELECT
d.id,
d.name,
d.description,
d.created_by,
d.updated_by,
d.created_at,
d.updated_at,
d.refresh_type,
d.refresh_interval
FROM `:db`.`dashboard` d
LEFT JOIN `:db`.dashboard_contact_relation dcr
ON d.id = dcr.dashboard_id
LEFT JOIN `:db`.dashboard_contactgroup_relation dcgr
ON d.id = dcgr.dashboard_id
WHERE d.id IN ({$dashboardIdsAsString})
AND (dcr.contact_id = :contactId
OR dcgr.contactgroup_id IN (SELECT contactgroup_cg_id FROM `:db`.contactgroup_contact_relation WHERE contact_contact_id = :contactId))
SQL;
$statement = $this->db->prepare($this->translateDbName($query));
foreach ($bind as $token => $id) {
$statement->bindValue($token, $id, \PDO::PARAM_INT);
}
$statement->bindValue(':contactId', $contactId, \PDO::PARAM_INT);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
// Retrieve data
$dashboards = [];
foreach ($statement as $result) {
/** @var DashboardResultSet $result */
$dashboards[] = $this->createDashboardFromArray($result);
}
return $dashboards;
}
/**
* @param _DashboardThumbnailSet $record
*
* @return Media
*/
private function createThumbnailFromArray(array $record): Media
{
return new Media(
(int) $record['id'],
$record['name'],
$record['directory'],
comment: null,
data: null
);
}
/**
* @param SqlConcatenator $concatenator
* @param RequestParametersInterface|null $requestParameters
*
* @throws \Throwable
*
* @return list<Dashboard>
*/
private function findDashboards(
SqlConcatenator $concatenator,
?RequestParametersInterface $requestParameters,
): array {
// If we use RequestParameters
$sqlTranslator = $requestParameters ? new SqlRequestParametersTranslator($requestParameters) : null;
$sqlTranslator?->setConcordanceArray([
'id' => 'd.id',
'name' => 'd.name',
'created_at' => 'd.created_at',
'updated_at' => 'd.updated_at',
'created_by' => 'c.contact_name',
]);
$concatenator->appendJoins(
<<<'SQL'
LEFT JOIN contact c
ON d.created_by = c.contact_id
SQL
);
// Update the SQL string builder with the RequestParameters through SqlRequestParametersTranslator
$sqlTranslator?->translateForConcatenator($concatenator);
// Prepare SQL + bind values
$statement = $this->db->prepare($this->translateDbName($concatenator->concatAll()));
$sqlTranslator?->bindSearchValues($statement);
$concatenator->bindValuesToStatement($statement);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
// Calculate the number of rows for the pagination.
$sqlTranslator?->calculateNumberOfRows($this->db);
// Retrieve data
$dashboards = [];
foreach ($statement as $result) {
/** @var DashboardResultSet $result */
$dashboards[] = $this->createDashboardFromArray($result);
}
return $dashboards;
}
/**
* @param int|null $contactId
*
* @return SqlConcatenator
*/
private function getFindDashboardConcatenator(?int $contactId): SqlConcatenator
{
$concatenator = (new SqlConcatenator())
->defineSelect(
<<<'SQL'
SELECT
d.id,
d.name,
d.description,
d.created_by,
d.updated_by,
d.created_at,
d.updated_at,
d.refresh_type,
d.refresh_interval
SQL
)
->defineFrom(
<<<'SQL'
FROM
`:db`.`dashboard` d
SQL
)
->defineOrderBy(
<<<'SQL'
ORDER BY d.name ASC
SQL
);
if ($contactId) {
$concatenator->appendJoins(
<<<'SQL'
LEFT JOIN (
SELECT DISTINCT dcgr.`dashboard_id` as `id`
FROM `:db`.`dashboard_contactgroup_relation` dcgr
INNER JOIN `:db`.`contactgroup` cg ON cg.`cg_id`=dcgr.`contactgroup_id`
INNER JOIN `:db`.`contactgroup_contact_relation` cgcr ON cg.`cg_id`=cgcr.`contactgroup_cg_id`
WHERE cgcr.`contact_contact_id` = :contact_id
) has_contactgroup_share USING (`id`)
LEFT JOIN (
SELECT dcr.`dashboard_id` as `id`
FROM `:db`.`dashboard_contact_relation` dcr
WHERE dcr.`contact_id` = :contact_id
) has_contact_share USING (`id`)
SQL
);
$concatenator->appendWhere(
<<<'SQL'
WHERE (has_contact_share.id IS NOT NULL OR has_contactgroup_share.id IS NOT NULL)
SQL
);
$concatenator->storeBindValue(':contact_id', $contactId, \PDO::PARAM_INT);
}
return $concatenator;
}
/**
* @phpstan-param DashboardResultSet $result
*
* @param array $result
*
* @throws \ValueError
* @throws AssertionFailedException
* @throws \InvalidArgumentException
*
* @return Dashboard
*/
private function createDashboardFromArray(array $result): Dashboard
{
$dashboard = new Dashboard(
id: $result['id'],
name: $result['name'],
createdBy: $result['created_by'],
updatedBy: $result['updated_by'],
createdAt: $this->timestampToDateTimeImmutable($result['created_at']),
updatedAt: $this->timestampToDateTimeImmutable($result['updated_at']),
refresh: new Refresh(
RefreshTypeConverter::fromString((string) $result['refresh_type']),
$result['refresh_interval'],
)
);
if ($result['description'] !== null) {
$dashboard->setDescription($result['description']);
}
return $dashboard;
}
}
| 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/Repository/DbWriteDashboardPanelRepository.php | centreon/src/Core/Dashboard/Infrastructure/Repository/DbWriteDashboardPanelRepository.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\Repository;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Repository\RepositoryException;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Core\Dashboard\Application\Repository\WriteDashboardPanelRepositoryInterface;
use Core\Dashboard\Domain\Model\DashboardPanel;
use Core\Dashboard\Domain\Model\NewDashboardPanel;
class DbWriteDashboardPanelRepository extends AbstractRepositoryDRB implements WriteDashboardPanelRepositoryInterface
{
use LoggerTrait;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
public function deletePanel(int $panelId): void
{
$this->info('Delete dashboard panel', ['id' => $panelId]);
$query = <<<'SQL'
DELETE FROM `:db`.`dashboard_panel`
WHERE id = :panel_id
SQL;
$statement = $this->db->prepare($this->translateDbName($query));
$statement->bindValue(':panel_id', $panelId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* {@inheritDoc}
*
* @throws \PDOException
* @throws RepositoryException
*/
public function addPanel(int $dashboardId, NewDashboardPanel $newPanel): int
{
$insert = <<<'SQL'
INSERT INTO `:db`.`dashboard_panel`
(
`dashboard_id`,
`name`,
`layout_x`,
`layout_y`,
`layout_width`,
`layout_height`,
`layout_min_width`,
`layout_min_height`,
`widget_type`,
`widget_settings`
)
VALUES
(
:dashboard_id,
:name,
:layout_x,
:layout_y,
:layout_width,
:layout_height,
:layout_min_width,
:layout_min_height,
:widget_type,
:widget_settings
)
SQL;
$statement = $this->db->prepare($this->translateDbName($insert));
$this->bindValuesOfPanel($statement, $dashboardId, $newPanel);
$statement->execute();
return (int) $this->db->lastInsertId();
}
/**
* {@inheritDoc}
*
* @throws \PDOException
* @throws \ValueError
*/
public function updatePanel(int $dashboardId, DashboardPanel $panel): void
{
$update = <<<'SQL'
UPDATE `:db`.`dashboard_panel`
SET
`name` = :name,
`layout_x` = :layout_x,
`layout_y` = :layout_y,
`layout_width` = :layout_width,
`layout_height` = :layout_height,
`layout_min_width` = :layout_min_width,
`layout_min_height` = :layout_min_height,
`widget_type` = :widget_type,
`widget_settings` = :widget_settings
WHERE
`id` = :panel_id AND `dashboard_id` = :dashboard_id
SQL;
$statement = $this->db->prepare($this->translateDbName($update));
$this->bindValuesOfPanel($statement, $dashboardId, $panel);
$statement->execute();
}
/**
* @param \PDOStatement $statement
* @param int $dashboardId
* @param DashboardPanel|NewDashboardPanel $panel
*
* @throws RepositoryException
*/
private function bindValuesOfPanel(
\PDOStatement $statement,
int $dashboardId,
DashboardPanel|NewDashboardPanel $panel,
): void {
$statement->bindValue(':dashboard_id', $dashboardId, \PDO::PARAM_INT);
$statement->bindValue(':name', $panel->getName(), \PDO::PARAM_STR);
$statement->bindValue(':layout_x', $panel->getLayoutX(), \PDO::PARAM_INT);
$statement->bindValue(':layout_y', $panel->getLayoutY(), \PDO::PARAM_INT);
$statement->bindValue(':layout_width', $panel->getLayoutWidth(), \PDO::PARAM_INT);
$statement->bindValue(':layout_height', $panel->getLayoutHeight(), \PDO::PARAM_INT);
$statement->bindValue(':layout_min_width', $panel->getLayoutMinWidth(), \PDO::PARAM_INT);
$statement->bindValue(':layout_min_height', $panel->getLayoutMinHeight(), \PDO::PARAM_INT);
$statement->bindValue(':widget_type', $panel->getWidgetType(), \PDO::PARAM_STR);
$statement->bindValue(':widget_settings', $this->encodeToJson($panel->getWidgetSettings()));
if ($panel instanceof DashboardPanel) {
$statement->bindValue(':panel_id', $panel->getId(), \PDO::PARAM_INT);
}
}
/**
* @param array<mixed> $widgetSettings
*
* @throws RepositoryException
*
* @return string
*/
private function encodeToJson(array $widgetSettings): string
{
try {
return json_encode($widgetSettings, JSON_THROW_ON_ERROR | JSON_PRESERVE_ZERO_FRACTION);
} catch (\JsonException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
throw new RepositoryException('Dashboard widget settings could not be JSON encoded.', $ex->getCode(), $ex);
}
}
}
| 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/Repository/DbReadDashboardPerformanceMetricRepository.php | centreon/src/Core/Dashboard/Infrastructure/Repository/DbReadDashboardPerformanceMetricRepository.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\Repository;
use Adaptation\Database\Connection\Adapter\Pdo\Transformer\PdoParameterTypeTransformer;
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use Core\Common\Domain\Exception\CollectionException;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Common\Domain\Exception\ValueObjectException;
use Core\Dashboard\Application\Repository\ReadDashboardPerformanceMetricRepositoryInterface as RepositoryInterface;
use Core\Dashboard\Domain\Model\Metric\PerformanceMetric;
use Core\Dashboard\Domain\Model\Metric\ResourceMetric;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
/**
* Class
*
* @class DbReadDashboardPerformanceMetricRepository
* @package Core\Dashboard\Infrastructure\Repository
*/
class DbReadDashboardPerformanceMetricRepository extends AbstractRepositoryDRB implements RepositoryInterface
{
/** @var SqlRequestParametersTranslator */
private SqlRequestParametersTranslator $sqlRequestParametersTranslator;
/** @var QueryParameters */
private QueryParameters $queryParameters;
/**
* @param DatabaseConnection $db
* @param array<
* string, array{
* request: string,
* bindValues: array<string, array<int|string, int>>
* }
* > $subRequestsInformation
*/
public function __construct(
DatabaseConnection $db,
private array $subRequestsInformation = [],
) {
$this->db = $db;
$this->queryParameters = new QueryParameters();
}
/**
* @param RequestParametersInterface $requestParameters
*
* @throws RepositoryException
*
* @return ResourceMetric[]
*/
public function findByRequestParameters(RequestParametersInterface $requestParameters): array
{
try {
$request = $this->buildQuery($requestParameters);
$statement = $this->db->prepare($this->translateDbName($request));
$statement = $this->executeQuery($statement);
return $this->buildResourceMetrics($requestParameters, $statement);
} catch (\Throwable $e) {
throw new RepositoryException(
message: 'An error occurred while trying to find performance metrics by request parameters.',
context: ['requestParameters' => $requestParameters->toArray()],
previous: $e
);
}
}
/**
* @param RequestParametersInterface $requestParameters
* @param AccessGroup[] $accessGroups
*
* @throws RepositoryException
*
* @return ResourceMetric[]
*/
public function findByRequestParametersAndAccessGroups(
RequestParametersInterface $requestParameters,
array $accessGroups,
): array {
try {
$request = $this->buildQuery($requestParameters, $accessGroups);
$statement = $this->db->prepare($this->translateDbName($request));
$statement = $this->executeQuery($statement);
return $this->buildResourceMetrics($requestParameters, $statement);
} catch (\Throwable $e) {
throw new RepositoryException(
message: 'An error occurred while trying to find performance metrics by request parameters and access groups.',
context: [
'requestParameters' => $requestParameters->toArray(),
'accessGroups' => array_map(fn ($group) => $group->getId(), $accessGroups),
],
previous: $e
);
}
}
/**
* @param RequestParametersInterface $requestParameters
* @param string $metricName
*
* @throws RepositoryException
*
* @return ResourceMetric[]
*/
public function findByRequestParametersAndMetricName(
RequestParametersInterface $requestParameters,
string $metricName,
): array {
try {
$request = $this->buildQuery($requestParameters, [], true);
$statement = $this->db->prepare($this->translateDbName($request));
$statement = $this->executeQuery($statement, $metricName);
return $this->buildResourceMetrics($requestParameters, $statement);
} catch (\Throwable $e) {
throw new RepositoryException(
message: 'An error occurred while trying to find performance metrics by request parameters and metric name.',
context: [
'requestParameters' => $requestParameters->toArray(),
'metricName' => $metricName,
],
previous: $e
);
}
}
/**
* @param RequestParametersInterface $requestParameters
* @param AccessGroup[] $accessGroups
* @param string $metricName
*
* @throws RepositoryException
*
* @return ResourceMetric[]
*/
public function findByRequestParametersAndAccessGroupsAndMetricName(
RequestParametersInterface $requestParameters,
array $accessGroups,
string $metricName,
): array {
try {
$request = $this->buildQuery($requestParameters, $accessGroups, true);
$statement = $this->db->prepare($this->translateDbName($request));
$statement = $this->executeQuery($statement, $metricName);
return $this->buildResourceMetrics($requestParameters, $statement);
} catch (\Throwable $e) {
throw new RepositoryException(
message: 'An error occurred while trying to find performance metrics by request parameters, access groups and metric name.',
context: [
'requestParameters' => $requestParameters->toArray(),
'accessGroups' => array_map(fn ($group) => $group->getId(), $accessGroups),
'metricName' => $metricName,
],
previous: $e
);
}
}
/**
* build the sub request for service filter.
*
* @param non-empty-array<string> $serviceNames
*
* @return array{
* request: string,
* bindValues: array<string, array<string, int>>
* }
*/
private function buildSubRequestForServiceFilter(array $serviceNames): array
{
$bindServiceNames = [];
foreach ($serviceNames as $key => $serviceName) {
$bindServiceNames[':service_name' . $key] = [$serviceName => \PDO::PARAM_STR];
}
$bindTokens = implode(', ', array_keys($bindServiceNames));
return [
'request' => <<<SQL
AND r.name IN ({$bindTokens})
AND r.type = 0
SQL,
'bindValues' => $bindServiceNames,
];
}
/**
* build the sub request for metaservice filter.
*
* @param non-empty-array<int> $metaserviceIds
*
* @return array{
* request: string,
* bindValues: array<string, int[]>
* }
*/
private function buildSubRequestForMetaserviceFilter(array $metaserviceIds): array
{
$bindMetaserviceIds = [];
foreach ($metaserviceIds as $key => $metaserviceId) {
$bindMetaserviceIds[':metaservice_' . $key] = [$metaserviceId => \PDO::PARAM_INT];
}
$bindTokens = implode(', ', array_keys($bindMetaserviceIds));
return [
'request' => <<<SQL
AND r.internal_id IN ({$bindTokens})
AND r.type = 2
SQL,
'bindValues' => $bindMetaserviceIds,
];
}
/**
* build the sub request for host filter.
*
* @param non-empty-array<int> $hostIds
*
* @return array{
* request: string,
* bindValues: array<string, int[]>
* }
*/
private function buildSubRequestForHostFilter(array $hostIds): array
{
$bindHostIds = [];
foreach ($hostIds as $hostId) {
$bindHostIds[':host_' . $hostId] = [$hostId => \PDO::PARAM_INT];
}
$bindTokens = implode(', ', array_keys($bindHostIds));
return [
'request' => <<<SQL
AND r.parent_id IN ({$bindTokens})
SQL,
'bindValues' => $bindHostIds,
];
}
/**
* build the sub request for host group filter.
*
* @param non-empty-array<int> $hostGroupIds
*
* @return array{
* request: string,
* bindValues: array<string, int[]>
* }
*/
private function buildSubRequestForHostGroupFilter(array $hostGroupIds): array
{
$bindValues = [];
foreach ($hostGroupIds as $hostGroupId) {
$bindValues[':hostgroup_' . $hostGroupId] = [$hostGroupId => \PDO::PARAM_INT];
}
$boundTokens = implode(', ', array_keys($bindValues));
return [
'request' => <<<SQL
SELECT resources.resource_id
FROM `:dbstg`.`resources` resources
LEFT JOIN `:dbstg`.`resources` parent_resource
ON parent_resource.id = resources.parent_id
LEFT JOIN `:dbstg`.resources_tags AS rtags
ON rtags.resource_id = parent_resource.resource_id
INNER JOIN `:dbstg`.tags
ON tags.tag_id = rtags.tag_id
WHERE tags.id IN ({$boundTokens})
AND tags.type = 1
SQL,
'bindValues' => $bindValues,
];
}
/**
* build the sub request for host category filter.
*
* @param non-empty-array<int> $hostCategoryIds
*
* @return array{
* request: string,
* bindValues: array<string, int[]>
* }
*/
private function buildSubRequestForHostCategoryFilter(array $hostCategoryIds): array
{
$bindValues = [];
foreach ($hostCategoryIds as $hostCategoryId) {
$bindValues[':hostcategory_' . $hostCategoryId] = [$hostCategoryId => \PDO::PARAM_INT];
}
$boundTokens = implode(', ', array_keys($bindValues));
return [
'request' => <<<SQL
SELECT resources.resource_id
FROM `:dbstg`.`resources` resources
LEFT JOIN `:dbstg`.`resources` parent_resource
ON parent_resource.id = resources.parent_id
LEFT JOIN `:dbstg`.resources_tags AS rtags
ON rtags.resource_id = parent_resource.resource_id
INNER JOIN `:dbstg`.tags
ON tags.tag_id = rtags.tag_id
WHERE tags.id IN ({$boundTokens})
AND tags.type = 3
SQL,
'bindValues' => $bindValues,
];
}
/**
* build the sub request for service group filter.
*
* @param non-empty-array<int> $serviceGroupIds
*
* @return array{
* request: string,
* bindValues: array<string, int[]>
* }
*/
private function buildSubRequestForServiceGroupFilter(array $serviceGroupIds): array
{
$bindValues = [];
foreach ($serviceGroupIds as $serviceGroupId) {
$bindValues[':servicegroup_' . $serviceGroupId] = [$serviceGroupId => \PDO::PARAM_INT];
}
$boundTokens = implode(', ', array_keys($bindValues));
return [
'request' => <<<SQL
SELECT rtags.resource_id
FROM `:dbstg`.resources_tags AS rtags
INNER JOIN `:dbstg`.tags
ON tags.tag_id = rtags.tag_id
WHERE tags.id IN ({$boundTokens})
AND tags.type = 0
SQL,
'bindValues' => $bindValues,
];
}
/**
* build the sub request for service category filter.
*
* @param non-empty-array<int> $serviceCategoryIds
*
* @return array{
* request: string,
* bindValues: array<string, int[]>
* }
*/
private function buildSubRequestForServiceCategoryFilter(array $serviceCategoryIds): array
{
$bindValues = [];
foreach ($serviceCategoryIds as $serviceCategoryId) {
$bindValues[':servicecategory_' . $serviceCategoryId] = [$serviceCategoryId => \PDO::PARAM_INT];
}
$boundTokens = implode(', ', array_keys($bindValues));
return [
'request' => <<<SQL
SELECT rtags.resource_id
FROM `:dbstg`.resources_tags AS rtags
INNER JOIN `:dbstg`.tags
ON tags.tag_id = rtags.tag_id
WHERE tags.id IN ({$boundTokens})
AND tags.type = 2
SQL,
'bindValues' => $bindValues,
];
}
/**
* Get request and bind values information for each search filter.
*
* @phpstan-param array{
* '$and': array<
* array{
* 'service.name'?: array{'$in': non-empty-array<string>},
* 'metaservice.id'?: array{'$in': non-empty-array<int>},
* 'host.id'?: array{'$in': non-empty-array<int>},
* 'hostgroup.id'?: array{'$in': non-empty-array<int>},
* 'servicegroup.id'?: array{'$in': non-empty-array<int>},
* 'hostcategory.id'?: array{'$in': non-empty-array<int>},
* 'servicecategory.id'?: array{'$in': non-empty-array<int>},
* }
* >
* } $search
*
* @param array<mixed> $search
*
* @return array<
* string, array{
* request: string,
* bindValues: array<string, array<int|string, int>>
* }
* >
*/
private function getSubRequestsInformation(array $search): array
{
$searchParameters = $search['$and'];
$subRequestsInformation = [];
foreach ($searchParameters as $searchParameter) {
if (
array_key_exists('service.name', $searchParameter)
&& array_key_exists('$in', $searchParameter['service.name'])
) {
$subRequestsInformation['service'] = $this->buildSubRequestForServiceFilter(
$searchParameter['service.name']['$in']
);
}
if (
array_key_exists('metaservice.id', $searchParameter)
&& array_key_exists('$in', $searchParameter['metaservice.id'])
) {
$subRequestsInformation['metaservice'] = $this->buildSubRequestForMetaserviceFilter(
$searchParameter['metaservice.id']['$in']
);
}
if (
array_key_exists('host.id', $searchParameter)
&& array_key_exists('$in', $searchParameter['host.id'])
) {
$subRequestsInformation['host'] = $this->buildSubRequestForHostFilter(
$searchParameter['host.id']['$in']
);
}
if (
array_key_exists('hostgroup.id', $searchParameter)
&& array_key_exists('$in', $searchParameter['hostgroup.id'])
) {
$subRequestsInformation['hostgroup'] = $this->buildSubRequestForHostGroupFilter(
$searchParameter['hostgroup.id']['$in']
);
}
if (
array_key_exists('servicegroup.id', $searchParameter)
&& array_key_exists('$in', $searchParameter['servicegroup.id'])
) {
$subRequestsInformation['servicegroup'] = $this->buildSubRequestForServiceGroupFilter(
$searchParameter['servicegroup.id']['$in']
);
}
if (
array_key_exists('hostcategory.id', $searchParameter)
&& array_key_exists('$in', $searchParameter['hostcategory.id'])
) {
$subRequestsInformation['hostcategory'] = $this->buildSubRequestForHostCategoryFilter(
$searchParameter['hostcategory.id']['$in']
);
}
if (
array_key_exists('servicecategory.id', $searchParameter)
&& array_key_exists('$in', $searchParameter['servicecategory.id'])
) {
$subRequestsInformation['servicecategory'] = $this->buildSubRequestForServiceCategoryFilter(
$searchParameter['servicecategory.id']['$in']
);
}
}
return $subRequestsInformation;
}
/**
* Build the subrequest for tags filter.
*
* @param array<
* string, array{
* request: string,
* bindValues: array<string, array<int|string, int>>
* }
* > $subRequestInformation
*
* @return string
*/
private function buildSubRequestForTags(array $subRequestInformation): string
{
$request = '';
$subRequestForTags = array_reduce(array_keys($subRequestInformation), function (array $acc, string $item) use (
$subRequestInformation
) {
if ($item !== 'host' && $item !== 'service' && $item !== 'metric' && $item !== 'metaservice') {
$acc[] = $subRequestInformation[$item];
}
return $acc;
}, []);
if (! empty($subRequestForTags)) {
$subRequests = array_map(fn ($subRequestForTag) => $subRequestForTag['request'], $subRequestForTags);
$request .= ' INNER JOIN (';
$request .= implode(' INTERSECT ', $subRequests);
$request .= ') AS t ON t.resource_id = r.resource_id';
}
return $request;
}
/**
* Build the SQL Query.
*
* @param RequestParametersInterface $requestParameters
* @param AccessGroup[] $accessGroups
* @param bool $hasMetricName
*
* @throws CollectionException
* @throws ValueObjectException
* @return string
*/
private function buildQuery(
RequestParametersInterface $requestParameters,
array $accessGroups = [],
bool $hasMetricName = false,
): string {
$this->sqlRequestParametersTranslator = new SqlRequestParametersTranslator($requestParameters);
$this->sqlRequestParametersTranslator->setConcordanceArray(
['current_value' => 'm.current_value']
);
$request
= <<<'SQL_WRAP'
SELECT SQL_CALC_FOUND_ROWS DISTINCT
m.metric_id, m.metric_name, m.unit_name, m.warn, m.crit, m.current_value, m.warn_low, m.crit_low, m.min,
m.max, r.parent_name, r.name, r.id as service_id, r.parent_id
FROM `:dbstg`.`metrics` AS m
INNER JOIN `:dbstg`.`index_data` AS id ON id.id = m.index_id
INNER JOIN `:dbstg`.`resources` AS r ON r.id = id.service_id
SQL_WRAP;
$accessGroupIds = array_map(
fn ($accessGroup) => $accessGroup->getId(),
$accessGroups
);
if ($accessGroups !== []) {
$request .= ' INNER JOIN `:dbstg`.`centreon_acl` acl
ON acl.service_id = r.id
AND r.type = 0
AND acl.group_id IN (' . implode(',', $accessGroupIds) . ') ';
}
$search = $requestParameters->getSearch();
if ($search !== [] && array_key_exists('$and', $search)) {
$this->subRequestsInformation = $this->getSubRequestsInformation($search);
$request .= $this->buildSubRequestForTags($this->subRequestsInformation);
}
// To add a regex join clause for service name if it exists in the search parameters.
// To patch a bug from top/bottom widget
$serviceRegexWhereClause = $this->addServiceRegexJoinClause($requestParameters);
$request .= ! is_null(
$serviceRegexWhereClause
) ? " {$serviceRegexWhereClause} AND r.enabled = 1" : ' AND r.enabled = 1';
// End of this patch
if ($this->subRequestsInformation !== []) {
$request .= $this->subRequestsInformation['service']['request'] ?? '';
$request .= $this->subRequestsInformation['metaservice']['request'] ?? '';
$request .= $this->subRequestsInformation['host']['request'] ?? '';
}
if ($hasMetricName) {
$request .= ' WHERE m.metric_name = :metricName';
}
$sortRequest = $this->sqlRequestParametersTranslator->translateSortParameterToSql();
$request .= $sortRequest ?? ' ORDER BY m.metric_id ASC';
$request .= $this->sqlRequestParametersTranslator->translatePaginationToSql();
return $request;
}
/**
* Execute the SQL Query.
*
* @param \PDOStatement $statement
* @param string $metricName
*
* @throws \PDOException
*
* @return \PDOStatement
*/
private function executeQuery(\PDOStatement $statement, string $metricName = ''): \PDOStatement
{
$boundValues = [];
if (! empty($metricName)) {
$boundValues[] = [
':metricName' => [$metricName => \PDO::PARAM_STR],
];
}
if ($this->subRequestsInformation !== []) {
foreach ($this->subRequestsInformation as $subRequestInformation) {
$boundValues[] = $subRequestInformation['bindValues'];
}
}
$boundValues = array_merge(...$boundValues);
foreach ($boundValues as $bindToken => $bindValueInformation) {
foreach ($bindValueInformation as $bindValue => $paramType) {
$statement->bindValue($bindToken, $bindValue, $paramType);
}
}
// To add a regex join clause for service name if it exists in the search parameters.
// To patch a bug from top/bottom widget
if (! $this->queryParameters->isEmpty() && $this->queryParameters->has('serviceRegex')) {
$queryParameter = $this->queryParameters->get('serviceRegex');
$statement->bindValue(
param: $queryParameter->getName(),
value: $queryParameter->getValue(),
type: ! is_null($queryParameter->getType())
? PdoParameterTypeTransformer::transformFromQueryParameterType($queryParameter->getType())
: \PDO::PARAM_STR // Default type if not specified
);
}
// End of this patch
$statement->execute();
return $statement;
}
/**
* Create the ResourceMetrics from result of query.
*
* @param RequestParametersInterface $requestParameters
* @param \PDOStatement $statement
*
* @throws \PDOException
*
* @return ResourceMetric[]
*/
private function buildResourceMetrics(
RequestParametersInterface $requestParameters,
\PDOStatement $statement,
): array {
$foundRecords = $this->db->query('SELECT FOUND_ROWS()');
$resourceMetrics = [];
if ($foundRecords !== false && ($total = $foundRecords->fetchColumn()) !== false) {
$requestParameters->setTotal((int) $total);
}
if (($records = $statement->fetchAll(\PDO::FETCH_ASSOC)) !== false) {
$metricsInformation = [];
foreach ($records as $record) {
if (! array_key_exists($record['service_id'], $metricsInformation)) {
$metricsInformation[$record['service_id']] = [
'service_id' => $record['service_id'],
'name' => $record['name'],
'parent_name' => $record['parent_name'],
'parent_id' => $record['parent_id'],
'metrics' => [],
];
}
$metricsInformation[$record['service_id']]['metrics'][] = new PerformanceMetric(
$record['metric_id'],
$record['metric_name'],
$record['unit_name'],
$record['warn'],
$record['crit'],
$record['warn_low'],
$record['crit_low'],
$record['current_value'],
$record['min'],
$record['max']
);
}
foreach ($metricsInformation as $information) {
$resourceMetrics[] = new ResourceMetric(
$information['service_id'],
$information['name'],
$information['parent_name'],
$information['parent_id'],
$information['metrics']
);
}
}
return $resourceMetrics;
}
/**
* To add a regex join clause for service name if it exists in the search parameters.
* To patch a bug from top/bottom widget
*
* @param RequestParametersInterface $requestParameters
*
* @throws CollectionException
* @throws ValueObjectException
* @return string|null
*/
private function addServiceRegexJoinClause(RequestParametersInterface $requestParameters): ?string
{
if (! $requestParameters->hasSearchParameter('name')) {
return null;
}
$searchParameters = $requestParameters->extractSearchNames(true);
if (($searchParameters['name'] ?? []) === [] || count($searchParameters['name']) !== 1) {
return null;
}
$nameParameter = $searchParameters['name'];
if (! isset($nameParameter[RequestParameters::OPERATOR_REGEXP])) {
return null;
}
$value = $nameParameter[RequestParameters::OPERATOR_REGEXP];
$this->queryParameters->add(
'serviceRegex',
QueryParameter::string(':serviceRegex', $value)
);
return ' AND r.name REGEXP :serviceRegex';
}
}
| 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/ShareDashboardRequestTransformer.php | centreon/src/Core/Dashboard/Infrastructure/API/ShareDashboard/ShareDashboardRequestTransformer.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 Core\Dashboard\Application\UseCase\ShareDashboard\ShareDashboardRequest;
abstract readonly class ShareDashboardRequestTransformer
{
/**
* @param ShareDashboardInput $input
* @return ShareDashboardRequest
*/
public static function transform(
ShareDashboardInput $input,
): ShareDashboardRequest {
$request = new ShareDashboardRequest();
$request->contacts = $input->contacts;
$request->contactGroups = $input->contactGroups;
return $request;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.