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/Severity/RealTime/Infrastructure/Repository/DbSeverityFactory.php
centreon/src/Core/Severity/RealTime/Infrastructure/Repository/DbSeverityFactory.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Severity\RealTime\Infrastructure\Repository; use Core\Domain\RealTime\Model\Icon; use Core\Severity\RealTime\Domain\Model\Severity; class DbSeverityFactory { /** * @param array<string,int|string|null> $record * * @return Severity */ public static function createFromRecord(array $record): Severity { /** @var string|null */ $iconName = $record['icon_name']; $icon = (new Icon()) ->setId((int) $record['icon_id']) ->setName($iconName) ->setUrl($record['icon_directory'] . DIRECTORY_SEPARATOR . $record['icon_path']); return new Severity( (int) $record['id'], (string) $record['name'], (int) $record['level'], (int) $record['type'], $icon ); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Severity/RealTime/Infrastructure/API/FindSeverity/FindHostSeverityController.php
centreon/src/Core/Severity/RealTime/Infrastructure/API/FindSeverity/FindHostSeverityController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Severity\RealTime\Infrastructure\API\FindSeverity; use Centreon\Application\Controller\AbstractController; use Core\Severity\RealTime\Application\UseCase\FindSeverity\FindSeverity; use Core\Severity\RealTime\Application\UseCase\FindSeverity\FindSeverityPresenterInterface; use Core\Severity\RealTime\Domain\Model\Severity; final class FindHostSeverityController extends AbstractController { /** * @param FindSeverity $useCase * @param FindSeverityPresenterInterface $presenter * * @return object */ public function __invoke(FindSeverity $useCase, FindSeverityPresenterInterface $presenter): object { $this->denyAccessUnlessGrantedForApiRealtime(); $useCase(Severity::HOST_SEVERITY_TYPE_ID, $presenter); return $presenter->show(); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Severity/RealTime/Infrastructure/API/FindSeverity/FindServiceSeverityController.php
centreon/src/Core/Severity/RealTime/Infrastructure/API/FindSeverity/FindServiceSeverityController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Severity\RealTime\Infrastructure\API\FindSeverity; use Centreon\Application\Controller\AbstractController; use Core\Severity\RealTime\Application\UseCase\FindSeverity\FindSeverity; use Core\Severity\RealTime\Application\UseCase\FindSeverity\FindSeverityPresenterInterface; use Core\Severity\RealTime\Domain\Model\Severity; final class FindServiceSeverityController extends AbstractController { /** * @param FindSeverity $useCase * @param FindSeverityPresenterInterface $presenter * * @return object */ public function __invoke(FindSeverity $useCase, FindSeverityPresenterInterface $presenter): object { $this->denyAccessUnlessGrantedForApiRealtime(); $useCase(Severity::SERVICE_SEVERITY_TYPE_ID, $presenter); return $presenter->show(); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Severity/RealTime/Infrastructure/API/FindSeverity/FindSeverityPresenter.php
centreon/src/Core/Severity/RealTime/Infrastructure/API/FindSeverity/FindSeverityPresenter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Severity\RealTime\Infrastructure\API\FindSeverity; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\Severity\RealTime\Application\UseCase\FindSeverity\FindSeverityPresenterInterface; class FindSeverityPresenter extends AbstractPresenter implements FindSeverityPresenterInterface { /** * @param RequestParametersInterface $requestParameters * @param PresenterFormatterInterface $presenterFormatter */ public function __construct( private RequestParametersInterface $requestParameters, protected PresenterFormatterInterface $presenterFormatter, ) { } /** * @param mixed $data */ public function present(mixed $data): void { parent::present([ 'result' => $data->severities, 'meta' => $this->requestParameters->toArray(), ]); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Application/UseCase/GetHostGroup/GetHostGroup.php
centreon/src/Core/HostGroup/Application/UseCase/GetHostGroup/GetHostGroup.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Application\UseCase\GetHostGroup; 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\Application\Common\UseCase\ResponseStatusInterface; use Core\Contact\Application\Repository\ReadContactGroupRepositoryInterface; use Core\Contact\Domain\AdminResolver; use Core\Host\Application\Repository\ReadHostRepositoryInterface; use Core\HostGroup\Application\Exceptions\HostGroupException; use Core\HostGroup\Application\Repository\ReadHostGroupRepositoryInterface; use Core\Media\Application\Repository\ReadMediaRepositoryInterface; use Core\ResourceAccess\Application\Repository\ReadResourceAccessRepositoryInterface; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\HostGroupFilterType; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; final class GetHostGroup { use LoggerTrait; public function __construct( private readonly ReadHostGroupRepositoryInterface $readHostGroupRepository, private readonly ReadHostRepositoryInterface $readHostRepository, private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository, private readonly ReadResourceAccessRepositoryInterface $readResourceAccessRepository, private readonly ReadMediaRepositoryInterface $readMediaRepository, private readonly ReadContactGroupRepositoryInterface $readContactGroupRepository, private readonly bool $isCloudPlatform, private readonly ContactInterface $user, private readonly AdminResolver $adminResolver, ) { } public function __invoke(int $hostGroupId): GetHostGroupResponse|ResponseStatusInterface { try { if ($this->adminResolver->isAdmin($this->user)) { $hostGroup = $this->readHostGroupRepository->findOne($hostGroupId); if ($hostGroup === null) { return new NotFoundResponse('Host group'); } $hosts = $this->readHostRepository->findByHostGroup($hostGroupId); $icon = $hostGroup->getIconId() === null ? null : $this->readMediaRepository->findById($hostGroup->getIconId()); $rules = $this->isCloudPlatform ? $this->readResourceAccessRepository->findRuleByResourceId(HostGroupFilterType::TYPE_NAME, $hostGroupId) : []; } else { $accessGroups = $this->readAccessGroupRepository->findByContact($this->user); $hostGroup = $this->readHostGroupRepository->findOneByAccessGroups($hostGroupId, $accessGroups); if ($hostGroup === null) { return new NotFoundResponse('Host group'); } $hosts = $this->readHostRepository->findByHostGroupAndAccessGroups($hostGroupId, $accessGroups); $icon = $hostGroup->getIconId() === null ? null : $this->readMediaRepository->findById($hostGroup->getIconId()); $rules = []; if ($this->isCloudPlatform) { $rules = array_unique( array_merge( $this->readResourceAccessRepository->findRuleByResourceIdAndContactId( HostGroupFilterType::TYPE_NAME, $hostGroupId, $this->user->getId() ), $this->readResourceAccessRepository->findRuleByResourceIdAndContactGroups( HostGroupFilterType::TYPE_NAME, $hostGroupId, $this->readContactGroupRepository->findAllByUserId($this->user->getId()) ), ), SORT_REGULAR ); } } return new GetHostGroupResponse($hostGroup, $hosts, $rules, $icon); } catch (\Throwable $ex) { $this->error( "Error while retrieving a host group: {$ex->getMessage()}", [ 'user_id' => $this->user->getId(), 'hostgroup_id' => $hostGroupId, 'exception' => ['message' => $ex->getMessage(), 'trace' => $ex->getTraceAsString()], ] ); return new ErrorResponse(HostGroupException::errorWhileRetrieving()->getMessage()); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Application/UseCase/GetHostGroup/GetHostGroupResponse.php
centreon/src/Core/HostGroup/Application/UseCase/GetHostGroup/GetHostGroupResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Application\UseCase\GetHostGroup; use Core\Application\Common\UseCase\StandardResponseInterface; use Core\Common\Domain\SimpleEntity; use Core\HostGroup\Domain\Model\HostGroup; use Core\Media\Domain\Model\Media; use Core\ResourceAccess\Domain\Model\TinyRule; final class GetHostGroupResponse implements StandardResponseInterface { /** * @param HostGroup $hostgroup * @param SimpleEntity[] $hosts * @param TinyRule[] $rules * @param ?Media $icon */ public function __construct( public readonly HostGroup $hostgroup, public readonly array $hosts = [], public readonly array $rules = [], public readonly ?Media $icon = null, ) { } /** * @inheritDoc */ public function getData(): mixed { 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/HostGroup/Application/UseCase/AddHostGroup/AddHostGroupValidator.php
centreon/src/Core/HostGroup/Application/UseCase/AddHostGroup/AddHostGroupValidator.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Application\UseCase\AddHostGroup; use Centreon\Domain\Configuration\Icon\IconException; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Log\LoggerTrait; use Core\Contact\Application\Repository\ReadContactGroupRepositoryInterface; use Core\Contact\Domain\AdminResolver; use Core\Host\Application\Exception\HostException; use Core\Host\Application\Repository\ReadHostRepositoryInterface; use Core\HostGroup\Application\Exceptions\HostGroupException; use Core\HostGroup\Application\Repository\ReadHostGroupRepositoryInterface; use Core\ResourceAccess\Application\Exception\RuleException; use Core\ResourceAccess\Application\Repository\ReadResourceAccessRepositoryInterface; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\ViewImg\Application\Repository\ReadViewImgRepositoryInterface; class AddHostGroupValidator { use LoggerTrait; private bool $isUserAdmin = false; public function __construct( private readonly ReadHostGroupRepositoryInterface $readHostGroupRepository, private readonly ReadResourceAccessRepositoryInterface $readResourceAccessRepository, private readonly ReadContactGroupRepositoryInterface $readContactGroupRepository, private readonly ReadHostRepositoryInterface $readHostRepository, private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository, private readonly ReadViewImgRepositoryInterface $readViewImgRepository, private readonly ContactInterface $user, private readonly AdminResolver $adminResolver, ) { $this->isUserAdmin = $this->adminResolver->isAdmin($this->user); } /** * @param string $hostGroupName * * @throws HostGroupException * * @throws \Throwable */ public function assertNameDoesNotAlreadyExists(string $hostGroupName): void { if ($this->readHostGroupRepository->nameAlreadyExists($hostGroupName)) { throw HostGroupException::nameAlreadyExists($hostGroupName); } } /** * Assert that given host ids exists (filtered by access groups for non admin users) * * @param int[] $hostIds * @throws \Throwable|HostException */ public function assertHostsExist(array $hostIds): void { $unexistentHosts = $this->isUserAdmin ? array_diff($hostIds, $this->readHostRepository->exist($hostIds)) : array_filter($hostIds, fn ($hostId) => ! $this->readHostRepository->existsByAccessGroups( $hostId, $this->readAccessGroupRepository->findByContact($this->user) )); if ($unexistentHosts !== []) { $this->warning( 'Some hosts are not accessible by the user, they will not be linked to the host group.', ['unexistentHosts' => $unexistentHosts] ); throw HostException::idsDoNotExist('hosts', $unexistentHosts); } } /** * Assert That given Resource Access Rule IDs exists. * - Check that ids globally exists * - Check that ids exists for the contact * - Check that ids exists for the contact contact groups. * * @param int[] $resourceAccessRuleIds * * @throws RuleException */ public function assertResourceAccessRulesExist(array $resourceAccessRuleIds): void { $unexistentAccessRules = array_diff( $resourceAccessRuleIds, $this->readResourceAccessRepository->exist($resourceAccessRuleIds) ); if ($unexistentAccessRules !== []) { throw RuleException::idsDoNotExist('rules', $unexistentAccessRules); } if (! $this->isUserAdmin) { $existentRulesByContact = $this->readResourceAccessRepository->existByContact( ruleIds: $resourceAccessRuleIds, userId: $this->user->getId() ); $existentRulesByContactGroup = $this->readResourceAccessRepository->existByContactGroup( ruleIds: $resourceAccessRuleIds, contactGroups: $this->readContactGroupRepository->findAllByUserId($this->user->getId()) ); $existentRules = array_unique( array_merge($existentRulesByContact, $existentRulesByContactGroup) ); if ([] !== $unexistentAccessRulesByContact = array_diff($resourceAccessRuleIds, $existentRules)) { throw RuleException::idsDoNotExist('rules', $unexistentAccessRulesByContact); } if ($existentRules === []) { throw HostGroupException::errorResourceAccessRulesEmpty(); } } } /** * Assert that given icon id exists. * * @param int $iconId * * @throws IconException */ public function assertIconExists(int $iconId): void { if (! $this->readViewImgRepository->existsOne($iconId)) { throw IconException::iconDoesNotExists($iconId); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Application/UseCase/AddHostGroup/AddHostGroupRequest.php
centreon/src/Core/HostGroup/Application/UseCase/AddHostGroup/AddHostGroupRequest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Application\UseCase\AddHostGroup; final class AddHostGroupRequest { /** * @param string $name * @param string $alias * @param null|string $geoCoords * @param string $comment * @param int|null $iconId * @param int[] $hosts * @param int[] $resourceAccessRules * @return void */ public function __construct( public string $name = '', public string $alias = '', public ?string $geoCoords = null, public string $comment = '', public ?int $iconId = null, public array $hosts = [], public array $resourceAccessRules = [], ) { } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Application/UseCase/AddHostGroup/AddHostGroupResponse.php
centreon/src/Core/HostGroup/Application/UseCase/AddHostGroup/AddHostGroupResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Application\UseCase\AddHostGroup; use Core\Application\Common\UseCase\StandardResponseInterface; use Core\HostGroup\Domain\Model\HostGroupRelation; final readonly class AddHostGroupResponse implements StandardResponseInterface { public function __construct(private readonly HostGroupRelation $data) { } /** * @return HostGroupRelation */ public function getData(): HostGroupRelation { return $this->data; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Application/UseCase/AddHostGroup/AddHostGroup.php
centreon/src/Core/HostGroup/Application/UseCase/AddHostGroup/AddHostGroup.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Application\UseCase\AddHostGroup; use Assert\AssertionFailedException; use Centreon\Domain\Configuration\Icon\IconException; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Log\LoggerTrait; use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface; use Core\Application\Common\UseCase\{ ErrorResponse, InvalidArgumentResponse, ResponseStatusInterface }; use Core\Domain\Common\GeoCoords; use Core\Host\Application\Exception\HostException; use Core\Host\Application\Repository\ReadHostRepositoryInterface; use Core\HostGroup\Application\Exceptions\HostGroupException; use Core\HostGroup\Application\Repository\{ ReadHostGroupRepositoryInterface, WriteHostGroupRepositoryInterface }; use Core\HostGroup\Domain\Model\HostGroupRelation; use Core\HostGroup\Domain\Model\NewHostGroup; use Core\ResourceAccess\Application\Exception\RuleException; use Core\ResourceAccess\Application\Repository\{ ReadResourceAccessRepositoryInterface, WriteResourceAccessRepositoryInterface }; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\HostGroupFilterType; use Core\Security\AccessGroup\Application\Repository\{ ReadAccessGroupRepositoryInterface, WriteAccessGroupRepositoryInterface }; final class AddHostGroup { use LoggerTrait; public function __construct( private readonly ContactInterface $user, private readonly AddHostGroupValidator $validator, private readonly DataStorageEngineInterface $storageEngine, private readonly bool $isCloudPlatform, private readonly ReadHostGroupRepositoryInterface $readHostGroupRepository, private readonly ReadResourceAccessRepositoryInterface $readResourceAccessRepository, private readonly ReadHostRepositoryInterface $readHostRepository, private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository, private readonly WriteHostGroupRepositoryInterface $writeHostGroupRepository, private readonly WriteResourceAccessRepositoryInterface $writeResourceAccessRepository, private readonly WriteAccessGroupRepositoryInterface $writeAccessGroupRepository, ) { } /** * @param AddHostGroupRequest $request */ public function __invoke(AddHostGroupRequest $request): AddHostGroupResponse|ResponseStatusInterface { try { $this->validator->assertNameDoesNotAlreadyExists($request->name); $this->validator->assertHostsExist($request->hosts); if ($request->iconId !== null) { $this->validator->assertIconExists($request->iconId); } if ($this->isCloudPlatform) { $this->validator->assertResourceAccessRulesExist($request->resourceAccessRules); } $hostGroup = new NewHostGroup( name: $request->name, alias: $request->alias, comment: $request->comment, iconId: $request->iconId, geoCoords: match ($request->geoCoords) { null, '' => null, default => GeoCoords::fromString($request->geoCoords), }, ); if (! $this->storageEngine->isAlreadyinTransaction()) { $this->storageEngine->startTransaction(); } $newHostGroupId = $this->writeHostGroupRepository->add($hostGroup); $this->writeHostGroupRepository->addHostLinks($newHostGroupId, $request->hosts); $this->linkHostGroupToRessourceAccess($request->resourceAccessRules, $newHostGroupId); $newHostGroup = $this->readHostGroupRepository->findOne($newHostGroupId); if ($newHostGroup === null) { throw HostGroupException::errorWhileRetrievingJustCreated(); } $linkedHosts = $this->readHostRepository->findByHostGroup($newHostGroupId); if ($this->isCloudPlatform) { $linkedResourceAccessRules = array_map( fn (int $ruleId) => $this->readResourceAccessRepository->findById($ruleId) ?? throw RuleException::errorWhileRetrievingARule(), $request->resourceAccessRules ); } $this->storageEngine->commitTransaction(); return new AddHostGroupResponse( new HostGroupRelation($newHostGroup, $linkedHosts, $linkedResourceAccessRules ?? []) ); } catch (HostGroupException|HostException|RuleException|AssertionFailedException|IconException $ex) { if ($this->storageEngine->isAlreadyInTransaction()) { $this->storageEngine->rollbackTransaction(); } $this->error( "Error while adding host groups : {$ex->getMessage()}", [ 'exception' => ['message' => $ex->getMessage(), 'trace' => $ex->getTraceAsString()], ] ); return new InvalidArgumentResponse($ex); } catch (\Throwable $ex) { if ($this->storageEngine->isAlreadyInTransaction()) { $this->storageEngine->rollbackTransaction(); } $this->error( "Error while adding host groups : {$ex->getMessage()}", [ 'exception' => ['message' => $ex->getMessage(), 'trace' => $ex->getTraceAsString()], ] ); return new ErrorResponse(HostGroupException::errorWhileAdding()); } } /** * Link Host Groups to Ressource Access * For On Prem: Host Groups are linked to Ressource Access Groups * For Cloud: Host Groups are added to Datasets's Resource Access Rules, * only if the dataset Hostgroup has no parent * * @param int[] $resourceAccessRuleIds * @param int $hostGroupId * * @throws \Throwable */ private function linkHostGroupToRessourceAccess(array $resourceAccessRuleIds, int $hostGroupId): void { if ($this->isCloudPlatform) { $this->linkHostGroupToRAM($resourceAccessRuleIds, $hostGroupId); } else { $this->linkHostGroupToResourcesACL($hostGroupId); } } /** * Link Host groups to Datasets's Resource Access Rules, only if the dataset Hostgroup has no parent * * @param int[] $resourceAccessRuleIds * @param int $hostGroupId * * @throws \Throwable */ private function linkHostGroupToRAM(array $resourceAccessRuleIds, int $hostGroupId): void { $datasetFilterRelations = $this->readResourceAccessRepository->findLastLevelDatasetFilterByRuleIdsAndType( $resourceAccessRuleIds, HostGroupFilterType::TYPE_NAME ); foreach ($datasetFilterRelations as $datasetFilterRelation) { $resourceIds = $datasetFilterRelation->getResourceIds(); $resourceIds[] = $hostGroupId; $this->writeResourceAccessRepository->updateDatasetResources( $datasetFilterRelation->getDatasetFilterId(), $resourceIds ); $this->linkHostGroupToResourcesACL($hostGroupId); } } /** * Link Host Groups to user Resource Access Groups * * @param int $hostGroupId * * @throws \Throwable */ private function linkHostGroupToResourcesACL(int $hostGroupId): void { if (! $this->user->isAdmin()) { $this->writeAccessGroupRepository->addLinksBetweenHostGroupAndAccessGroups( $hostGroupId, $this->readAccessGroupRepository->findByContact($this->user) ); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Application/UseCase/FindHostGroups/FindHostGroupsResponse.php
centreon/src/Core/HostGroup/Application/UseCase/FindHostGroups/FindHostGroupsResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Application\UseCase\FindHostGroups; use Core\Application\Common\UseCase\ListingResponseInterface; final class FindHostGroupsResponse implements ListingResponseInterface { /** * @param HostGroupResponse[] $hostgroups */ public function __construct( public array $hostgroups = [], ) { } /** * @inheritDoc */ public function getData(): mixed { return $this->hostgroups; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Application/UseCase/FindHostGroups/FindHostGroups.php
centreon/src/Core/HostGroup/Application/UseCase/FindHostGroups/FindHostGroups.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Application\UseCase\FindHostGroups; 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\Domain\AdminResolver; use Core\HostGroup\Application\Exceptions\HostGroupException; use Core\HostGroup\Application\Repository\ReadHostGroupRepositoryInterface; use Core\HostGroup\Domain\Model\HostGroup; use Core\HostGroup\Domain\Model\HostGroupRelationCount; use Core\Media\Application\Repository\ReadMediaRepositoryInterface; use Core\Media\Domain\Model\Media; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\Security\AccessGroup\Domain\Model\AccessGroup; final class FindHostGroups { use LoggerTrait; public function __construct( private readonly ReadHostGroupRepositoryInterface $readHostGroupRepository, private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository, private readonly ReadMediaRepositoryInterface $readMediaRepository, private readonly RequestParametersInterface $requestParameters, private readonly ContactInterface $contact, private readonly AdminResolver $adminResolver, ) { } public function __invoke(): FindHostGroupsResponse|ResponseStatusInterface { try { return $this->adminResolver->isAdmin($this->contact) ? $this->findHostGroupAsAdmin() : $this->findHostGroupAsContact(); } catch (\Throwable $ex) { $this->error( "Error while listing host groups : {$ex->getMessage()}", [ 'contact_id' => $this->contact->getId(), 'request_parameters' => $this->requestParameters->toArray(), 'exception' => ['message' => $ex->getMessage(), 'trace' => $ex->getTraceAsString()], ] ); return new ErrorResponse(HostGroupException::errorWhileSearching()->getMessage()); } } /** * @throws \Throwable * * @return FindHostGroupsResponse */ private function findHostGroupAsAdmin(): FindHostGroupsResponse { $hostGroups = $this->readHostGroupRepository->findAll($this->requestParameters); $hostGroupIds = array_map( fn (HostGroup $hostGroup): int => $hostGroup->getId(), iterator_to_array($hostGroups) ); $iconIds = array_filter( array_map( fn (HostGroup $hostGroup): ?int => $hostGroup->getIconId(), iterator_to_array($hostGroups) ), fn (?int $iconId): bool => $iconId !== null, ); return $this->createResponse( $hostGroups, $hostGroupIds ? $this->readHostGroupRepository->findHostsCountByIds($hostGroupIds) : [], $iconIds !== [] ? $this->readMediaRepository->findByIds($iconIds) : [], ); } /** * @throws \Throwable * * @return FindHostGroupsResponse */ private function findHostGroupAsContact(): FindHostGroupsResponse { $hostGroups = []; $accessGroupIds = array_map( fn (AccessGroup $accessGroup): int => $accessGroup->getId(), $this->readAccessGroupRepository->findByContact($this->contact) ); if ($accessGroupIds !== []) { // if user has access to all hostgroups then use admin workflow if ($this->readHostGroupRepository->hasAccessToAllHostGroups($accessGroupIds)) { $this->debug( 'ACL configuration for user gives access to all host groups', ['user_id' => $this->contact->getId()] ); $hostGroups = $this->readHostGroupRepository->findAll($this->requestParameters); } else { $this->debug( 'Using users ACL configured on host groups', ['user_id' => $this->contact->getId()] ); $hostGroups = $this->readHostGroupRepository->findAllByAccessGroupIds( $this->requestParameters, $accessGroupIds ); } } $hostGroupIds = array_map( fn (HostGroup $hostGroup): int => $hostGroup->getId(), iterator_to_array($hostGroups) ); $iconIds = array_filter( array_map( fn (HostGroup $hostGroup): ?int => $hostGroup->getIconId(), iterator_to_array($hostGroups) ), fn (?int $iconId): bool => $iconId !== null, ); return $this->createResponse( $hostGroups, $accessGroupIds !== [] && $hostGroupIds !== [] ? $this->readHostGroupRepository->findHostsCountByAccessGroupsIds($hostGroupIds, $accessGroupIds) : [], $iconIds !== [] ? $this->readMediaRepository->findByIds($iconIds) : [], ); } /** * @param iterable<HostGroup> $hostGroups * @param array<int,HostGroupRelationCount> $hostsCount * @param array<int,Media> $icons * * @return FindHostGroupsResponse */ private function createResponse(iterable $hostGroups, array $hostsCount, array $icons): FindHostGroupsResponse { $response = new FindHostGroupsResponse(); foreach ($hostGroups as $hostgroup) { $response->hostgroups[] = new HostGroupResponse( hostgroup: $hostgroup, hostsCount: $hostsCount[$hostgroup->getId()] ?? null, icon: $icons[$hostgroup->getIconId()] ?? null, ); } return $response; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Application/UseCase/FindHostGroups/HostGroupResponse.php
centreon/src/Core/HostGroup/Application/UseCase/FindHostGroups/HostGroupResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Application\UseCase\FindHostGroups; use Core\HostGroup\Domain\Model\HostGroup; use Core\HostGroup\Domain\Model\HostGroupRelationCount; use Core\Media\Domain\Model\Media; final class HostGroupResponse { public function __construct( public HostGroup $hostgroup, public ?HostGroupRelationCount $hostsCount = null, public ?Media $icon = 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/HostGroup/Application/UseCase/DuplicateHostGroups/DuplicateHostGroupsRequest.php
centreon/src/Core/HostGroup/Application/UseCase/DuplicateHostGroups/DuplicateHostGroupsRequest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Application\UseCase\DuplicateHostGroups; final readonly class DuplicateHostGroupsRequest { /** * @param int[] $hostGroupIds * @param int $nbDuplicates */ public function __construct(public array $hostGroupIds, public int $nbDuplicates) { } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Application/UseCase/DuplicateHostGroups/DuplicateHostGroupsStatusResponse.php
centreon/src/Core/HostGroup/Application/UseCase/DuplicateHostGroups/DuplicateHostGroupsStatusResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Application\UseCase\DuplicateHostGroups; use Core\Common\Domain\ResponseCodeEnum; final class DuplicateHostGroupsStatusResponse { public int $id = 0; public ResponseCodeEnum $status = ResponseCodeEnum::OK; public ?string $message = null; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Application/UseCase/DuplicateHostGroups/DuplicateHostGroups.php
centreon/src/Core/HostGroup/Application/UseCase/DuplicateHostGroups/DuplicateHostGroups.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Application\UseCase\DuplicateHostGroups; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Log\LoggerTrait; use Core\Application\Common\UseCase\NotFoundResponse; use Core\Common\Domain\ResponseCodeEnum; use Core\Contact\Domain\AdminResolver; use Core\HostGroup\Application\Exceptions\HostGroupException; use Core\HostGroup\Application\Repository\ReadHostGroupRepositoryInterface; use Core\HostGroup\Application\Repository\WriteHostGroupRepositoryInterface; use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface; use Core\MonitoringServer\Application\Repository\WriteMonitoringServerRepositoryInterface; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\Security\AccessGroup\Application\Repository\WriteAccessGroupRepositoryInterface; final class DuplicateHostGroups { use LoggerTrait; private bool $isUserAdmin = false; public function __construct( private readonly ContactInterface $user, private readonly ReadHostGroupRepositoryInterface $readHostGroupRepository, private readonly WriteHostGroupRepositoryInterface $writeHostGroupRepository, private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository, private readonly WriteAccessGroupRepositoryInterface $writeAccessGroupRepository, private readonly ReadMonitoringServerRepositoryInterface $readMonitoringServerRepository, private readonly WriteMonitoringServerRepositoryInterface $writeMonitoringServerRepository, private readonly AdminResolver $adminResolver, ) { } /** * @param DuplicateHostGroupsRequest $request * * @return DuplicateHostGroupsResponse */ public function __invoke(DuplicateHostGroupsRequest $request): DuplicateHostGroupsResponse { $this->isUserAdmin = $this->adminResolver->isAdmin($this->user); $results = []; foreach ($request->hostGroupIds as $hostGroupId) { $statusResponse = new DuplicateHostGroupsStatusResponse(); $statusResponse->id = $hostGroupId; try { if (! $this->hostGroupExists($hostGroupId)) { $statusResponse->status = ResponseCodeEnum::NotFound; $statusResponse->message = (new NotFoundResponse('Host Group'))->getMessage(); $results[] = $statusResponse; continue; } $hostGroupName = $this->readHostGroupRepository->findNames([$hostGroupId])->getName($hostGroupId); $duplicated = 0; $duplicateIndex = 1; while ($duplicated < $request->nbDuplicates) { if ($this->hostGroupExistsByName($hostGroupName . '_' . $duplicateIndex)) { $duplicateIndex++; continue; } $newHostGroupId = $this->writeHostGroupRepository->duplicate($hostGroupId, $duplicateIndex); // Handle ACL Resources for non admin users if (! $this->isUserAdmin) { $this->duplicateContactAclResources($newHostGroupId); } // Duplicate Host Relationships $linkedHostsIds = $this->readHostGroupRepository->findLinkedHosts($hostGroupId); $this->duplicateHostsRelations($linkedHostsIds, $newHostGroupId); // Signal configuration change $this->signalConfigurationChange($linkedHostsIds); // Duplicate HG ACLs $this->duplicateHostGroupAcls($hostGroupId, $newHostGroupId); // Update ACL Groups Flag $this->updateAclGroupsFlag(); $duplicated++; } $results[] = $statusResponse; } catch (\Throwable $ex) { $this->error( "Error while duplicating host groups : {$ex->getMessage()}", [ 'hostgroupIds' => $request->hostGroupIds, 'current_hostgroupId' => $hostGroupId, 'exception' => ['message' => $ex->getMessage(), 'trace' => $ex->getTraceAsString()], ] ); $statusResponse->status = ResponseCodeEnum::Error; $statusResponse->message = HostGroupException::errorWhileDuplicating()->getMessage(); $results[] = $statusResponse; } } return new DuplicateHostGroupsResponse($results); } /** * Checks that host group exists for the user regarding ACLs * * @param int $hostGroupId * * @return bool */ private function hostGroupExists(int $hostGroupId): bool { return $this->isUserAdmin ? $this->readHostGroupRepository->existsOne($hostGroupId) : $this->readHostGroupRepository->existsOneByAccessGroups( $hostGroupId, $this->readAccessGroupRepository->findByContact($this->user) ); } /** * Checks whether a host group exists by name * * @param string $hostGroupName * @return bool */ private function hostGroupExistsByName(string $hostGroupName): bool { return $this->isUserAdmin ? $this->readHostGroupRepository->nameAlreadyExists($hostGroupName) : $this->readHostGroupRepository->nameAlreadyExistsByAccessGroups( $hostGroupName, $this->readAccessGroupRepository->findByContact($this->user) ); } /** * Duplicate hosts relations. * * @param int $newHostGroupId * @param int[] $linkedHostsIds */ private function duplicateHostsRelations(array $linkedHostsIds, int $newHostGroupId): void { foreach ($linkedHostsIds as $hostId) { $this->writeHostGroupRepository->linkToHost($hostId, [$newHostGroupId]); } } /** * Link HG to contact ACL. * * @param int $hostGroupId */ private function duplicateContactAclResources(int $hostGroupId): void { $accessGroups = $this->readAccessGroupRepository->findByContact($this->user); $this->writeAccessGroupRepository->addLinksBetweenHostGroupAndAccessGroups($hostGroupId, $accessGroups); } /** * Duplicate HG ACL. * * @param int $hostGroupId * @param int $newHostGroupId */ private function duplicateHostGroupAcls(int $hostGroupId, int $newHostGroupId): void { $aclResources = $this->readAccessGroupRepository->findAclResourcesByHostGroupId($hostGroupId); $this->writeAccessGroupRepository->addLinksBetweenHostGroupAndResourceIds($newHostGroupId, $aclResources); } /** * Update ACL groups flag. */ private function updateAclGroupsFlag(): void { if (! $this->isUserAdmin) { $accessGroups = $this->readAccessGroupRepository->findByContact($this->user); $this->writeAccessGroupRepository->updateAclGroupsFlag($accessGroups); } else { $this->writeAccessGroupRepository->updateAclResourcesFlag(); } } /** * Signal configuration change. * * @param int[] $linkedHostsIds */ private function signalConfigurationChange(array $linkedHostsIds): void { // Find monitoring servers associated with the linked hosts $serverIds = $this->readMonitoringServerRepository->findByHostsIds($linkedHostsIds); // Notify configuration changes $this->writeMonitoringServerRepository->notifyConfigurationChanges($serverIds); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Application/UseCase/DuplicateHostGroups/DuplicateHostGroupsResponse.php
centreon/src/Core/HostGroup/Application/UseCase/DuplicateHostGroups/DuplicateHostGroupsResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Application\UseCase\DuplicateHostGroups; use Core\Application\Common\UseCase\BulkResponseInterface; final class DuplicateHostGroupsResponse implements BulkResponseInterface { /** * @param DuplicateHostGroupsStatusResponse[] $results */ public function __construct(private readonly array $results) { } /** * {@inheritDoc} * * @return DuplicateHostGroupsStatusResponse[] */ public function getData(): array { return $this->results; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Application/UseCase/DeleteHostGroup/DeleteHostGroup.php
centreon/src/Core/HostGroup/Application/UseCase/DeleteHostGroup/DeleteHostGroup.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Application\UseCase\DeleteHostGroup; use Centreon\Domain\Contact\Contact; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Log\LoggerTrait; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\ForbiddenResponse; use Core\Application\Common\UseCase\NoContentResponse; use Core\Application\Common\UseCase\NotFoundResponse; use Core\Application\Common\UseCase\PresenterInterface; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\Contact\Domain\AdminResolver; use Core\HostGroup\Application\Exceptions\HostGroupException; use Core\HostGroup\Application\Repository\ReadHostGroupRepositoryInterface; use Core\HostGroup\Application\Repository\WriteHostGroupRepositoryInterface; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Throwable; final class DeleteHostGroup { use LoggerTrait; public function __construct( private readonly ReadHostGroupRepositoryInterface $readHostGroupRepository, private readonly WriteHostGroupRepositoryInterface $writeHostGroupRepository, private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository, private readonly ContactInterface $contact, private readonly AdminResolver $adminResolver, ) { } public function __invoke(int $hostGroupId, PresenterInterface $presenter): void { try { if ($this->adminResolver->isAdmin($this->contact)) { $presenter->setResponseStatus($this->deleteHostGroupAsAdmin($hostGroupId)); } elseif ($this->contactCanExecuteThisUseCase()) { $presenter->setResponseStatus($this->deleteHostGroupAsContact($hostGroupId)); } else { $this->error( "User doesn't have sufficient rights to see host groups", ['user_id' => $this->contact->getId()] ); $presenter->setResponseStatus( new ForbiddenResponse(HostGroupException::accessNotAllowedForWriting()->getMessage()) ); } } catch (Throwable $ex) { $presenter->setResponseStatus(new ErrorResponse(HostGroupException::errorWhileDeleting()->getMessage())); $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); } } /** * @param int $hostGroupId * * @throws Throwable * * @return ResponseStatusInterface */ private function deleteHostGroupAsAdmin(int $hostGroupId): ResponseStatusInterface { if ($this->readHostGroupRepository->existsOne($hostGroupId)) { $this->writeHostGroupRepository->deleteHostGroup($hostGroupId); return new NoContentResponse(); } $this->warning('Host group (%s) not found', ['id' => $hostGroupId]); return new NotFoundResponse('Host group'); } /** * @param int $hostGroupId * * @throws Throwable * * @return ResponseStatusInterface */ private function deleteHostGroupAsContact(int $hostGroupId): ResponseStatusInterface { $accessGroups = $this->readAccessGroupRepository->findByContact($this->contact); if ($this->readHostGroupRepository->existsOneByAccessGroups($hostGroupId, $accessGroups)) { $this->writeHostGroupRepository->deleteHostGroup($hostGroupId); return new NoContentResponse(); } $this->warning('Host group (%s) not found', ['id' => $hostGroupId]); return new NotFoundResponse('Host group'); } /** * @return bool */ private function contactCanExecuteThisUseCase(): bool { return $this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_HOSTS_HOST_GROUPS_READ_WRITE); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Application/UseCase/EnableDisableHostGroups/EnableDisableHostGroupsResponse.php
centreon/src/Core/HostGroup/Application/UseCase/EnableDisableHostGroups/EnableDisableHostGroupsResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Application\UseCase\EnableDisableHostGroups; use Core\Application\Common\UseCase\BulkResponseInterface; final class EnableDisableHostGroupsResponse implements BulkResponseInterface { /** * @param EnableDisableHostGroupsStatusResponse[] $results */ public function __construct(private readonly array $results) { } /** * {@inheritDoc} * * @return EnableDisableHostGroupsStatusResponse[] */ public function getData(): array { return $this->results; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Application/UseCase/EnableDisableHostGroups/EnableDisableHostGroups.php
centreon/src/Core/HostGroup/Application/UseCase/EnableDisableHostGroups/EnableDisableHostGroups.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Application\UseCase\EnableDisableHostGroups; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Log\LoggerTrait; use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface; use Core\Application\Common\UseCase\NotFoundResponse; use Core\Common\Domain\ResponseCodeEnum; use Core\Contact\Domain\AdminResolver; use Core\HostGroup\Application\Exceptions\HostGroupException; use Core\HostGroup\Application\Repository\ReadHostGroupRepositoryInterface; use Core\HostGroup\Application\Repository\WriteHostGroupRepositoryInterface; use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface; use Core\MonitoringServer\Application\Repository\WriteMonitoringServerRepositoryInterface; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; final class EnableDisableHostGroups { use LoggerTrait; private bool $isUserAdmin = false; public function __construct( private readonly ContactInterface $user, private readonly DataStorageEngineInterface $storageEngine, private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository, private readonly ReadHostGroupRepositoryInterface $readRepository, private readonly WriteHostGroupRepositoryInterface $writeRepository, private readonly ReadMonitoringServerRepositoryInterface $readMonitoringServerRepository, private readonly WriteMonitoringServerRepositoryInterface $writeMonitoringServerRepository, private readonly AdminResolver $adminResolver, ) { } public function __invoke(EnableDisableHostGroupsRequest $request): EnableDisableHostGroupsResponse { $this->isUserAdmin = $this->adminResolver->isAdmin($this->user); $results = []; foreach ($request->hostGroupIds as $hostGroupId) { $statusResponse = new EnableDisableHostGroupsStatusResponse(); $statusResponse->id = $hostGroupId; try { if (! $this->storageEngine->isAlreadyinTransaction()) { $this->storageEngine->startTransaction(); } if (! $this->hostGroupExists($hostGroupId)) { $statusResponse->status = ResponseCodeEnum::NotFound; $statusResponse->message = (new NotFoundResponse('Host Group'))->getMessage(); $results[] = $statusResponse; continue; } $this->writeRepository->enableDisableHostGroup($hostGroupId, $request->isEnable); $linkedHostIds = $this->readRepository->findLinkedHosts($hostGroupId); $this->notifyConfigurationChange($linkedHostIds); if ($this->storageEngine->isAlreadyinTransaction()) { $this->storageEngine->commitTransaction(); } $results[] = $statusResponse; } catch (\Exception $ex) { if ($this->storageEngine->isAlreadyinTransaction()) { $this->storageEngine->rollbackTransaction(); } $this->error( "Error while enabling/disabling host groups : {$ex->getMessage()}", [ 'hostgroupIds' => $request->hostGroupIds, 'current_hostgroupId' => $hostGroupId, 'exception' => ['message' => $ex->getMessage(), 'trace' => $ex->getTraceAsString()], ] ); $statusResponse->status = ResponseCodeEnum::Error; $statusResponse->message = HostGroupException::errorWhileEnablingDisabling()->getMessage(); $results[] = $statusResponse; } } return new EnableDisableHostGroupsResponse($results); } /** * Check that host group exists for the user regarding ACLs. * * @param int $hostGroupId * * @return bool */ private function hostGroupExists(int $hostGroupId): bool { return $this->isUserAdmin ? $this->readRepository->existsOne($hostGroupId) : $this->readRepository->existsOneByAccessGroups( $hostGroupId, $this->readAccessGroupRepository->findByContact($this->user) ); } /** * Notify configuration change to monitoring servers. * * @param int[] $linkedHostsIds */ private function notifyConfigurationChange(array $linkedHostsIds): void { // Find monitoring servers associated with the linked hosts $serverIds = $this->readMonitoringServerRepository->findByHostsIds($linkedHostsIds); // Notify configuration changes $this->writeMonitoringServerRepository->notifyConfigurationChanges($serverIds); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Application/UseCase/EnableDisableHostGroups/EnableDisableHostGroupsStatusResponse.php
centreon/src/Core/HostGroup/Application/UseCase/EnableDisableHostGroups/EnableDisableHostGroupsStatusResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Application\UseCase\EnableDisableHostGroups; use Core\Common\Domain\ResponseCodeEnum; final class EnableDisableHostGroupsStatusResponse { public int $id = 0; public ResponseCodeEnum $status = ResponseCodeEnum::OK; public ?string $message = null; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Application/UseCase/EnableDisableHostGroups/EnableDisableHostGroupsRequest.php
centreon/src/Core/HostGroup/Application/UseCase/EnableDisableHostGroups/EnableDisableHostGroupsRequest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Application\UseCase\EnableDisableHostGroups; final readonly class EnableDisableHostGroupsRequest { /** * @param int[] $hostGroupIds * @param bool $isEnable */ public function __construct(public array $hostGroupIds, public bool $isEnable) { } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Application/UseCase/UpdateHostGroup/UpdateHostGroupValidator.php
centreon/src/Core/HostGroup/Application/UseCase/UpdateHostGroup/UpdateHostGroupValidator.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Application\UseCase\UpdateHostGroup; use Centreon\Domain\Configuration\Icon\IconException; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Log\LoggerTrait; use Core\Common\Domain\TrimmedString; use Core\Contact\Application\Repository\ReadContactGroupRepositoryInterface; use Core\Contact\Domain\AdminResolver; use Core\Host\Application\Exception\HostException; use Core\Host\Application\Repository\ReadHostRepositoryInterface; use Core\HostGroup\Application\Exceptions\HostGroupException; use Core\HostGroup\Application\Repository\ReadHostGroupRepositoryInterface; use Core\HostGroup\Domain\Model\HostGroup; use Core\ResourceAccess\Application\Exception\RuleException; use Core\ResourceAccess\Application\Repository\ReadResourceAccessRepositoryInterface; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\ViewImg\Application\Repository\ReadViewImgRepositoryInterface; class UpdateHostGroupValidator { use LoggerTrait; private bool $isUserAdmin = false; public function __construct( private readonly ReadHostGroupRepositoryInterface $readHostGroupRepository, private readonly ReadResourceAccessRepositoryInterface $readResourceAccessRepository, private readonly ReadContactGroupRepositoryInterface $readContactGroupRepository, private readonly ReadHostRepositoryInterface $readHostRepository, private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository, private readonly ReadViewImgRepositoryInterface $readViewImgRepository, private readonly ContactInterface $user, private readonly AdminResolver $adminResolver, ) { $this->isUserAdmin = $this->adminResolver->isAdmin($this->user); } /** * Assert that the host group name is not already used. * * @param HostGroup $hostGroup * @param string $hostGroupName * * @throws HostGroupException|\Throwable */ public function assertNameDoesNotAlreadyExists(HostGroup $hostGroup, string $hostGroupName): void { $hostGroupName = new TrimmedString($hostGroupName); if ( $hostGroup->getName() !== (string) $hostGroupName && $this->readHostGroupRepository->nameAlreadyExists((string) $hostGroupName) ) { throw HostGroupException::nameAlreadyExists((string) $hostGroupName); } } /** * Assert that given host ids exists (filtered by access groups for non admin users) * * @param int[] $hostIds * @throws \Throwable|HostException */ public function assertHostsExist(array $hostIds): void { $unexistentHosts = $this->isUserAdmin ? array_diff($hostIds, $this->readHostRepository->exist($hostIds)) : array_filter($hostIds, fn ($hostId) => ! $this->readHostRepository->existsByAccessGroups( $hostId, $this->readAccessGroupRepository->findByContact($this->user) )); if ($unexistentHosts !== []) { throw HostException::idsDoNotExist('hosts', $unexistentHosts); } } /** * Assert That given Resource Access Rule IDs exists. * - Check that ids globally exists * - Check that ids exists for the contact * - Check that ids exists for the contact contact groups. * * @param int[] $resourceAccessRuleIds * * @throws RuleException|\Throwable */ public function assertResourceAccessRulesExist(array $resourceAccessRuleIds): void { // Add Link between RAM rule and HG $unexistentAccessRules = array_diff( $resourceAccessRuleIds, $this->readResourceAccessRepository->exist($resourceAccessRuleIds) ); if ($unexistentAccessRules !== []) { throw RuleException::idsDoNotExist('rules', $unexistentAccessRules); } if (! $this->isUserAdmin) { $existentRulesByContact = $this->readResourceAccessRepository->existByContact( ruleIds: $resourceAccessRuleIds, userId: $this->user->getId() ); $existentRulesByContactGroup = $this->readResourceAccessRepository->existByContactGroup( ruleIds: $resourceAccessRuleIds, contactGroups: $this->readContactGroupRepository->findAllByUserId($this->user->getId()) ); $existentRules = array_unique( array_merge($existentRulesByContact, $existentRulesByContactGroup) ); if ([] !== $unexistentAccessRulesByContact = array_diff($resourceAccessRuleIds, $existentRules)) { throw RuleException::idsDoNotExist('rules', $unexistentAccessRulesByContact); } if ($existentRules === []) { throw HostGroupException::errorResourceAccessRulesEmpty(); } } } /** * Assert that given icon id exists. * * @param int $iconId * * @throws IconException */ public function assertIconExists(int $iconId): void { if (! $this->readViewImgRepository->existsOne($iconId)) { throw IconException::iconDoesNotExists($iconId); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Application/UseCase/UpdateHostGroup/UpdateHostGroupRequest.php
centreon/src/Core/HostGroup/Application/UseCase/UpdateHostGroup/UpdateHostGroupRequest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Application\UseCase\UpdateHostGroup; final class UpdateHostGroupRequest { /** * @param int $id * @param string $name * @param string $alias * @param string|null $geoCoords * @param string $comment * @param int|null $iconId * @param int[] $hosts * @param int[] $resourceAccessRules */ public function __construct( public int $id = 0, public string $name = '', public string $alias = '', public ?string $geoCoords = null, public string $comment = '', public ?int $iconId = null, public array $hosts = [], public array $resourceAccessRules = [], ) { } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Application/UseCase/UpdateHostGroup/UpdateHostGroup.php
centreon/src/Core/HostGroup/Application/UseCase/UpdateHostGroup/UpdateHostGroup.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Application\UseCase\UpdateHostGroup; use Assert\AssertionFailedException; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Log\LoggerTrait; use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface; use Centreon\Domain\RequestParameters\RequestParameters; use Core\Application\Common\UseCase\{ ErrorResponse, InvalidArgumentResponse, NoContentResponse, NotFoundResponse, ResponseStatusInterface, }; use Core\Common\Domain\SimpleEntity; use Core\Contact\Domain\AdminResolver; use Core\Domain\Common\GeoCoords; use Core\Domain\Exception\InvalidGeoCoordException; use Core\Host\Application\Exception\HostException; use Core\Host\Application\Repository\ReadHostRepositoryInterface; use Core\Host\Domain\Model\SmallHost; use Core\HostGroup\Application\Exceptions\HostGroupException; use Core\HostGroup\Application\Repository\{ ReadHostGroupRepositoryInterface, WriteHostGroupRepositoryInterface, }; use Core\HostGroup\Domain\Model\HostGroup; use Core\MonitoringServer\Application\Repository\{ ReadMonitoringServerRepositoryInterface, WriteMonitoringServerRepositoryInterface, }; use Core\ResourceAccess\Application\Exception\RuleException; use Core\ResourceAccess\Application\Repository\{ ReadResourceAccessRepositoryInterface, WriteResourceAccessRepositoryInterface, }; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\HostGroupFilterType; use Core\Security\AccessGroup\Application\Repository\{ ReadAccessGroupRepositoryInterface, WriteAccessGroupRepositoryInterface, }; use Utility\Difference\BasicDifference; final class UpdateHostGroup { use LoggerTrait; public function __construct( private readonly ContactInterface $user, private readonly UpdateHostGroupValidator $validator, private readonly DataStorageEngineInterface $storageEngine, private readonly bool $isCloudPlatform, private readonly ReadHostGroupRepositoryInterface $readHostGroupRepository, private readonly ReadHostRepositoryInterface $readHostRepository, private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository, private readonly ReadResourceAccessRepositoryInterface $readResourceAccessRepository, private readonly ReadMonitoringServerRepositoryInterface $readMonitoringServerRepository, private readonly WriteHostGroupRepositoryInterface $writeHostGroupRepository, private readonly WriteResourceAccessRepositoryInterface $writeResourceAccessRepository, private readonly WriteMonitoringServerRepositoryInterface $writeMonitoringServerRepository, private readonly WriteAccessGroupRepositoryInterface $writeAccessGroupRepository, private readonly AdminResolver $adminResolver, ) { } /** * @param UpdateHostGroupRequest $request */ public function __invoke(UpdateHostGroupRequest $request): ResponseStatusInterface { try { $existingHostGroup = $this->adminResolver->isAdmin($this->user) ? $this->readHostGroupRepository->findOne($request->id) : $this->readHostGroupRepository->findOneByAccessGroups( $request->id, $this->readAccessGroupRepository->findByContact($this->user) ); if ($existingHostGroup === null) { return new NotFoundResponse('Host Group'); } $this->validator->assertNameDoesNotAlreadyExists($existingHostGroup, $request->name); $this->validator->assertHostsExist($request->hosts); if ($request->iconId !== null) { $this->validator->assertIconExists($request->iconId); } if ($this->isCloudPlatform) { $this->validator->assertResourceAccessRulesExist($request->resourceAccessRules); } if (! $this->storageEngine->isAlreadyInTransaction()) { $this->storageEngine->startTransaction(); } $this->updateHostGroup($request, $existingHostGroup); $this->updateHostLinks($request); if ($this->isCloudPlatform) { $this->updateResourceAccess($request); } $this->storageEngine->commitTransaction(); return new NoContentResponse(); } catch (HostGroupException|HostException|RuleException|AssertionFailedException|InvalidGeoCoordException $ex) { if ($this->storageEngine->isAlreadyInTransaction()) { $this->storageEngine->rollbackTransaction(); } $this->error( "Error while updating host group : {$ex->getMessage()}", [ 'hostGroupId' => $request->id, 'exception' => ['message' => $ex->getMessage(), 'trace' => $ex->getTraceAsString()], ] ); return new InvalidArgumentResponse($ex); } catch (\Throwable $ex) { if ($this->storageEngine->isAlreadyInTransaction()) { $this->storageEngine->rollbackTransaction(); } $this->error( "Error while updating host group : {$ex->getMessage()}", [ 'hostGroupId' => $request->id, 'exception' => ['message' => $ex->getMessage(), 'trace' => $ex->getTraceAsString()], ] ); return new ErrorResponse($ex); } } /** * Update the configuration options of the host group. * * @param UpdateHostGroupRequest $request * @param HostGroup $existingHostGroup * * @throws InvalidGeoCoordException|\Throwable */ private function updateHostGroup(UpdateHostGroupRequest $request, HostGroup $existingHostGroup): void { $updatedHostGroup = new HostGroup( id: $request->id, name: $request->name, alias: $request->alias, comment: $request->comment, iconId: $request->iconId, geoCoords: match ($request->geoCoords) { null, '' => null, default => GeoCoords::fromString($request->geoCoords), }, isActivated: $existingHostGroup->isActivated(), ); $this->writeHostGroupRepository->update($updatedHostGroup); } /** * Update the hosts linked to the host group. * * @param UpdateHostGroupRequest $request * * @throws \Throwable */ private function updateHostLinks(UpdateHostGroupRequest $request): void { if ($this->adminResolver->isAdmin($this->user)) { $existingHosts = $this->readHostRepository->findByHostGroup($request->id); $hostsToRemove = array_map(fn (SimpleEntity $host): int => $host->getId(), $existingHosts); } else { $reachableHosts = $this->readHostRepository->findByRequestParametersAndAccessGroups( new RequestParameters(), $this->readAccessGroupRepository->findByContact($this->user) ); $hostsToRemove = (new BasicDifference( array_map(fn (SmallHost $host) => $host->getId(), $reachableHosts), $request->hosts ))->getRemoved(); } $this->writeHostGroupRepository->deleteHostLinks($request->id, $hostsToRemove); $this->writeHostGroupRepository->addHostLinks($request->id, $request->hosts); $this->notifyConfigurationChange($request->hosts); } /** * Update Resource Access Rules linked to the host group. * * @param UpdateHostGroupRequest $request * * @throws \Throwable */ private function updateResourceAccess(UpdateHostGroupRequest $request): void { $rulesByHostgroup = $this->readResourceAccessRepository->existByTypeAndResourceId( HostGroupFilterType::TYPE_NAME, $request->id ); $rulesDifference = new BasicDifference($rulesByHostgroup, $request->resourceAccessRules); $rulesToRemove = $rulesDifference->getRemoved(); $rulesToAdd = $rulesDifference->getAdded(); $this->unlinkHostGroupToRAM($rulesToRemove, $request->id); $this->linkHostGroupToRAM($rulesToAdd, $request->id); } /** * Link Host groups to Datasets's Resource Access Rules, * only if the dataset Hostgroup has no parent * * @param int[] $resourceAccessRuleIds * @param int $hostGroupId * * @throws \Throwable */ private function linkHostGroupToRAM(array $resourceAccessRuleIds, int $hostGroupId): void { $datasetFilterRelations = $this->readResourceAccessRepository->findLastLevelDatasetFilterByRuleIdsAndType( $resourceAccessRuleIds, HostGroupFilterType::TYPE_NAME ); foreach ($datasetFilterRelations as $datasetFilterRelation) { /** * Empty $resourceIds are dataset with "All Host Groups" Configured * So we don't want to update it, * as we will loss the "All Host Groups" notion. */ if (! empty($datasetFilterRelation->getResourceIds())) { $resourceIds = $datasetFilterRelation->getResourceIds(); $resourceIds[] = $hostGroupId; $this->writeResourceAccessRepository->updateDatasetResources( $datasetFilterRelation->getDatasetFilterId(), $resourceIds ); $this->linkHostGroupToResourcesACL($hostGroupId, $datasetFilterRelation->getResourceAccessGroupId()); } } } /** * Unlink Host groups to Datasets's Resource Access Rules. * Remove dataset filters if he is empty after removing the hostgroup. * * @param int[] $resourceAccessRuleIds * @param int $hostGroupId * * @throws \Throwable */ private function unlinkHostGroupToRAM(array $resourceAccessRuleIds, int $hostGroupId): void { $datasetFilterRelations = $this->readResourceAccessRepository->findLastLevelDatasetFilterByRuleIdsAndType( $resourceAccessRuleIds, HostGroupFilterType::TYPE_NAME ); foreach ($datasetFilterRelations as $datasetFilterRelation) { /** * Empty $resourceIds are dataset with "All Host Groups" Configured * So we don't want to delete the dataset, and we don't want to update it either, * as we will loss the "All Host Groups" notion. */ if (! empty($datasetFilterRelation->getResourceIds())) { $resourceIdToUpdates = array_filter( $datasetFilterRelation->getResourceIds(), fn ($resourceId) => $resourceId !== $hostGroupId ); if ($resourceIdToUpdates === []) { $this->writeResourceAccessRepository->deleteDatasetFilter($datasetFilterRelation->getDatasetFilterId()); } else { $this->writeResourceAccessRepository->updateDatasetResources($datasetFilterRelation->getDatasetFilterId(), $resourceIdToUpdates); } $this->unlinkHostGroupToResourcesACL($hostGroupId); } } } /** * Signal Monitoring Server Configuration change. * * @param int[] $linkedHostsIds */ private function notifyConfigurationChange(array $linkedHostsIds): void { // Find monitoring servers associated with the linked hosts $serverIds = $this->readMonitoringServerRepository->findByHostsIds($linkedHostsIds); // Notify configuration changes $this->writeMonitoringServerRepository->notifyConfigurationChanges($serverIds); } /** * Unlink Host Groups to user Resource Access Groups * * @param int $hostGroupId * * @throws \Throwable */ private function unlinkHostGroupToResourcesACL(int $hostGroupId): void { if (! $this->user->isAdmin()) { $this->writeAccessGroupRepository->removeLinksBetweenHostGroupAndAccessGroups( $hostGroupId, $this->readAccessGroupRepository->findByContact($this->user) ); } } /** * Link Host Groups to user Resource Access Groups * * @param int $hostGroupId * @param int $datasetId * * @throws \Throwable */ private function linkHostGroupToResourcesACL(int $hostGroupId, int $datasetId): void { if (! $this->user->isAdmin()) { $this->writeAccessGroupRepository->addLinksBetweenHostGroupAndResourceAccessGroup( $hostGroupId, $datasetId ); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Application/UseCase/DeleteHostGroups/DeleteHostGroupsResponse.php
centreon/src/Core/HostGroup/Application/UseCase/DeleteHostGroups/DeleteHostGroupsResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Application\UseCase\DeleteHostGroups; use Core\Application\Common\UseCase\BulkResponseInterface; final class DeleteHostGroupsResponse implements BulkResponseInterface { /** * @param DeleteHostGroupsStatusResponse[] $results */ public function __construct(private readonly array $results) { } /** * {@inheritDoc} * * @return DeleteHostGroupsStatusResponse[] */ public function getData(): array { return $this->results; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Application/UseCase/DeleteHostGroups/DeleteHostGroups.php
centreon/src/Core/HostGroup/Application/UseCase/DeleteHostGroups/DeleteHostGroups.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Application\UseCase\DeleteHostGroups; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Log\LoggerTrait; use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface; use Core\Application\Common\UseCase\NotFoundResponse; use Core\Common\Domain\ResponseCodeEnum; use Core\Contact\Domain\AdminResolver; use Core\HostGroup\Application\Exceptions\HostGroupException; use Core\HostGroup\Application\Repository\ReadHostGroupRepositoryInterface; use Core\HostGroup\Application\Repository\WriteHostGroupRepositoryInterface; use Core\Notification\Application\Repository\ReadNotificationRepositoryInterface; use Core\Notification\Application\Repository\WriteNotificationRepositoryInterface; use Core\ResourceAccess\Application\Repository\ReadResourceAccessRepositoryInterface; use Core\ResourceAccess\Application\Repository\WriteResourceAccessRepositoryInterface; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\Service\Application\Repository\ReadServiceRepositoryInterface; use Core\Service\Application\Repository\WriteServiceRepositoryInterface; use Core\Service\Domain\Model\ServiceRelation; final class DeleteHostGroups { use LoggerTrait; private bool $isUserAdmin = false; public function __construct( private readonly ContactInterface $user, private readonly WriteHostGroupRepositoryInterface $writeHostGroupRepository, private readonly ReadHostGroupRepositoryInterface $readHostGroupRepository, private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository, private readonly ReadNotificationRepositoryInterface $readNotificationRepository, private readonly WriteNotificationRepositoryInterface $writeNotificationRepository, private readonly ReadServiceRepositoryInterface $readServiceRepository, private readonly WriteServiceRepositoryInterface $writeServiceRepository, private readonly ReadResourceAccessRepositoryInterface $readResourceAccessRepository, private readonly WriteResourceAccessRepositoryInterface $writeResourceAccessRepository, private readonly DataStorageEngineInterface $storageEngine, private readonly bool $isCloudPlatform, private readonly AdminResolver $adminResolver, ) { } /** * @param DeleteHostGroupsRequest $request * * @return DeleteHostGroupsResponse */ public function __invoke(DeleteHostGroupsRequest $request): DeleteHostGroupsResponse { $this->isUserAdmin = $this->adminResolver->isAdmin($this->user); $results = []; foreach ($request->hostGroupIds as $hostGroupId) { $statusResponse = new DeleteHostGroupsStatusResponse(); $statusResponse->id = $hostGroupId; try { if (! $this->storageEngine->isAlreadyinTransaction()) { $this->storageEngine->startTransaction(); } if (! $this->hostGroupExists($hostGroupId)) { $statusResponse->status = ResponseCodeEnum::NotFound; $statusResponse->message = (new NotFoundResponse('Host Group'))->getMessage(); $results[] = $statusResponse; continue; } $this->deleteNotificationHostGroupDependency($hostGroupId); $this->deleteServiceRelations($hostGroupId); if ($this->isCloudPlatform) { $this->deleteFromDatasets($hostGroupId); } $this->writeHostGroupRepository->deleteHostGroup($hostGroupId); $this->storageEngine->commitTransaction(); $results[] = $statusResponse; } catch (\Throwable $ex) { if ($this->storageEngine->isAlreadyinTransaction()) { $this->storageEngine->rollbackTransaction(); } $this->error( "Error while deleting host groups : {$ex->getMessage()}", [ 'hostgroupIds' => $request->hostGroupIds, 'current_hostgroupId' => $hostGroupId, 'exception' => ['message' => $ex->getMessage(), 'trace' => $ex->getTraceAsString()], ] ); $statusResponse->status = ResponseCodeEnum::Error; $statusResponse->message = HostGroupException::errorWhileDeleting()->getMessage(); $results[] = $statusResponse; } } return new DeleteHostGroupsResponse($results); } /** * Check that host group exists for the user regarding ACLs. * * @param int $hostGroupId * * @return bool */ private function hostGroupExists(int $hostGroupId): bool { return $this->isUserAdmin ? $this->readHostGroupRepository->existsOne($hostGroupId) : $this->readHostGroupRepository->existsOneByAccessGroups( $hostGroupId, $this->readAccessGroupRepository->findByContact($this->user) ); } /** * If the host group was the last dependency of a notification, we need to delete the Dependency. * * @param int $hostGroupId * * @throws \Throwable */ private function deleteNotificationHostGroupDependency(int $hostGroupId): void { $lastDependencyIds = $this->readNotificationRepository ->findLastNotificationDependencyIdsByHostGroup($hostGroupId); if ($lastDependencyIds !== []) { $this->writeNotificationRepository->deleteDependencies($lastDependencyIds); } } /** * If the host group was the last host group of a service, we need to delete the service. * * @param int $hostGroupId * * @throws \Throwable */ private function deleteServiceRelations(int $hostGroupId): void { $lastRelations = array_filter( $this->readServiceRepository->findServiceRelationsByHostGroupId($hostGroupId), fn (ServiceRelation $relation): bool => $relation->hasOnlyOneHostGroup() ); if ($lastRelations !== []) { $this->writeServiceRepository->deleteByIds( ...array_map(fn (ServiceRelation $relation) => $relation->getServiceId(), $lastRelations) ); } } /** * Delete the host group from the Resource Access datasets. * * @param int $hostGroupId * * @throws \Throwable */ private function deleteFromDatasets(int $hostGroupId): void { $datasetResourceIds = $this->readResourceAccessRepository ->findDatasetResourceIdsByHostGroupId($hostGroupId); foreach ($datasetResourceIds as $datasetFilterId => &$resourceIds) { $resourceIds = array_filter($resourceIds, fn ($resourceId) => $resourceId !== $hostGroupId); if ($resourceIds === []) { $this->writeResourceAccessRepository->deleteDatasetFilter($datasetFilterId); } else { $this->writeResourceAccessRepository->updateDatasetResources($datasetFilterId, $resourceIds); } } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Application/UseCase/DeleteHostGroups/DeleteHostGroupsRequest.php
centreon/src/Core/HostGroup/Application/UseCase/DeleteHostGroups/DeleteHostGroupsRequest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Application\UseCase\DeleteHostGroups; final readonly class DeleteHostGroupsRequest { /** * @param int[] $hostGroupIds */ public function __construct(public array $hostGroupIds) { } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Application/UseCase/DeleteHostGroups/DeleteHostGroupsStatusResponse.php
centreon/src/Core/HostGroup/Application/UseCase/DeleteHostGroups/DeleteHostGroupsStatusResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Application\UseCase\DeleteHostGroups; use Core\Common\Domain\ResponseCodeEnum; final class DeleteHostGroupsStatusResponse { public int $id = 0; public ResponseCodeEnum $status = ResponseCodeEnum::OK; public ?string $message = null; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Application/UseCase/FindHostGroup/FindHostGroupResponse.php
centreon/src/Core/HostGroup/Application/UseCase/FindHostGroup/FindHostGroupResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Application\UseCase\FindHostGroup; final class FindHostGroupResponse { public int $id = 0; public string $name = ''; public string $alias = ''; public string $notes = ''; public string $notesUrl = ''; public string $actionUrl = ''; public ?int $iconId = null; public ?int $iconMapId = null; public ?int $rrdRetention = null; public ?string $geoCoords = null; public string $comment = ''; public bool $isActivated = true; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Application/Exceptions/HostGroupException.php
centreon/src/Core/HostGroup/Application/Exceptions/HostGroupException.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Application\Exceptions; class HostGroupException extends \Exception { public const CODE_CONFLICT = 1; /** * @return self */ public static function accessNotAllowed(): self { return new self(_('You are not allowed to access host groups')); } /** * @return self */ public static function accessNotAllowedForWriting(): self { return new self(_('You are not allowed to perform write operations on host groups')); } /** * @return self */ public static function errorWhileSearching(): self { return new self(_('Error while searching for host groups')); } /** * @return self */ public static function errorWhileRetrieving(): self { return new self(_('Error while retrieving a host group')); } /** * @return self */ public static function errorWhileDeleting(): self { return new self(_('Error while deleting a host group')); } /** * @return self */ public static function errorWhileAdding(): self { return new self(_('Error while adding a host group')); } /** * @return self */ public static function errorWhileUpdating(): self { return new self(_('Error while updating a host group')); } public static function errorWhileEnablingDisabling(): self { return new self(_('Error while enabling/disabling host groups')); } /** * @return self */ public static function errorWhileDuplicating(): self { return new self(_('Error while duplicating a host group')); } /** * @return self */ public static function errorWhileRetrievingJustCreated(): self { return new self(_('Error while retrieving newly created host group')); } /** * @param string $iconName * @param int $iconId * * @return self */ public static function iconDoesNotExist(string $iconName, int $iconId): self { return new self( sprintf( _("The host group icon '%s' with id '%d' does not exist"), $iconName, $iconId ), self::CODE_CONFLICT ); } /** * @param string $hostGroupName * * @return self */ public static function nameAlreadyExists(string $hostGroupName): self { return new self(sprintf(_("The host group name '%s' already exists"), $hostGroupName), self::CODE_CONFLICT); } /** * @return self */ public static function errorResourceAccessRulesEmpty(): self { return new self('The host group must have at least one valid resource access rule', self::CODE_CONFLICT); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Application/Repository/WriteHostGroupRepositoryInterface.php
centreon/src/Core/HostGroup/Application/Repository/WriteHostGroupRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Application\Repository; use Core\HostGroup\Domain\Model\HostGroup; use Core\HostGroup\Domain\Model\NewHostGroup; interface WriteHostGroupRepositoryInterface { /** * Delete a host group. * * @param int $hostGroupId */ public function deleteHostGroup(int $hostGroupId): void; /** * @param NewHostGroup $newHostGroup * * @throws \Throwable * * @return int */ public function add(NewHostGroup $newHostGroup): int; /** * @param HostGroup $hostGroup * * @throws \Throwable */ public function update(HostGroup $hostGroup): void; /** * Link a list of groups to a host. * * @param int $hostId * @param int[] $groupIds * * @throws \Throwable */ public function linkToHost(int $hostId, array $groupIds): void; /** * Unlink a list of groups from a host. * * @param int $hostId * @param int[] $groupIds * * @throws \Throwable */ public function unlinkFromHost(int $hostId, array $groupIds): void; /** * Add a list of hosts to a host group. * * @param int $hostGroupId * @param int[] $hostIds * * @throws \Throwable */ public function addHostLinks(int $hostGroupId, array $hostIds): void; /** * Delete a list of hosts from an host group. * * @param int $hostGroupId * @param int[] $hostIds * @return void */ public function deleteHostLinks(int $hostGroupId, array $hostIds): void; /** * Set an host group as enabled or disabled. * * @param int $hostGroupId * @param bool $isEnable */ public function enableDisableHostGroup(int $hostGroupId, bool $isEnable): void; /** * Duplicate a host group. * * @param int $hostGroupId * @param int $duplicateIndex The index to append to the duplicated host group name * * @throws \Throwable * * @return int The new host group ID */ public function duplicate(int $hostGroupId, int $duplicateIndex): 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/HostGroup/Application/Repository/ReadHostGroupRepositoryInterface.php
centreon/src/Core/HostGroup/Application/Repository/ReadHostGroupRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Application\Repository; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Core\HostGroup\Domain\Model\HostGroup; use Core\HostGroup\Domain\Model\HostGroupNamesById; use Core\HostGroup\Domain\Model\HostGroupRelationCount; use Core\Security\AccessGroup\Domain\Model\AccessGroup; interface ReadHostGroupRepositoryInterface { /** * Find All host groups without acl. * * @param RequestParametersInterface|null $requestParameters * * @throws \Throwable * * @return \Traversable<int, HostGroup>&\Countable */ public function findAll(?RequestParametersInterface $requestParameters = null): \Traversable&\Countable; /** * Find All host groups with access groups. * * @param RequestParametersInterface|null $requestParameters * @param list<int> $accessGroupIds * * @throws \Throwable * * @return \Traversable<HostGroup>&\Countable */ public function findAllByAccessGroupIds(?RequestParametersInterface $requestParameters, array $accessGroupIds): \Traversable&\Countable; /** * Find one host group without acl. * * @param int $hostGroupId * * @throws \Throwable * * @return HostGroup|null */ public function findOne(int $hostGroupId): ?HostGroup; /** * Find one host group with access groups. * * @param int $hostGroupId * @param AccessGroup[] $accessGroups * * @throws \Throwable * * @return HostGroup|null */ public function findOneByAccessGroups(int $hostGroupId, array $accessGroups): ?HostGroup; /** * Tells whether the host group exists. * * @param int $hostGroupId * * @throws \Throwable * * @return bool */ public function existsOne(int $hostGroupId): bool; /** * Tells whether the host group exists but with access groups. * * @param int $hostGroupId * @param AccessGroup[] $accessGroups * * @throws \Throwable * * @return bool */ public function existsOneByAccessGroups(int $hostGroupId, array $accessGroups): bool; /** * Check existence of a list of host groups. * Return the ids of the existing groups. * * @param int[] $hostGroupIds * * @throws \Throwable * * @return int[] */ public function exist(array $hostGroupIds): array; /** * Check existence of a list of host groups by access groups. * Return the ids of the existing groups. * * @param int[] $hostGroupIds * @param AccessGroup[] $accessGroups * * @throws \Throwable * * @return int[] */ public function existByAccessGroups(array $hostGroupIds, array $accessGroups): array; /** * Tells whether the host group name already exists. * This method does not need an acl version of it. * * @param string $hostGroupName * * @throws \Throwable * * @return bool */ public function nameAlreadyExists(string $hostGroupName): bool; /** * Tells whether the host group name already exists by access groups. * * @param string $hostGroupName * @param AccessGroup[] $accessGroups * * @throws \Throwable * * @return bool */ public function nameAlreadyExistsByAccessGroups(string $hostGroupName, array $accessGroups): bool; /** * Find host groups linked to a host (no ACLs). * * @param int $hostId * * @throws \Throwable * * @return HostGroup[] */ public function findByHost(int $hostId): array; /** * Find host groups linked to a host by access groups. * * @param int $hostId * @param AccessGroup[] $accessGroups * * @throws \Throwable * * @return HostGroup[] */ public function findByHostAndAccessGroups(int $hostId, array $accessGroups): array; /** * Find host groups by their ID. * * @param int ...$hostGroupIds * * @throws \Throwable * * @return list<HostGroup> */ public function findByIds(int ...$hostGroupIds): array; /** * Find Host Groups names by their IDs. * * @param int[] $hostGroupIds * * @return HostGroupNamesById */ public function findNames(array $hostGroupIds): HostGroupNamesById; /** * @param int[] $accessGroupIds * * @return bool */ public function hasAccessToAllHostGroups(array $accessGroupIds): bool; /** * @param int[] $hostGroupIds * * @return array<int,HostGroupRelationCount> HostGroupRelationCount indexed by Host Group ID */ public function findHostsCountByIds(array $hostGroupIds): array; /** * @param int[] $hostGroupIds * @param int[] $accessGroupIds * * @return array<int,HostGroupRelationCount> HostGroupRelationCount indexed by Host Group ID */ public function findHostsCountByAccessGroupsIds(array $hostGroupIds, array $accessGroupIds): array; /** * Find hosts associated with a host group. * * @param int $hostGroupId * * @throws \Throwable * * @return int[] */ public function findLinkedHosts(int $hostGroupId): array; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Domain/Model/HostGroupNamesById.php
centreon/src/Core/HostGroup/Domain/Model/HostGroupNamesById.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Domain\Model; use Core\Common\Domain\TrimmedString; class HostGroupNamesById { /** @var array<int,TrimmedString> */ private array $names = []; /** * @param int $hostGroupId * @param TrimmedString $hostGroupName */ public function addName(int $hostGroupId, TrimmedString $hostGroupName): void { $this->names[$hostGroupId] = $hostGroupName; } /** * @param int $hostGroupId * * @return null|string */ public function getName(int $hostGroupId): ?string { return isset($this->names[$hostGroupId]) ? $this->names[$hostGroupId]->value : null; } /** * @return array<int,TrimmedString> */ public function getNames(): array { return $this->names; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Domain/Model/HostGroup.php
centreon/src/Core/HostGroup/Domain/Model/HostGroup.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Domain\Model; use Assert\AssertionFailedException; use Centreon\Domain\Common\Assertion\Assertion; use Core\Common\Domain\Comparable; use Core\Common\Domain\Identifiable; use Core\Domain\Common\GeoCoords; class HostGroup extends NewHostGroup implements Comparable, Identifiable { private int $id; /** * @param int $id * @param string $name * @param string $alias * @param int|null $iconId * @param GeoCoords|null $geoCoords * @param string $comment * @param bool $isActivated * * @throws AssertionFailedException */ public function __construct( int $id, string $name, string $alias = '', ?int $iconId = null, null|GeoCoords $geoCoords = null, string $comment = '', bool $isActivated = true, ) { Assertion::positiveInt($id, 'HostGroup::id'); $this->id = $id; parent::__construct( $name, $alias, $iconId, $geoCoords, $comment, $isActivated, ); } /** * @return int */ public function getId(): int { return $this->id; } public function isEqual(object $object): bool { return $object instanceof self && $object->getName() === $this->name; } public function getEqualityHash(): string { return md5($this->getName()); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Domain/Model/NewHostGroup.php
centreon/src/Core/HostGroup/Domain/Model/NewHostGroup.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Domain\Model; use Assert\AssertionFailedException; use Centreon\Domain\Common\Assertion\Assertion; use Core\Domain\Common\GeoCoords; class NewHostGroup { public const MAX_NAME_LENGTH = 200; public const MIN_NAME_LENGTH = 1; public const MAX_ALIAS_LENGTH = 200; public const MAX_COMMENT_LENGTH = 65535; /** * @param string $name * @param string $alias * @param int|null $iconId FK * @param GeoCoords|null $geoCoords * @param string $comment * @param bool $isActivated * * @throws AssertionFailedException */ public function __construct( protected string $name, protected string $alias = '', protected ?int $iconId = null, protected null|GeoCoords $geoCoords = null, protected string $comment = '', protected bool $isActivated = true, ) { $shortName = (new \ReflectionClass($this))->getShortName(); $this->name = trim($this->name); Assertion::minLength($this->name, self::MIN_NAME_LENGTH, "{$shortName}::name"); Assertion::maxLength($this->name, self::MAX_NAME_LENGTH, "{$shortName}::name"); $this->alias = trim($this->alias); Assertion::maxLength($this->alias, self::MAX_ALIAS_LENGTH, "{$shortName}::alias"); $this->comment = trim($this->comment); Assertion::maxLength($this->comment, self::MAX_COMMENT_LENGTH, "{$shortName}::comment"); if ($iconId !== null) { Assertion::positiveInt($iconId, "{$shortName}::iconId"); } } public function getName(): string { return $this->name; } public function getAlias(): string { return $this->alias; } public function getIconId(): ?int { return $this->iconId; } public function getComment(): string { return $this->comment; } public function isActivated(): bool { return $this->isActivated; } public function getGeoCoords(): ?GeoCoords { return $this->geoCoords; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Domain/Model/HostGroupRelationCount.php
centreon/src/Core/HostGroup/Domain/Model/HostGroupRelationCount.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Domain\Model; class HostGroupRelationCount { public function __construct( public int $enabledHostsCount = 0, public int $disabledHostsCount = 0, ) { } public function setEnabledHostsCount(int $count): void { $this->enabledHostsCount = $count; } public function setDisabledHostsCount(int $count): void { $this->disabledHostsCount = $count; } public function getEnabledHostsCount(): int { return $this->enabledHostsCount; } public function getDisabledHostsCount(): int { return $this->disabledHostsCount; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Domain/Model/HostGroupRelation.php
centreon/src/Core/HostGroup/Domain/Model/HostGroupRelation.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Domain\Model; use Core\Common\Domain\SimpleEntity; use Core\ResourceAccess\Domain\Model\Rule; /** * This class is designed to represent the relation between a hostgroup and its hosts and resource access. */ final class HostGroupRelation { /** * @param HostGroup $hostGroup * @param SimpleEntity[] $hosts * @param Rule[] $resourceAccessRules */ public function __construct( private readonly HostGroup $hostGroup, private readonly array $hosts = [], private readonly array $resourceAccessRules = [], ) { } public function getHostGroup(): HostGroup { return $this->hostGroup; } /** * @return SimpleEntity[] */ public function getHosts(): array { return $this->hosts; } /** * @return Rule[] */ public function getResourceAccessRules(): array { return $this->resourceAccessRules; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Infrastructure/Voters/HostGroupVoters.php
centreon/src/Core/HostGroup/Infrastructure/Voters/HostGroupVoters.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\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 HostGroupVoters extends Voter { public const HOSTGROUP_DELETE = 'hostgroup_delete'; public const HOSTGROUP_ADD = 'hostgroup_add'; public const HOSTGROUP_LIST = 'hostgroup_list'; public const HOSTGROUP_ENABLE_DISABLE = 'hostgroup_enable_disable'; public const HOSTGROUP_DUPLICATE = 'hostgroup_duplicate'; public const HOSTGROUP_UPDATE = 'hostgroup_update'; private const ALLOWED_ATTRIBUTES = [ self::HOSTGROUP_ADD, self::HOSTGROUP_LIST, self::HOSTGROUP_DELETE, self::HOSTGROUP_ENABLE_DISABLE, self::HOSTGROUP_DUPLICATE, self::HOSTGROUP_UPDATE, ]; /** * @inheritDoc */ protected function supports(string $attribute, mixed $subject): bool { return in_array($attribute, self::ALLOWED_ATTRIBUTES, true); } /** * @inheritDoc */ protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool { $user = $token->getUser(); if (! $user instanceof ContactInterface) { return false; } return match ($attribute) { self::HOSTGROUP_LIST => $this->checkUserReadRights($user), self::HOSTGROUP_DELETE, self::HOSTGROUP_ADD, self::HOSTGROUP_ENABLE_DISABLE, self::HOSTGROUP_UPDATE, self::HOSTGROUP_DUPLICATE => $this->checkUserWriteRights($user), default => false, }; } /** * Check that user has rights to perform write operations on host groups. * * @param ContactInterface $user * * @return bool */ private function checkUserWriteRights(ContactInterface $user): bool { return $user->hasTopologyRole(Contact::ROLE_CONFIGURATION_HOSTS_HOST_GROUPS_READ_WRITE); } /** * Check that user has rights to perform read operations on services. * * @param ContactInterface $user * * @return bool */ private function checkUserReadRights(ContactInterface $user): bool { return $user->hasTopologyRole(Contact::ROLE_CONFIGURATION_HOSTS_HOST_GROUPS_READ_WRITE) || $user->hasTopologyRole(Contact::ROLE_CONFIGURATION_HOSTS_HOST_GROUPS_READ); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Infrastructure/Serializer/HostGroupNormalizer.php
centreon/src/Core/HostGroup/Infrastructure/Serializer/HostGroupNormalizer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Infrastructure\Serializer; use Core\Common\Domain\SimpleEntity; use Core\HostGroup\Application\UseCase\FindHostGroups\HostGroupResponse; use Core\HostGroup\Application\UseCase\GetHostGroup\GetHostGroupResponse; use Core\Infrastructure\Common\Api\HttpUrlTrait; use Core\ResourceAccess\Domain\Model\TinyRule; use Symfony\Component\DependencyInjection\Attribute\Autowire; use Symfony\Component\Serializer\Normalizer\NormalizerInterface; final class HostGroupNormalizer implements NormalizerInterface { use HttpUrlTrait; public function __construct( private readonly string $mediaPath, #[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 HostGroupResponse || $data instanceof GetHostGroupResponse; } /** * @param GetHostGroupResponse|HostGroupResponse $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 * @var array{groups?: string[],is_cloud_platform?: bool} $context */ $data = $this->normalizer->normalize($object->hostgroup, $format, $context); if (isset($data['alias']) && $data['alias'] === '') { $data['alias'] = null; } if (isset($data['comment']) && $data['comment'] === '') { $data['comment'] = null; } if (in_array('HostGroup:List', $context['groups'] ?? [], true)) { /** @var HostGroupResponse $object */ $data['icon'] = $object->icon !== null ? [ 'id' => $object->icon->getId(), 'name' => $object->icon->getFilename(), 'url' => $this->generateNormalizedIconUrl($object->icon->getDirectory() . '/' . $object->icon->getFilename()), ] : null; $data['enabled_hosts_count'] = $object->hostsCount ? $object->hostsCount->getEnabledHostsCount() : 0; $data['disabled_hosts_count'] = $object->hostsCount ? $object->hostsCount->getDisabledHostsCount() : 0; } if (in_array('HostGroup:Get', $context['groups'] ?? [], true)) { /** @var GetHostGroupResponse $object */ $data['icon'] = $object->icon !== null ? [ 'id' => $object->icon->getId(), 'name' => $object->icon->getFilename(), 'url' => $this->generateNormalizedIconUrl($object->icon->getDirectory() . '/' . $object->icon->getFilename()), ] : null; $data['hosts'] = array_map( fn (SimpleEntity $host) => $this->normalizer->normalize($host, $format), $object->hosts ); if (true === ($context['is_cloud_platform'] ?? false)) { $data['resource_access_rules'] = array_map( fn (TinyRule $rule) => $this->normalizer->normalize($rule, $format, $context), $object->rules ); } } return $data; } /** * @param ?string $format * @return array<class-string|'*'|'object'|string, bool|null> */ public function getSupportedTypes(?string $format): array { return [ HostGroupResponse::class => true, GetHostGroupResponse::class => true, ]; } /** * @param string|null $url * * @return string|null */ private function generateNormalizedIconUrl(?string $url): ?string { return $url !== null ? $this->getBaseUri() . '/' . $this->mediaPath . '/' . $url : $url; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Infrastructure/Serializer/HostGroupRelationNormalizer.php
centreon/src/Core/HostGroup/Infrastructure/Serializer/HostGroupRelationNormalizer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Infrastructure\Serializer; use Core\Common\Domain\SimpleEntity; use Core\HostGroup\Domain\Model\HostGroupRelation; use Symfony\Component\DependencyInjection\Attribute\Autowire; use Symfony\Component\Serializer\Normalizer\NormalizerInterface; class HostGroupRelationNormalizer implements NormalizerInterface { public function __construct( #[Autowire(service: 'serializer.normalizer.object')] private readonly NormalizerInterface $normalizer, ) { } /** * @param HostGroupRelation $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 * @var array{groups?: string[],is_cloud_platform: bool} $context */ $data = $this->normalizer->normalize($object->getHostGroup(), null, $context); if (isset($data['alias']) && $data['alias'] === '') { $data['alias'] = null; } if (isset($data['comment']) && $data['comment'] === '') { $data['comment'] = null; } $data['hosts'] = array_map( fn (SimpleEntity $host) => $this->normalizer->normalize($host, $format), $object->getHosts() ); if ($context['is_cloud_platform'] === true) { $data['resource_access_rules'] = []; foreach ($object->getResourceAccessRules() as $resourceAccessRule) { $data['resource_access_rules'][] = $this->normalizer->normalize($resourceAccessRule, null, $context); } } return $data; } /** * @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 HostGroupRelation; } /** * @param ?string $format * @return array<class-string|'*'|'object'|string, bool|null> */ public function getSupportedTypes(?string $format): array { return [ HostGroupRelation::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/HostGroup/Infrastructure/Serializer/BulkHostGroupsStatusResponseNormalizer.php
centreon/src/Core/HostGroup/Infrastructure/Serializer/BulkHostGroupsStatusResponseNormalizer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Infrastructure\Serializer; use Centreon\Domain\Log\LoggerTrait; use Core\Common\Domain\ResponseCodeEnum; use Core\HostGroup\Application\UseCase\DeleteHostGroups\DeleteHostGroupsStatusResponse; use Core\HostGroup\Application\UseCase\DuplicateHostGroups\DuplicateHostGroupsStatusResponse; use Core\HostGroup\Application\UseCase\EnableDisableHostGroups\EnableDisableHostGroupsStatusResponse; use Core\Infrastructure\Common\Api\Router; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Serializer\Normalizer\NormalizerInterface; class BulkHostGroupsStatusResponseNormalizer implements NormalizerInterface { use LoggerTrait; private const HOSTGROUP_ROUTE_NAME = 'GetHostGroup'; /** * @param Router $router */ public function __construct( private readonly Router $router, ) { } /** * @param DeleteHostGroupsStatusResponse $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 { return [ 'href' => $this->router->generate(self::HOSTGROUP_ROUTE_NAME, ['hostGroupId' => $object->id]), 'status' => $this->enumToHttpStatusCodeConverter($object->status), 'message' => $object->message, ]; } /** * @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 DeleteHostGroupsStatusResponse || $data instanceof DuplicateHostGroupsStatusResponse || $data instanceof EnableDisableHostGroupsStatusResponse; } /** * @param ?string $format * @return array<class-string|'*'|'object'|string, bool|null> */ public function getSupportedTypes(?string $format): array { return [ DeleteHostGroupsStatusResponse::class => true, DuplicateHostGroupsStatusResponse::class => true, EnableDisableHostGroupsStatusResponse::class => true, ]; } /** * Convert ResponseCodeEnum to HTTP Status Code. * * @param ResponseCodeEnum $code * * @return int */ private function enumToHttpStatusCodeConverter(ResponseCodeEnum $code): int { return match ($code) { ResponseCodeEnum::OK => Response::HTTP_NO_CONTENT, ResponseCodeEnum::NotFound => Response::HTTP_NOT_FOUND, ResponseCodeEnum::Error => Response::HTTP_INTERNAL_SERVER_ERROR, }; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Infrastructure/Repository/DbWriteHostGroupRepository.php
centreon/src/Core/HostGroup/Infrastructure/Repository/DbWriteHostGroupRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Infrastructure\Repository; use Centreon\Domain\Log\LoggerTrait; use Centreon\Infrastructure\DatabaseConnection; use Centreon\Infrastructure\Repository\AbstractRepositoryDRB; use Core\Common\Infrastructure\Repository\RepositoryTrait; use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait; use Core\Common\Infrastructure\RequestParameters\Normalizer\BoolToEnumNormalizer; use Core\HostGroup\Application\Repository\WriteHostGroupRepositoryInterface; use Core\HostGroup\Domain\Model\HostGroup; use Core\HostGroup\Domain\Model\NewHostGroup; use Utility\SqlConcatenator; class DbWriteHostGroupRepository extends AbstractRepositoryDRB implements WriteHostGroupRepositoryInterface { use RepositoryTrait; use LoggerTrait; use SqlMultipleBindTrait; public function __construct(DatabaseConnection $db) { $this->db = $db; } /** * @param int $hostGroupId * * @throws \PDOException */ public function deleteHostGroup(int $hostGroupId): void { $this->info('Delete host group', ['id' => $hostGroupId]); $query = <<<'SQL' DELETE FROM `:db`.`hostgroup` WHERE hg_id = :hostgroup_id SQL; $statement = $this->db->prepare($this->translateDbName($query)); $statement->bindValue(':hostgroup_id', $hostGroupId, \PDO::PARAM_INT); $statement->execute(); } public function update(HostGroup $hostGroup): void { $update = <<<'SQL' UPDATE `:db`.`hostgroup` SET hg_name = :name, hg_alias = :alias, hg_icon_image = :icon_image, geo_coords = :geo_coords, hg_comment = :comment, hg_activate = :activate WHERE hg_id = :hostgroup_id SQL; $statement = $this->db->prepare($this->translateDbName($update)); $statement->bindValue(':hostgroup_id', $hostGroup->getId(), \PDO::PARAM_INT); $this->bindValueOfHostGroup($statement, $hostGroup); $statement->execute(); } /** * @inheritDoc */ public function add(NewHostGroup $newHostGroup): int { $insert = <<<'SQL' INSERT INTO `:db`.`hostgroup` ( hg_name, hg_alias, hg_icon_image, geo_coords, hg_comment, hg_activate ) VALUES ( :name, :alias, :icon_image, :geo_coords, :comment, :activate ) SQL; $statement = $this->db->prepare($this->translateDbName($insert)); $this->bindValueOfHostGroup($statement, $newHostGroup); $statement->execute(); return (int) $this->db->lastInsertId(); } /** * @inheritDoc */ public function linkToHost(int $hostId, array $groupIds): void { if ($groupIds === []) { return; } $bindValues = []; $subQuery = []; foreach ($groupIds as $key => $groupId) { $bindValues[":group_id_{$key}"] = $groupId; $subQuery[] = "(:group_id_{$key}, :host_id)"; } $statement = $this->db->prepare($this->translateDbName( 'INSERT INTO `:db`.`hostgroup_relation` (hostgroup_hg_id, host_host_id) VALUES ' . implode(', ', $subQuery) )); foreach ($bindValues as $key => $value) { $statement->bindValue($key, $value, \PDO::PARAM_INT); } $statement->bindValue(':host_id', $hostId, \PDO::PARAM_INT); $statement->execute(); } /** * @inheritDoc */ public function addHostLinks(int $hostGroupId, array $hostIds): void { if ($hostIds === []) { return; } $bindValues = []; $subQuery = []; foreach ($hostIds as $key => $hostId) { $bindValues[":host_id_{$key}"] = $hostId; $subQuery[] = "(:host_id_{$key}, :group_id)"; } $statement = $this->db->prepare($this->translateDbName( 'INSERT INTO `:db`.`hostgroup_relation` (host_host_id, hostgroup_hg_id) VALUES ' . implode(', ', $subQuery) )); foreach ($bindValues as $key => $value) { $statement->bindValue($key, $value, \PDO::PARAM_INT); } $statement->bindValue(':group_id', $hostGroupId, \PDO::PARAM_INT); $statement->execute(); } /** * @inheritDoc */ public function unlinkFromHost(int $hostId, array $groupIds): void { if ($groupIds === []) { return; } $concatenator = new SqlConcatenator(); $concatenator ->appendWhere('host_host_id = :host_id') ->appendWhere('hostgroup_hg_id in (:group_ids)') ->storeBindValue(':host_id', $hostId, \PDO::PARAM_INT) ->storeBindValueMultiple(':group_ids', $groupIds, \PDO::PARAM_INT); $statement = $this->db->prepare($this->translateDbName( 'DELETE FROM `:db`.`hostgroup_relation`' . $concatenator->__toString() )); $concatenator->bindValuesToStatement($statement); $statement->execute(); } /** * @inheritDoc */ public function enableDisableHostGroup(int $hostGroupId, bool $isEnable): void { $update = <<<'SQL' UPDATE `:db`.`hostgroup` SET hg_activate = :activate WHERE hg_id = :hostgroup_id SQL; $statement = $this->db->prepare($this->translateDbName($update)); $statement->bindValue(':hostgroup_id', $hostGroupId, \PDO::PARAM_INT); $statement->bindValue(':activate', (new BoolToEnumNormalizer())->normalize($isEnable)); $statement->execute(); } /** * @inheritDoc */ public function duplicate(int $hostGroupId, int $duplicateIndex): int { $this->info('Duplicate host group', ['id' => $hostGroupId]); $query = <<<'SQL' INSERT INTO `:db`.`hostgroup` ( hg_name, hg_alias, geo_coords, hg_comment, hg_icon_image, hg_activate ) SELECT CONCAT(hg_name, '_', :duplicateIndex), hg_alias, geo_coords, hg_comment, hg_icon_image, hg_activate FROM `:db`.`hostgroup` WHERE hg_id = :hostgroup_id SQL; $statement = $this->db->prepare($this->translateDbName($query)); $statement->bindValue(':hostgroup_id', $hostGroupId, \PDO::PARAM_INT); $statement->bindValue(':duplicateIndex', $duplicateIndex, \PDO::PARAM_STR); $statement->execute(); return (int) $this->db->lastInsertId(); } public function deleteHostLinks(int $hostGroupId, array $hostIds): void { if ($hostIds === []) { return; } [$bindValues, $bindQuery] = $this->createMultipleBindQuery($hostIds, ':host_id_'); $statement = $this->db->prepare($this->translateDbName( <<<SQL DELETE FROM `:db`.`hostgroup_relation` WHERE hostgroup_hg_id = :hostgroup_id AND host_host_id IN ({$bindQuery}) SQL )); $statement->bindValue(':hostgroup_id', $hostGroupId, \PDO::PARAM_INT); foreach ($bindValues as $key => $value) { $statement->bindValue($key, $value, \PDO::PARAM_INT); } $statement->execute(); } /** * @param \PDOStatement $statement * @param HostGroup|NewHostGroup $newHostGroup */ private function bindValueOfHostGroup(\PDOStatement $statement, HostGroup|NewHostGroup $newHostGroup): void { $statement->bindValue(':name', $newHostGroup->getName()); $statement->bindValue(':alias', $this->emptyStringAsNull($newHostGroup->getAlias())); $statement->bindValue(':icon_image', $newHostGroup->getIconId(), \PDO::PARAM_INT); $statement->bindValue(':geo_coords', $newHostGroup->getGeoCoords()?->__toString()); $statement->bindValue(':comment', $this->emptyStringAsNull($newHostGroup->getComment())); $statement->bindValue(':activate', (new BoolToEnumNormalizer())->normalize($newHostGroup->isActivated())); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Infrastructure/Repository/ApiReadHostGroupRepository.php
centreon/src/Core/HostGroup/Infrastructure/Repository/ApiReadHostGroupRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Infrastructure\Repository; use Centreon\Domain\Repository\RepositoryException; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Core\Common\Infrastructure\Repository\ApiCallIterator; use Core\Common\Infrastructure\Repository\ApiRepositoryTrait; use Core\Common\Infrastructure\Repository\ApiResponseTrait; use Core\HostGroup\Application\Repository\ReadHostGroupRepositoryInterface; use Core\HostGroup\Domain\Model\HostGroup; use Core\HostGroup\Domain\Model\HostGroupNamesById; use Psr\Log\LoggerInterface; use Symfony\Component\Routing\RouterInterface; use Symfony\Contracts\HttpClient\HttpClientInterface; class ApiReadHostGroupRepository implements ReadHostGroupRepositoryInterface { use ApiResponseTrait; use ApiRepositoryTrait; public function __construct( private readonly HttpClientInterface $httpClient, private readonly RouterInterface $router, private readonly LoggerInterface $logger, ) { } /** * @inheritDoc */ public function findNames(array $hostGroupIds): HostGroupNamesById { throw RepositoryException::notYetImplemented(); } /** * @inheritDoc */ public function findAll(?RequestParametersInterface $requestParameters = null): \Traversable&\Countable { if ($requestParameters !== null) { throw RepositoryException::notYetImplemented(); } $apiEndpoint = $this->router->generate('FindHostGroups'); $options = [ 'verify_peer' => true, 'verify_host' => true, 'timeout' => $this->timeout, 'headers' => ['X-AUTH-TOKEN: ' . $this->authenticationToken], ]; if ($this->proxy !== null) { $options['proxy'] = $this->proxy; $this->logger->info('Getting host groups using proxy'); } $debugOptions = $options; unset($debugOptions['headers'][0]); $this->logger->debug('Connexion configuration', [ 'url' => $apiEndpoint, 'options' => $debugOptions, ]); return new ApiCallIterator( $this->httpClient, $this->url . $apiEndpoint, $options, $this->maxItemsByRequest, HostGroupFactory::createFromApi(...), $this->logger ); } /** * @inheritDoc */ public function findAllByAccessGroupIds(?RequestParametersInterface $requestParameters, array $accessGroupIds): \Traversable&\Countable { throw RepositoryException::notYetImplemented(); } /** * @inheritDoc */ public function findOne(int $hostGroupId): ?HostGroup { throw RepositoryException::notYetImplemented(); } /** * @inheritDoc */ public function findOneByAccessGroups(int $hostGroupId, array $accessGroups): ?HostGroup { throw RepositoryException::notYetImplemented(); } /** * @inheritDoc */ public function existsOne(int $hostGroupId): bool { throw RepositoryException::notYetImplemented(); } /** * @inheritDoc */ public function existsOneByAccessGroups(int $hostGroupId, array $accessGroups): bool { throw RepositoryException::notYetImplemented(); } /** * @inheritDoc */ public function exist(array $hostGroupIds): array { throw RepositoryException::notYetImplemented(); } /** * @inheritDoc */ public function existByAccessGroups(array $hostGroupIds, array $accessGroups): array { throw RepositoryException::notYetImplemented(); } /** * @inheritDoc */ public function nameAlreadyExists(string $hostGroupName): bool { throw RepositoryException::notYetImplemented(); } /** * @inheritDoc */ public function nameAlreadyExistsByAccessGroups(string $hostGroupName, array $accessGroups): bool { throw RepositoryException::notYetImplemented(); } /** * @inheritDoc */ public function findByHost(int $hostId): array { throw RepositoryException::notYetImplemented(); } /** * @inheritDoc */ public function findByHostAndAccessGroups(int $hostId, array $accessGroups): array { throw RepositoryException::notYetImplemented(); } /** * @inheritDoc */ public function findByIds(int ...$hostGroupIds): array { throw RepositoryException::notYetImplemented(); } /** * @inheritDoc */ public function hasAccessToAllHostGroups(array $accessGroupIds): bool { throw RepositoryException::notYetImplemented(); } /** * @inheritDoc */ public function findHostsCountByIds(array $hostGroupIds): array { throw RepositoryException::notYetImplemented(); } /** * @inheritDoc */ public function findHostsCountByAccessGroupsIds(array $hostGroupIds, array $accessGroupIds): array { throw RepositoryException::notYetImplemented(); } /** * @inheritDoc */ public function findLinkedHosts(int $hostGroupId): array { throw RepositoryException::notYetImplemented(); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Infrastructure/Repository/DbWriteHostGroupActionLogRepository.php
centreon/src/Core/HostGroup/Infrastructure/Repository/DbWriteHostGroupActionLogRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Infrastructure\Repository; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Log\LoggerTrait; use Centreon\Domain\Repository\RepositoryException; use Centreon\Infrastructure\DatabaseConnection; use Core\ActionLog\Application\Repository\WriteActionLogRepositoryInterface; use Core\ActionLog\Domain\Model\ActionLog; use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB; use Core\Domain\Common\GeoCoords; use Core\HostGroup\Application\Repository\ReadHostGroupRepositoryInterface; use Core\HostGroup\Application\Repository\WriteHostGroupRepositoryInterface; use Core\HostGroup\Domain\Model\HostGroup; use Core\HostGroup\Domain\Model\NewHostGroup; class DbWriteHostGroupActionLogRepository extends AbstractRepositoryRDB implements WriteHostGroupRepositoryInterface { use LoggerTrait; private const HOSTGROUP_PROPERTIES_MAP = [ 'name' => 'hg_name', 'alias' => 'hg_alias', 'iconId' => 'hg_icon_image', 'geoCoords' => 'geo_coords', 'comment' => 'hg_comment', 'isActivated' => 'hg_activate', ]; /** * @param WriteHostGroupRepositoryInterface $writeHostGroupRepository * @param ContactInterface $contact * @param ReadHostGroupRepositoryInterface $readHostGroupRepository * @param WriteActionLogRepositoryInterface $writeActionLogRepository * @param DatabaseConnection $db */ public function __construct( private readonly WriteHostGroupRepositoryInterface $writeHostGroupRepository, private readonly ContactInterface $contact, private readonly ReadHostGroupRepositoryInterface $readHostGroupRepository, private readonly WriteActionLogRepositoryInterface $writeActionLogRepository, DatabaseConnection $db, ) { $this->db = $db; } /** * @inheritDoc */ public function deleteHostGroup(int $hostGroupId): void { try { $hostGroup = $this->readHostGroupRepository->findOne($hostGroupId); if ($hostGroup === null) { throw new RepositoryException('Cannot find hostgroup to delete'); } $this->writeHostGroupRepository->deleteHostGroup($hostGroupId); $actionLog = new ActionLog( ActionLog::OBJECT_TYPE_HOSTGROUP, $hostGroupId, $hostGroup->getName(), ActionLog::ACTION_TYPE_DELETE, $this->contact->getId() ); $this->writeActionLogRepository->addAction($actionLog); } catch (\Throwable $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); throw $ex; } } /** * @inheritDoc */ public function add(NewHostGroup $newHostGroup): int { try { $hostGroupId = $this->writeHostGroupRepository->add($newHostGroup); if ($hostGroupId === 0) { throw new RepositoryException('Hostgroup ID cannot be 0'); } $actionLog = new ActionLog( ActionLog::OBJECT_TYPE_HOSTGROUP, $hostGroupId, $newHostGroup->getName(), ActionLog::ACTION_TYPE_ADD, $this->contact->getId() ); $actionLogId = $this->writeActionLogRepository->addAction($actionLog); $actionLog->setId($actionLogId); $details = $this->getHostGroupPropertiesAsArray($newHostGroup); $this->writeActionLogRepository->addActionDetails($actionLog, $details); return $hostGroupId; } catch (\Throwable $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); throw $ex; } } /** * @inheritDoc */ public function update(HostGroup $hostGroup): void { try { $currentHostGroup = $this->readHostGroupRepository->findOne($hostGroup->getId()); if ($currentHostGroup === null) { throw new RepositoryException('Cannot find hostgroup to update'); } $currentHostGroupDetails = $this->getHostGroupPropertiesAsArray($currentHostGroup); $updatedHostGroupDetails = $this->getHostGroupPropertiesAsArray($hostGroup); $diff = array_diff_assoc($updatedHostGroupDetails, $currentHostGroupDetails); $this->writeHostGroupRepository->update($hostGroup); if (array_key_exists('isActivated', $diff) && count($diff) === 1) { $action = (bool) $diff['isActivated'] ? ActionLog::ACTION_TYPE_ENABLE : ActionLog::ACTION_TYPE_DISABLE; $actionLog = new ActionLog( ActionLog::OBJECT_TYPE_HOSTGROUP, $hostGroup->getId(), $hostGroup->getName(), $action, $this->contact->getId() ); $this->writeActionLogRepository->addAction($actionLog); } if (array_key_exists('isActivated', $diff) && count($diff) > 1) { $action = (bool) $diff['isActivated'] ? ActionLog::ACTION_TYPE_ENABLE : ActionLog::ACTION_TYPE_DISABLE; $actionLog = new ActionLog( ActionLog::OBJECT_TYPE_HOSTGROUP, $hostGroup->getId(), $hostGroup->getName(), $action, $this->contact->getId() ); $this->writeActionLogRepository->addAction($actionLog); $actionLogChange = new ActionLog( ActionLog::OBJECT_TYPE_HOSTGROUP, $hostGroup->getId(), $hostGroup->getName(), ActionLog::ACTION_TYPE_CHANGE, $this->contact->getId() ); $actionLogChangeId = $this->writeActionLogRepository->addAction($actionLogChange); if ($actionLogChangeId === 0) { throw new RepositoryException('Action log ID cannot be 0'); } $actionLogChange->setId($actionLogChangeId); $this->writeActionLogRepository->addActionDetails($actionLogChange, $updatedHostGroupDetails); } if (! array_key_exists('isActivated', $diff) && count($diff) >= 1) { $actionLogChange = new ActionLog( ActionLog::OBJECT_TYPE_HOSTGROUP, $hostGroup->getId(), $hostGroup->getName(), ActionLog::ACTION_TYPE_CHANGE, $this->contact->getId() ); $actionLogChangeId = $this->writeActionLogRepository->addAction($actionLogChange); if ($actionLogChangeId === 0) { throw new RepositoryException('Action log ID cannot be 0'); } $actionLogChange->setId($actionLogChangeId); $this->writeActionLogRepository->addActionDetails($actionLogChange, $updatedHostGroupDetails); } } catch (\Throwable $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); throw $ex; } } /** * @inheritDoc */ public function linkToHost(int $hostId, array $groupIds): void { $this->writeHostGroupRepository->linkToHost($hostId, $groupIds); } /** * @inheritDoc */ public function unlinkFromHost(int $hostId, array $groupIds): void { $this->writeHostGroupRepository->unlinkFromHost($hostId, $groupIds); } public function addHostLinks(int $hostGroupId, array $hostIds): void { $this->writeHostGroupRepository->addHostLinks($hostGroupId, $hostIds); } /** * @inheritDoc */ public function enableDisableHostGroup(int $hostGroupId, bool $isEnable): void { try { $hostGroup = $this->readHostGroupRepository->findOne($hostGroupId); if ($hostGroup === null) { throw new RepositoryException('Cannot find hostgroup to enable/disable'); } $this->writeHostGroupRepository->enableDisableHostGroup($hostGroupId, $isEnable); $actionLog = new ActionLog( ActionLog::OBJECT_TYPE_HOSTGROUP, $hostGroupId, $hostGroup->getName(), $isEnable ? ActionLog::ACTION_TYPE_ENABLE : ActionLog::ACTION_TYPE_DISABLE, $this->contact->getId() ); $this->writeActionLogRepository->addAction($actionLog); } catch (\Throwable $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); throw $ex; } } /** * @inheritDoc */ public function duplicate(int $hostGroupId, int $duplicateIndex): int { try { $newHostGroupId = $this->writeHostGroupRepository->duplicate($hostGroupId, $duplicateIndex); $newHostGroup = $this->readHostGroupRepository->findOne($newHostGroupId); if ($newHostGroupId === 0) { throw new RepositoryException('Hostgroup ID cannot be 0'); } if ($newHostGroup === null) { throw new RepositoryException('Cannot find duplicated hostgroup'); } $actionLog = new ActionLog( ActionLog::OBJECT_TYPE_HOSTGROUP, $newHostGroupId, $newHostGroup->getName(), ActionLog::ACTION_TYPE_ADD, $this->contact->getId() ); $actionLogId = $this->writeActionLogRepository->addAction($actionLog); $actionLog->setId($actionLogId); $details = $this->getHostGroupPropertiesAsArray($newHostGroup); $this->writeActionLogRepository->addActionDetails($actionLog, $details); return $newHostGroupId; } catch (\Throwable $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); throw $ex; } } public function deleteHostLinks(int $hostGroupId, array $hostIds): void { $this->writeHostGroupRepository->deleteHostLinks($hostGroupId, $hostIds); } /** * @param NewHostGroup $hostGroup * * @return array<string,int|bool|string> */ private function getHostGroupPropertiesAsArray(NewHostGroup $hostGroup): array { $hostGroupPropertiesArray = []; $hostGroupReflection = new \ReflectionClass($hostGroup); foreach ($hostGroupReflection->getProperties() as $property) { $propertyName = $property->getName(); $mappedName = self::HOSTGROUP_PROPERTIES_MAP[$propertyName] ?? $propertyName; $value = $property->getValue($hostGroup); if ($value === null) { $value = ''; } if ($value instanceof GeoCoords) { $value = $value->__toString(); } $hostGroupPropertiesArray[$mappedName] = $value; } return $hostGroupPropertiesArray; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Infrastructure/Repository/HostGroupFactory.php
centreon/src/Core/HostGroup/Infrastructure/Repository/HostGroupFactory.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Infrastructure\Repository; use Assert\AssertionFailedException; use Core\Domain\Common\GeoCoords; use Core\HostGroup\Domain\Model\HostGroup; /** * @phpstan-type _DbHostGroup array{ * hg_id: int, * hg_name: string, * hg_alias: ?string, * hg_icon_image: ?int, * geo_coords: ?string, * hg_comment: ?string, * hg_activate: '0'|'1' * } * @phpstan-type _ApiHostGroup array{ * id: int, * name: string, * alias: ?string, * icon_id: ?int, * geo_coords: ?string, * comment: ?string, * is_activated: bool * } */ class HostGroupFactory { /** * @param _DbHostGroup $data * * @throws AssertionFailedException * * @return HostGroup */ public static function createFromDb(array $data): HostGroup { return new HostGroup( id: $data['hg_id'], name: $data['hg_name'], alias: (string) $data['hg_alias'], iconId: $data['hg_icon_image'], geoCoords: match ($geoCoords = $data['geo_coords']) { null, '' => null, default => GeoCoords::fromString($geoCoords), }, comment: (string) $data['hg_comment'], isActivated: (bool) $data['hg_activate'], ); } /** * @param _ApiHostGroup $data * * @throws AssertionFailedException * * @return HostGroup */ public static function createFromApi(array $data): HostGroup { return new HostGroup( id: $data['id'], name: $data['name'], alias: (string) $data['alias'], iconId: $data['icon_id'], geoCoords: match ($geoCoords = $data['geo_coords']) { null, '' => null, default => GeoCoords::fromString($geoCoords), }, comment: (string) $data['comment'], isActivated: (bool) $data['is_activated'], ); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Infrastructure/Repository/HostGroupRepositoryTrait.php
centreon/src/Core/HostGroup/Infrastructure/Repository/HostGroupRepositoryTrait.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Infrastructure\Repository; use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait; trait HostGroupRepositoryTrait { use SqlMultipleBindTrait; /** * @param int[] $accessGroupIds * * @return bool */ public function hasAccessToAllHostGroups(array $accessGroupIds): bool { if ($accessGroupIds === []) { return false; } [$bindValues, $bindQuery] = $this->createMultipleBindQuery($accessGroupIds, ':access_group_id_'); $request = <<<SQL SELECT res.all_hostgroups FROM `:db`.acl_resources res INNER JOIN `:db`.acl_res_group_relations argr ON argr.acl_res_id = res.acl_res_id INNER JOIN `:db`.acl_groups ag ON ag.acl_group_id = argr.acl_group_id WHERE res.acl_res_activate = '1' AND ag.acl_group_id IN ({$bindQuery}) SQL; $statement = $this->db->prepare($this->translateDbName($request)); foreach ($bindValues as $key => $value) { $statement->bindValue($key, $value, \PDO::PARAM_INT); } $statement->execute(); while (false !== ($hasAccessToAll = $statement->fetchColumn())) { if ((bool) $hasAccessToAll === true) { return true; } } return false; } /** * @param int[] $accessGroupIds * * @return string */ private function generateHostGroupAclSubRequest(array $accessGroupIds = []): string { $request = ''; if ( $accessGroupIds !== [] && ! $this->hasAccessToAllHostGroups($accessGroupIds) ) { [, $bindQuery] = $this->createMultipleBindQuery($accessGroupIds, ':access_group_id_'); $request = <<<SQL SELECT arhgr.hg_hg_id FROM `:db`.acl_resources_hg_relations arhgr INNER JOIN `:db`.acl_resources res ON res.acl_res_id = arhgr.acl_res_id INNER JOIN `:db`.acl_res_group_relations argr ON argr.acl_res_id = res.acl_res_id INNER JOIN `:db`.acl_groups ag ON ag.acl_group_id = argr.acl_group_id WHERE ag.acl_group_id IN ({$bindQuery}) SQL; } return $request; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Infrastructure/Repository/DbReadHostGroupRepository.php
centreon/src/Core/HostGroup/Infrastructure/Repository/DbReadHostGroupRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Infrastructure\Repository; use Assert\AssertionFailedException; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Centreon\Infrastructure\DatabaseConnection; use Centreon\Infrastructure\Repository\AbstractRepositoryDRB; use Centreon\Infrastructure\RequestParameters\RequestParametersTranslatorException; use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator; use Core\Common\Domain\TrimmedString; use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait; use Core\Common\Infrastructure\RequestParameters\Normalizer\BoolToEnumNormalizer; use Core\Domain\Common\GeoCoords; use Core\Domain\Exception\InvalidGeoCoordException; use Core\HostCategory\Infrastructure\Repository\HostCategoryRepositoryTrait; use Core\HostGroup\Application\Repository\ReadHostGroupRepositoryInterface; use Core\HostGroup\Domain\Model\HostGroup; use Core\HostGroup\Domain\Model\HostGroupNamesById; use Core\HostGroup\Domain\Model\HostGroupRelationCount; use Core\Security\AccessGroup\Domain\Model\AccessGroup; use Utility\SqlConcatenator; /** * @phpstan-type HostGroupResultSet array{ * hg_id: int, * hg_name: string, * hg_alias: ?string, * hg_icon_image: ?int, * geo_coords: ?string, * hg_comment: ?string, * hg_activate: '0'|'1' * } */ class DbReadHostGroupRepository extends AbstractRepositoryDRB implements ReadHostGroupRepositoryInterface { use SqlMultipleBindTrait; use HostCategoryRepositoryTrait; use HostGroupRepositoryTrait; public function __construct(DatabaseConnection $db) { $this->db = $db; } /** * @inheritDoc */ public function findNames(array $hostGroupIds): HostGroupNamesById { $concatenator = new SqlConcatenator(); $hostGroupIds = array_unique($hostGroupIds); $concatenator->defineSelect( <<<'SQL' SELECT hg.hg_id, hg.hg_name FROM `:db`.hostgroup hg WHERE hg.hg_id IN (:hostGroupIds) SQL ); $concatenator->storeBindValueMultiple(':hostGroupIds', $hostGroupIds, \PDO::PARAM_INT); $statement = $this->db->prepare($this->translateDbName($concatenator->__toString())); $concatenator->bindValuesToStatement($statement); $statement->setFetchMode(\PDO::FETCH_ASSOC); $statement->execute(); $names = new HostGroupNamesById(); foreach ($statement as $record) { /** @var array{hg_id:int,hg_name:string} $record */ $names->addName( $record['hg_id'], new TrimmedString($record['hg_name']) ); } return $names; } /** * @inheritDoc */ public function findAll(?RequestParametersInterface $requestParameters = null): \Traversable&\Countable { $request = <<<'SQL_WRAP' SELECT SQL_CALC_FOUND_ROWS DISTINCT hg.hg_id, hg.hg_name, hg.hg_alias, hg.hg_icon_image, hg.geo_coords, hg.hg_comment, hg.hg_activate FROM `:db`.`hostgroup` hg SQL_WRAP; $sqlTranslator = $requestParameters ? new SqlRequestParametersTranslator($requestParameters) : null; $sqlTranslator?->setConcordanceArray([ 'id' => 'hg.hg_id', 'alias' => 'hg.hg_alias', 'name' => 'hg.hg_name', 'is_activated' => 'hg.hg_activate', 'hostcategory.id' => 'hc.hc_id', 'hostcategory.name' => 'hc.hc_name', ]); $sqlTranslator?->addNormalizer('is_activated', new BoolToEnumNormalizer()); // Update the SQL string builder with the RequestParameters through SqlRequestParametersTranslator $searchRequest = $sqlTranslator?->translateSearchParameterToSql(); // Only JOIN if search request has been provided... if ($searchRequest !== null) { $request .= <<<'SQL' LEFT JOIN `:db`.hostgroup_relation hgr ON hgr.hostgroup_hg_id = hg.hg_id LEFT JOIN `:db`.hostcategories_relation hcr ON hcr.host_host_id = hgr.host_host_id LEFT JOIN `:db`.hostcategories hc ON hc.hc_id = hcr.hostcategories_hc_id AND hc.level IS NULL SQL; } $request .= $searchRequest; // handle sort $sortRequest = $sqlTranslator?->translateSortParameterToSql(); $request .= $sortRequest ?? ' ORDER BY hg.hg_name ASC'; // handle pagination $request .= $sqlTranslator?->translatePaginationToSql(); // Prepare SQL + bind values $statement = $this->db->prepare($this->translateDbName($request)); $sqlTranslator?->bindSearchValues($statement); $statement->setFetchMode(\PDO::FETCH_ASSOC); $statement->execute(); // Calculate the number of rows for the pagination. $sqlTranslator?->calculateNumberOfRows($this->db); $hostGroups = []; foreach ($statement as $record) { /** @var HostGroupResultSet $record */ $hostGroups[] = $this->createHostGroupFromArray($record); } return new \ArrayIterator($hostGroups); } /** * @inheritDoc */ public function findAllByAccessGroupIds(?RequestParametersInterface $requestParameters, array $accessGroupIds): \Traversable&\Countable { if ($accessGroupIds === []) { return new \ArrayIterator([]); } [$bindValues, $bindQuery] = $this->createMultipleBindQuery($accessGroupIds, ':access_group_id_'); $request = <<<'SQL_WRAP' SELECT SQL_CALC_FOUND_ROWS DISTINCT hg.hg_id, hg.hg_name, hg.hg_alias, hg.hg_icon_image, hg.geo_coords, hg.hg_comment, hg.hg_activate FROM `:db`.`hostgroup` hg INNER JOIN `:db`.acl_resources_hg_relations arhr ON hg.hg_id = arhr.hg_hg_id INNER JOIN `:db`.acl_resources res ON arhr.acl_res_id = res.acl_res_id INNER JOIN `:db`.acl_res_group_relations argr ON res.acl_res_id = argr.acl_res_id INNER JOIN `:db`.acl_groups ag ON argr.acl_group_id = ag.acl_group_id SQL_WRAP; $sqlTranslator = $requestParameters ? new SqlRequestParametersTranslator($requestParameters) : null; $sqlTranslator?->setConcordanceArray([ 'id' => 'hg.hg_id', 'alias' => 'hg.hg_alias', 'name' => 'hg.hg_name', 'is_activated' => 'hg.hg_activate', 'hostcategory.id' => 'hc.hc_id', 'hostcategory.name' => 'hc.hc_name', ]); $sqlTranslator?->addNormalizer('is_activated', new BoolToEnumNormalizer()); // Update the SQL string builder with the RequestParameters through SqlRequestParametersTranslator $searchRequest = $sqlTranslator?->translateSearchParameterToSql(); // Only JOIN if search request has been provided... if ($searchRequest !== null) { $hostCategoryAcls = $this->generateHostCategoryAclSubRequest($accessGroupIds); $request .= <<<SQL LEFT JOIN `:db`.hostgroup_relation hgr ON hgr.hostgroup_hg_id = hg.hg_id LEFT JOIN `:db`.hostcategories_relation hcr ON hcr.host_host_id = hgr.host_host_id AND hcr.hostcategories_hc_id IN ({$hostCategoryAcls}) LEFT JOIN `:db`.hostcategories hc ON hc.hc_id = hcr.hostcategories_hc_id AND hc.level IS NULL SQL; } $request .= $searchRequest ? $searchRequest . ' AND ' : ' WHERE '; $request .= <<<SQL ag.acl_group_id IN ({$bindQuery}) SQL; // handle sort $sortRequest = $sqlTranslator?->translateSortParameterToSql(); $request .= $sortRequest ?? ' ORDER BY hg.hg_name ASC'; // handle pagination $request .= $sqlTranslator?->translatePaginationToSql(); // Prepare SQL + bind values $statement = $this->db->prepare($this->translateDbName($request)); $sqlTranslator?->bindSearchValues($statement); foreach ($bindValues as $key => $value) { $statement->bindValue($key, $value, \PDO::PARAM_INT); } $statement->setFetchMode(\PDO::FETCH_ASSOC); $statement->execute(); // Calculate the number of rows for the pagination. $sqlTranslator?->calculateNumberOfRows($this->db); $hostGroups = []; foreach ($statement as $record) { /** @var HostGroupResultSet $record */ $hostGroups[] = $this->createHostGroupFromArray($record); } return new \ArrayIterator($hostGroups); } /** * @inheritDoc */ public function findOne(int $hostGroupId): ?HostGroup { $concatenator = $this->getFindHostGroupConcatenator(); return $this->retrieveHostgroup($concatenator, $hostGroupId); } /** * @inheritDoc */ public function findOneByAccessGroups(int $hostGroupId, array $accessGroups): ?HostGroup { if ($accessGroups === []) { return null; } $accessGroupIds = $this->accessGroupsToIds($accessGroups); if ($this->hasAccessToAllHostGroups($accessGroupIds)) { return $this->findOne($hostGroupId); } $concatenator = $this->getFindHostGroupConcatenator(null, $accessGroupIds); return $this->retrieveHostgroup($concatenator, $hostGroupId); } /** * @inheritDoc */ public function existsOne(int $hostGroupId): bool { $concatenator = $this->getFindHostGroupConcatenator(); return $this->existsHostGroup($concatenator, $hostGroupId); } /** * @inheritDoc */ public function existsOneByAccessGroups(int $hostGroupId, array $accessGroups): bool { if ($accessGroups === []) { return false; } $accessGroupIds = $this->accessGroupsToIds($accessGroups); if ($this->hasAccessToAllHostGroups($accessGroupIds)) { return $this->existsOne($hostGroupId); } $concatenator = $this->getFindHostGroupConcatenator(null, $accessGroupIds); return $this->existsHostGroup($concatenator, $hostGroupId); } /** * @inheritDoc */ public function exist(array $hostGroupIds): array { if ($hostGroupIds === []) { return []; } $concatenator = $this->getFindHostGroupConcatenator(); return $this->existHostGroups($concatenator, $hostGroupIds); } /** * @inheritDoc */ public function existByAccessGroups(array $hostGroupIds, array $accessGroups): array { if ($accessGroups === [] || $hostGroupIds === []) { return []; } $accessGroupIds = $this->accessGroupsToIds($accessGroups); if ($this->hasAccessToAllHostGroups($accessGroupIds)) { return $this->exist($hostGroupIds); } $concatenator = $this->getFindHostGroupConcatenator(null, $accessGroupIds); return $this->existHostGroups($concatenator, $hostGroupIds); } /** * @inheritDoc */ public function nameAlreadyExists(string $hostGroupName): bool { $statement = $this->db->prepare( $this->translateDbName( <<<'SQL' SELECT 1 FROM `:db`.`hostgroup` WHERE hg_name = :name SQL ) ); $statement->bindValue(':name', $hostGroupName); $statement->execute(); return (bool) $statement->fetchColumn(); } public function nameAlreadyExistsByAccessGroups(string $hostGroupName, array $accessGroups): bool { if ($accessGroups === []) { return false; } $accessGroupIds = $this->accessGroupsToIds($accessGroups); if ($this->hasAccessToAllHostGroups($accessGroupIds)) { return $this->nameAlreadyExists($hostGroupName); } $statement = $this->db->prepare( $this->translateDbName( <<<'SQL' SELECT 1 FROM `:db`.`hostgroup` hg INNER JOIN `:db`.acl_resources_hg_relations arhr ON hg.hg_id = arhr.hg_hg_id INNER JOIN `:db`.acl_resources res ON arhr.acl_res_id = res.acl_res_id INNER JOIN `:db`.acl_res_group_relations argr ON res.acl_res_id = argr.acl_res_id INNER JOIN `:db`.acl_groups ag ON argr.acl_group_id = ag.acl_group_id WHERE hg.hg_name = :name AND ag.acl_group_id IN (:ids) SQL ) ); $statement->bindValue(':name', $hostGroupName); $statement->bindValue(':ids', $accessGroupIds, \PDO::PARAM_INT); $statement->execute(); return (bool) $statement->fetchColumn(); } /** * @inheritDoc */ public function findByHost(int $hostId): array { $concatenator = $this->getFindHostGroupConcatenator(); return $this->retrieveHostGroupsByHost($concatenator, $hostId); } /** * @inheritDoc */ public function findByHostAndAccessGroups(int $hostId, array $accessGroups): array { if ($accessGroups === []) { return []; } $accessGroupIds = $this->accessGroupsToIds($accessGroups); if ($this->hasAccessToAllHostGroups($accessGroupIds)) { return $this->findByHost($hostId); } $concatenator = $this->getFindHostGroupConcatenator(null, $accessGroupIds); return $this->retrieveHostGroupsByHost($concatenator, $hostId); } /** * @inheritDoc */ public function findByIds(int ...$hostGroupIds): array { if ($hostGroupIds === []) { return []; } [$bindValues, $hostGroupIdsQuery] = $this->createMultipleBindQuery($hostGroupIds, ':hg_'); $request = <<<SQL SELECT hg.hg_id, hg.hg_name, hg.hg_alias, hg.hg_icon_image, hg.geo_coords, hg.hg_comment, hg.hg_activate FROM `:db`.`hostgroup` hg WHERE hg.hg_id IN ({$hostGroupIdsQuery}) SQL; $statement = $this->db->prepare($this->translateDbName($request)); foreach ($bindValues as $bindKey => $hostGroupId) { $statement->bindValue($bindKey, $hostGroupId, \PDO::PARAM_INT); } $statement->setFetchMode(\PDO::FETCH_ASSOC); $statement->execute(); $hostGroups = []; foreach ($statement as $result) { /** @var HostGroupResultSet $result */ $hostGroups[] = $this->createHostGroupFromArray($result); } return $hostGroups; } /** * @inheritDoc */ public function findHostsCountByIds(array $hostGroupIds): array { [$bindValues, $bindQuery] = $this->createMultipleBindQuery($hostGroupIds, ':hostGroupIds'); $statement = $this->db->prepare($this->translateDbName( <<<SQL SELECT COUNT(h.host_id) as count, hrel.hostgroup_hg_id, IF (h.host_activate = '0', false, true) as is_activated FROM `:db`.host h JOIN `:db`.hostgroup_relation hrel ON h.host_id = hrel.host_host_id WHERE hrel.hostgroup_hg_id IN ({$bindQuery}) GROUP BY hrel.hostgroup_hg_id, is_activated SQL )); foreach ($bindValues as $key => $value) { $statement->bindValue($key, $value, \PDO::PARAM_INT); } $statement->setFetchMode(\PDO::FETCH_ASSOC); $statement->execute(); $results = []; foreach ($statement as $record) { /** @var array{count:int, hostgroup_hg_id:int, is_activated:bool} $record */ $hostGroupId = $record['hostgroup_hg_id']; $count = $record['count']; $results[$hostGroupId] ??= new HostGroupRelationCount(); if ($record['is_activated']) { $results[$hostGroupId]->setEnabledHostsCount($count); } else { $results[$hostGroupId]->setDisabledHostsCount($count); } } return $results; } /** * @inheritDoc */ public function findHostsCountByAccessGroupsIds(array $hostGroupIds, array $accessGroupIds): array { [$bindAclValues, $bindAclQuery] = $this->createMultipleBindQuery($accessGroupIds, ':accessGroupIds'); [$bindValues, $bindQuery] = $this->createMultipleBindQuery($hostGroupIds, ':hostGroupIds'); $statement = $this->db->prepare($this->translateDbName( <<<SQL SELECT DISTINCT hrel.hostgroup_hg_id, h.host_id, IF (h.host_activate = '0', false, true) as is_activated FROM `:db`.host h INNER JOIN `:db`.hostgroup_relation hrel ON h.host_id = hrel.host_host_id INNER JOIN `:dbstg`.centreon_acl acl ON acl.host_id = h.host_id AND acl.service_id IS NULL AND acl.group_id IN ({$bindAclQuery}) WHERE hrel.hostgroup_hg_id IN ({$bindQuery}) SQL )); foreach ($bindValues as $key => $value) { $statement->bindValue($key, $value, \PDO::PARAM_INT); } foreach ($bindAclValues as $key => $value) { $statement->bindValue($key, $value, \PDO::PARAM_INT); } $statement->execute(); $data = $statement->fetchAll(\PDO::FETCH_GROUP | \PDO::FETCH_ASSOC); $results = []; foreach ($data as $hostGroupId => $hosts) { /** @var array<array{host_id:int, is_activated:bool}> $hosts */ $enabled = []; $disabled = []; foreach ($hosts as $host) { if ($host['is_activated']) { $enabled[] = $host['host_id']; } else { $disabled[] = $host['host_id']; } } $results[$hostGroupId] = new HostGroupRelationCount(); $results[$hostGroupId]->setEnabledHostsCount(count(array_unique($enabled))); $results[$hostGroupId]->setDisabledHostsCount(count(array_unique($disabled))); } return $results; } /** * @inheritDoc */ public function findLinkedHosts(int $hostGroupId): array { $statement = $this->db->prepare( $this->translateDbName( <<<'SQL' SELECT DISTINCT hgr.host_host_id FROM `:db`.`hostgroup_relation` hgr JOIN `:db`.`hostgroup` ON hostgroup.hg_id = hgr.hostgroup_hg_id WHERE hgr.hostgroup_hg_id = :hostGroupId SQL ) ); $statement->bindValue(':hostGroupId', $hostGroupId, \PDO::PARAM_INT); $statement->execute(); return $statement->fetchAll(\PDO::FETCH_COLUMN); } /** * @param ?RequestParametersInterface $requestParameters * @param list<int> $accessGroupIds * * @return SqlConcatenator */ private function getFindHostGroupConcatenator( ?RequestParametersInterface $requestParameters = null, array $accessGroupIds = [], ): SqlConcatenator { $concatenator = (new SqlConcatenator()) ->defineSelect( <<<'SQL' SELECT DISTINCT hg.hg_id, hg.hg_name, hg.hg_alias, hg.hg_icon_image, hg.geo_coords, hg.hg_comment, hg.hg_activate SQL ) ->defineFrom( <<<'SQL' FROM `:db`.`hostgroup` hg SQL ) ->defineOrderBy( <<<'SQL' ORDER BY hg.hg_name ASC SQL ); $hostCategoryAcls = ''; if ($accessGroupIds !== []) { if ($this->hasRestrictedAccessToHostCategories($accessGroupIds)) { $hostCategoryAcls = <<<'SQL' AND hcr.hostcategories_hc_id IN ( SELECT arhcr.hc_id FROM `:db`.acl_resources_hc_relations arhcr INNER JOIN `:db`.acl_resources res ON res.acl_res_id = arhcr.acl_res_id INNER JOIN `:db`.acl_res_group_relations argr ON argr.acl_res_id = res.acl_res_id INNER JOIN `:db`.acl_groups ag ON ag.acl_group_id = argr.acl_group_id WHERE ag.acl_group_id IN (:ids) ) SQL; } $concatenator ->appendJoins( <<<'SQL' INNER JOIN `:db`.acl_resources_hg_relations arhr ON hg.hg_id = arhr.hg_hg_id INNER JOIN `:db`.acl_resources res ON arhr.acl_res_id = res.acl_res_id INNER JOIN `:db`.acl_res_group_relations argr ON res.acl_res_id = argr.acl_res_id INNER JOIN `:db`.acl_groups ag ON argr.acl_group_id = ag.acl_group_id SQL ) ->appendWhere( <<<'SQL' WHERE ag.acl_group_id IN (:ids) SQL ) ->storeBindValueMultiple(':ids', $accessGroupIds, \PDO::PARAM_INT); } $search = $requestParameters?->getSearchAsString(); if ($search !== null && \str_contains($search, 'hostcategory')) { $concatenator->appendJoins( <<<SQL LEFT JOIN `:db`.hostgroup_relation hgr ON hgr.hostgroup_hg_id = hg.hg_id LEFT JOIN `:db`.hostcategories_relation hcr ON hcr.host_host_id = hgr.host_host_id {$hostCategoryAcls} LEFT JOIN `:db`.hostcategories hc ON hc.hc_id = hcr.hostcategories_hc_id AND hc.level IS NULL SQL ); } return $concatenator; } /** * @param list<AccessGroup> $accessGroups * * @return list<int> */ private function accessGroupsToIds(array $accessGroups): array { return array_map( static fn (AccessGroup $accessGroup) => $accessGroup->getId(), $accessGroups ); } /** * @param SqlConcatenator $concatenator * @param int $hostId * * @throws InvalidGeoCoordException * @throws RequestParametersTranslatorException * @throws \InvalidArgumentException * @throws \PDOException * @throws AssertionFailedException * * @return list<HostGroup> */ private function retrieveHostGroupsByHost( SqlConcatenator $concatenator, int $hostId, ): array { $concatenator ->appendJoins( <<<'SQL' JOIN `hostgroup_relation` hg_rel ON hg.hg_id = hg_rel.hostgroup_hg_id SQL ) ->appendWhere( <<<'SQL' WHERE hg_rel.host_host_id = :hostId SQL ) ->storeBindValue(':hostId', $hostId, \PDO::PARAM_INT); $statement = $this->db->prepare($this->translateDbName($concatenator->concatAll())); $concatenator->bindValuesToStatement($statement); $statement->setFetchMode(\PDO::FETCH_ASSOC); $statement->execute(); $hostGroups = []; foreach ($statement as $result) { /** @var HostGroupResultSet $result */ $hostGroups[] = $this->createHostGroupFromArray($result); } return $hostGroups; } /** * @param SqlConcatenator $concatenator * @param int $hostGroupId * * @throws \PDOException * * @return bool */ private function existsHostGroup(SqlConcatenator $concatenator, int $hostGroupId): bool { $concatenator // We override the select because we just need to get the ID to check the existence. ->defineSelect( <<<'SQL' SELECT 1 SQL ) // We add the filtering by host group id. ->appendWhere( <<<'SQL' WHERE hg.hg_id = :hostgroup_id SQL ) ->storeBindValue(':hostgroup_id', $hostGroupId, \PDO::PARAM_INT); // Prepare SQL + bind values $statement = $this->db->prepare($this->translateDbName($concatenator->concatAll())); $concatenator->bindValuesToStatement($statement); $statement->execute(); return (bool) $statement->fetchColumn(); } /** * @param SqlConcatenator $concatenator * @param int[] $hostGroupIds * * @throws \PDOException * * @return int[] */ private function existHostGroups(SqlConcatenator $concatenator, array $hostGroupIds): array { $concatenator ->defineSelect( <<<'SQL' SELECT hg.hg_id SQL ) ->appendWhere( <<<'SQL' WHERE hg.hg_id IN (:host_group_ids) SQL ) ->storeBindValueMultiple(':host_group_ids', $hostGroupIds, \PDO::PARAM_INT); // Prepare SQL + bind values $statement = $this->db->prepare($this->translateDbName($concatenator->concatAll())); $concatenator->bindValuesToStatement($statement); $statement->execute(); return $statement->fetchAll(\PDO::FETCH_COLUMN); } /** * @param SqlConcatenator $concatenator * @param int $hostGroupId * * @throws InvalidGeoCoordException * @throws \PDOException * @throws AssertionFailedException * * @return HostGroup|null */ private function retrieveHostgroup(SqlConcatenator $concatenator, int $hostGroupId): ?HostGroup { // We add the filtering by host group id. $concatenator ->appendWhere( <<<'SQL' WHERE hg.hg_id = :hostgroup_id SQL ) ->storeBindValue(':hostgroup_id', $hostGroupId, \PDO::PARAM_INT); // Prepare SQL + bind values $statement = $this->db->prepare($this->translateDbName($concatenator->concatAll())); $concatenator->bindValuesToStatement($statement); $statement->execute(); // Retrieve the first row /** @var null|false|HostGroupResultSet $data */ $data = $statement->fetch(\PDO::FETCH_ASSOC); return $data ? $this->createHostGroupFromArray($data) : null; } /** * @param array $result * * @phpstan-param HostGroupResultSet $result * * @throws AssertionFailedException * @throws InvalidGeoCoordException * * @return HostGroup */ private function createHostGroupFromArray(array $result): HostGroup { return new HostGroup( id: $result['hg_id'], name: $result['hg_name'], alias : (string) $result['hg_alias'], iconId: $result['hg_icon_image'], geoCoords: match ($geoCoords = $result['geo_coords']) { null, '' => null, default => GeoCoords::fromString($geoCoords), }, comment: (string) $result['hg_comment'], isActivated: (bool) $result['hg_activate'], ); } /** * Determines if host categories are filtered for given access group ids * true: accessible host categories are filtered (only specified are accessible) * false: accessible host categories are NOT filtered (all are accessible). * * @param int[] $accessGroupIds * * @phpstan-param non-empty-array<int> $accessGroupIds * * @return bool */ private function hasRestrictedAccessToHostCategories(array $accessGroupIds): bool { $bindValuesArray = []; foreach ($accessGroupIds as $index => $accessGroupId) { $bindValuesArray[':acl_group_id_' . $index] = $accessGroupId; } $bindParamsAsString = \implode(',', \array_keys($bindValuesArray)); $statement = $this->db->prepare($this->translateDbName( <<<SQL SELECT 1 FROM `:db`.acl_resources_hc_relations arhcr INNER JOIN `:db`.acl_resources res ON res.acl_res_id = arhcr.acl_res_id INNER JOIN `:db`.acl_res_group_relations argr ON argr.acl_res_id = res.acl_res_id INNER JOIN `:db`.acl_groups ag ON ag.acl_group_id = argr.acl_group_id WHERE ag.acl_group_id IN ({$bindParamsAsString}) SQL )); foreach ($bindValuesArray as $bindParam => $bindValue) { $statement->bindValue($bindParam, $bindValue, \PDO::PARAM_INT); } $statement->execute(); return (bool) $statement->fetchColumn(); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Infrastructure/API/GetHostGroup/GetHostGroupController.php
centreon/src/Core/HostGroup/Infrastructure/API/GetHostGroup/GetHostGroupController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Infrastructure\API\GetHostGroup; use Centreon\Application\Controller\AbstractController; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\HostGroup\Application\UseCase\GetHostGroup\GetHostGroup; use Core\HostGroup\Infrastructure\Voters\HostGroupVoters; use Core\Infrastructure\Common\Api\StandardPresenter; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Http\Attribute\IsGranted; #[IsGranted( HostGroupVoters::HOSTGROUP_LIST, null, 'You are not allowed to access host groups', Response::HTTP_FORBIDDEN )] final class GetHostGroupController extends AbstractController { public function __invoke( int $hostGroupId, GetHostGroup $useCase, StandardPresenter $presenter, bool $isCloudPlatform, ): Response { $response = $useCase($hostGroupId); if ($response instanceof ResponseStatusInterface) { return $this->createResponse($response); } return JsonResponse::fromJsonString($presenter->present( $response, ['groups' => ['HostGroup:Get'], 'is_cloud_platform' => $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/HostGroup/Infrastructure/API/AddHostGroup/AddHostGroupController.php
centreon/src/Core/HostGroup/Infrastructure/API/AddHostGroup/AddHostGroupController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Infrastructure\API\AddHostGroup; use Centreon\Application\Controller\AbstractController; use Centreon\Domain\Log\LoggerTrait; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\HostGroup\Application\UseCase\AddHostGroup\AddHostGroup; use Core\HostGroup\Infrastructure\Voters\HostGroupVoters; use Core\Infrastructure\Common\Api\StandardPresenter; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Attribute\MapRequestPayload; use Symfony\Component\Security\Http\Attribute\IsGranted; #[IsGranted( HostGroupVoters::HOSTGROUP_ADD, null, 'You are not allowed to add host groups', Response::HTTP_FORBIDDEN )] final class AddHostGroupController extends AbstractController { use LoggerTrait; public function __construct(private readonly bool $isCloudPlatform) { } /** * @param AddHostGroupInput $request * @param AddHostGroup $useCase * @param StandardPresenter $presenter * * @return Response */ public function __invoke( #[MapRequestPayload()] AddHostGroupInput $request, AddHostGroup $useCase, StandardPresenter $presenter, ): Response { $response = $useCase(AddHostGroupRequestTransformer::transform($request, $this->isCloudPlatform)); if ($response instanceof ResponseStatusInterface) { return $this->createResponse($response); } return JsonResponse::fromJsonString( $presenter->present( $response, [ 'groups' => ['HostGroup:Add'], 'is_cloud_platform' => $this->isCloudPlatform, ] ), Response::HTTP_CREATED ); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Infrastructure/API/AddHostGroup/AddHostGroupInput.php
centreon/src/Core/HostGroup/Infrastructure/API/AddHostGroup/AddHostGroupInput.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Infrastructure\API\AddHostGroup; use Core\Common\Domain\PlatformType; use Core\Common\Infrastructure\Validator\Constraints\WhenPlatform; use Symfony\Component\Validator\Constraints as Assert; final class AddHostGroupInput { /** * @param string $name * @param string|null $alias * @param string|null $geoCoords * @param string|null $comment * @param int|null $iconId * @param int[] $hosts * @param int[] $resourceAccessRules */ public function __construct( #[Assert\NotNull()] #[Assert\Type('string')] public readonly mixed $name, #[Assert\Type('string')] public readonly mixed $alias, #[Assert\Type('string')] public readonly mixed $geoCoords, #[Assert\Type('string')] public readonly mixed $comment, #[Assert\Type('integer')] public readonly mixed $iconId, #[Assert\NotNull()] #[Assert\Type('array')] #[Assert\All( new Assert\Type('integer') )] public readonly mixed $hosts, /** * This field MUST NOT be used outside of a CLOUD Platform Context. */ #[WhenPlatform(PlatformType::CLOUD, [ new Assert\NotNull(), new Assert\Type('array'), new Assert\All( new Assert\Type('integer') ), new Assert\Count(min: 1), ])] public readonly mixed $resourceAccessRules, ) { } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Infrastructure/API/AddHostGroup/AddHostGroupRequestTransformer.php
centreon/src/Core/HostGroup/Infrastructure/API/AddHostGroup/AddHostGroupRequestTransformer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Infrastructure\API\AddHostGroup; use Core\HostGroup\Application\UseCase\AddHostGroup\AddHostGroupRequest; final class AddHostGroupRequestTransformer { /** * @param AddHostGroupInput $input * @param bool $isCloudPlatform * @return AddHostGroupRequest */ public static function transform(AddHostGroupInput $input, bool $isCloudPlatform): AddHostGroupRequest { return new AddHostGroupRequest( name: $input->name, alias: (string) $input->alias, geoCoords: $input->geoCoords, comment: (string) $input->comment, iconId: $input->iconId, hosts: $input->hosts, resourceAccessRules: $isCloudPlatform ? $input->resourceAccessRules : [] ); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Infrastructure/API/FindHostGroups/FindHostGroupsController.php
centreon/src/Core/HostGroup/Infrastructure/API/FindHostGroups/FindHostGroupsController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Infrastructure\API\FindHostGroups; use Centreon\Application\Controller\AbstractController; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\HostGroup\Application\UseCase\FindHostGroups\FindHostGroups; use Core\HostGroup\Infrastructure\Voters\HostGroupVoters; use Core\Infrastructure\Common\Api\StandardPresenter; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Http\Attribute\IsGranted; #[IsGranted( HostGroupVoters::HOSTGROUP_LIST, null, 'You are not allowed to access host groups', Response::HTTP_FORBIDDEN )] final class FindHostGroupsController extends AbstractController { public function __invoke( FindHostGroups $useCase, StandardPresenter $presenter, ): Response { $response = $useCase(); if ($response instanceof ResponseStatusInterface) { return $this->createResponse($response); } return JsonResponse::fromJsonString($presenter->present($response, ['groups' => ['HostGroup:List']])); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Infrastructure/API/DuplicateHostGroups/DuplicateHostGroupsInput.php
centreon/src/Core/HostGroup/Infrastructure/API/DuplicateHostGroups/DuplicateHostGroupsInput.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Infrastructure\API\DuplicateHostGroups; use Symfony\Component\Validator\Constraints as Assert; final class DuplicateHostGroupsInput { /** * @param int[] $ids * @param int $nbDuplicates */ public function __construct( #[Assert\NotNull()] #[Assert\Type('array')] #[Assert\All( new Assert\Type('integer') )] public readonly array $ids, #[Assert\NotNull()] #[Assert\Type('integer')] public readonly int $nbDuplicates, ) { } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Infrastructure/API/DuplicateHostGroups/DuplicateHostGroupsController.php
centreon/src/Core/HostGroup/Infrastructure/API/DuplicateHostGroups/DuplicateHostGroupsController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Infrastructure\API\DuplicateHostGroups; use Centreon\Application\Controller\AbstractController; use Core\HostGroup\Application\UseCase\DuplicateHostGroups\DuplicateHostGroups; use Core\HostGroup\Infrastructure\Voters\HostGroupVoters; use Core\Infrastructure\Common\Api\StandardPresenter; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Attribute\MapRequestPayload; use Symfony\Component\Security\Http\Attribute\IsGranted; #[IsGranted( HostGroupVoters::HOSTGROUP_DUPLICATE, null, 'You are not allowed to duplicate host groups', Response::HTTP_FORBIDDEN )] final class DuplicateHostGroupsController extends AbstractController { public function __invoke( DuplicateHostGroups $useCase, #[MapRequestPayload()] DuplicateHostGroupsInput $request, StandardPresenter $presenter, ): Response { $response = $useCase(DuplicateHostGroupsRequestTransformer::transform($request)); return JsonResponse::fromJsonString($presenter->present($response)); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Infrastructure/API/DuplicateHostGroups/DuplicateHostGroupsRequestTransformer.php
centreon/src/Core/HostGroup/Infrastructure/API/DuplicateHostGroups/DuplicateHostGroupsRequestTransformer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Infrastructure\API\DuplicateHostGroups; use Core\HostGroup\Application\UseCase\DuplicateHostGroups\DuplicateHostGroupsRequest; final class DuplicateHostGroupsRequestTransformer { public static function transform(DuplicateHostGroupsInput $input): DuplicateHostGroupsRequest { return new DuplicateHostGroupsRequest($input->ids, $input->nbDuplicates); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Infrastructure/API/DeleteHostGroup/DeleteHostGroupController.php
centreon/src/Core/HostGroup/Infrastructure/API/DeleteHostGroup/DeleteHostGroupController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Infrastructure\API\DeleteHostGroup; use Centreon\Application\Controller\AbstractController; use Core\HostGroup\Application\UseCase\DeleteHostGroup\DeleteHostGroup; use Core\Infrastructure\Common\Api\DefaultPresenter; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Exception\AccessDeniedException; final class DeleteHostGroupController extends AbstractController { /** * @param int $hostGroupId * @param DeleteHostGroup $useCase * @param DefaultPresenter $presenter * * @throws AccessDeniedException * * @return Response */ public function __invoke( int $hostGroupId, DeleteHostGroup $useCase, DefaultPresenter $presenter, ): Response { $this->denyAccessUnlessGrantedForAPIConfiguration(); $useCase($hostGroupId, $presenter); return $presenter->show(); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Infrastructure/API/EnableDisableHostGroups/EnableDisableHostGroupsInput.php
centreon/src/Core/HostGroup/Infrastructure/API/EnableDisableHostGroups/EnableDisableHostGroupsInput.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Infrastructure\API\EnableDisableHostGroups; use Symfony\Component\Validator\Constraints as Assert; final class EnableDisableHostGroupsInput { /** * @param int[] $ids */ public function __construct( #[Assert\NotNull()] #[Assert\Type('array')] #[Assert\All( new Assert\Type('integer') )] public readonly mixed $ids, ) { } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Infrastructure/API/EnableDisableHostGroups/EnableDisableHostGroupsRequestTransformer.php
centreon/src/Core/HostGroup/Infrastructure/API/EnableDisableHostGroups/EnableDisableHostGroupsRequestTransformer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Infrastructure\API\EnableDisableHostGroups; use Core\HostGroup\Application\UseCase\EnableDisableHostGroups\EnableDisableHostGroupsRequest; final class EnableDisableHostGroupsRequestTransformer { /** * @param EnableDisableHostGroupsInput $input * @param string $action * * @return EnableDisableHostGroupsRequest */ public static function transform(EnableDisableHostGroupsInput $input, string $action): EnableDisableHostGroupsRequest { $action = ltrim($action, '_'); return new EnableDisableHostGroupsRequest($input->ids, $action === 'enable'); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Infrastructure/API/EnableDisableHostGroups/EnableDisableHostGroupsController.php
centreon/src/Core/HostGroup/Infrastructure/API/EnableDisableHostGroups/EnableDisableHostGroupsController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Infrastructure\API\EnableDisableHostGroups; use Centreon\Application\Controller\AbstractController; use Core\HostGroup\Application\UseCase\EnableDisableHostGroups\EnableDisableHostGroups; use Core\HostGroup\Infrastructure\Voters\HostGroupVoters; use Core\Infrastructure\Common\Api\StandardPresenter; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Attribute\MapRequestPayload; use Symfony\Component\Security\Http\Attribute\IsGranted; #[IsGranted( HostGroupVoters::HOSTGROUP_ENABLE_DISABLE, null, 'You are not allowed to enable or disable host groups', Response::HTTP_FORBIDDEN )] final class EnableDisableHostGroupsController extends AbstractController { public function __invoke( string $action, EnableDisableHostGroups $useCase, #[MapRequestPayload()] EnableDisableHostGroupsInput $request, StandardPresenter $presenter, ): Response { $response = $useCase(EnableDisableHostGroupsRequestTransformer::transform($request, $action)); return JsonResponse::fromJsonString($presenter->present($response)); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Infrastructure/API/UpdateHostGroup/UpdateHostGroupRequestTransformer.php
centreon/src/Core/HostGroup/Infrastructure/API/UpdateHostGroup/UpdateHostGroupRequestTransformer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Infrastructure\API\UpdateHostGroup; use Core\HostGroup\Application\UseCase\UpdateHostGroup\UpdateHostGroupRequest; final class UpdateHostGroupRequestTransformer { /** * @param UpdateHostGroupInput $input * @param bool $isCloudPlatform * @param int $hostGroupId * * @return UpdateHostGroupRequest */ public static function transform( UpdateHostGroupInput $input, int $hostGroupId, bool $isCloudPlatform, ): UpdateHostGroupRequest { return new UpdateHostGroupRequest( id: $hostGroupId, name: $input->name, alias: (string) $input->alias, geoCoords: $input->geoCoords, comment: (string) $input->comment, iconId: $input->iconId, hosts: $input->hosts, resourceAccessRules: $isCloudPlatform ? $input->resourceAccessRules : [] ); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Infrastructure/API/UpdateHostGroup/UpdateHostGroupController.php
centreon/src/Core/HostGroup/Infrastructure/API/UpdateHostGroup/UpdateHostGroupController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Infrastructure\API\UpdateHostGroup; use Centreon\Application\Controller\AbstractController; use Core\HostGroup\Application\UseCase\UpdateHostGroup\UpdateHostGroup; use Core\HostGroup\Infrastructure\Voters\HostGroupVoters; use Core\Infrastructure\Common\Api\StandardPresenter; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Attribute\MapRequestPayload; use Symfony\Component\Security\Http\Attribute\IsGranted; #[IsGranted( HostGroupVoters::HOSTGROUP_UPDATE, null, 'Your are not allowed to edit host groups', Response::HTTP_FORBIDDEN )] final class UpdateHostGroupController extends AbstractController { public function __construct(private readonly bool $isCloudPlatform) { } /** * @param int $hostGroupId * @param UpdateHostGroupInput $request * @param UpdateHostGroup $useCase * @param StandardPresenter $presenter * * @return Response */ public function __invoke( int $hostGroupId, #[MapRequestPayload()] UpdateHostGroupInput $request, UpdateHostGroup $useCase, StandardPresenter $presenter, ): Response { $response = $useCase(UpdateHostGroupRequestTransformer::transform( $request, $hostGroupId, $this->isCloudPlatform )); return $this->createResponse($response); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Infrastructure/API/UpdateHostGroup/UpdateHostGroupInput.php
centreon/src/Core/HostGroup/Infrastructure/API/UpdateHostGroup/UpdateHostGroupInput.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Infrastructure\API\UpdateHostGroup; use Core\Common\Domain\PlatformType; use Core\Common\Infrastructure\Validator\Constraints\WhenPlatform; use Symfony\Component\Validator\Constraints as Assert; final class UpdateHostGroupInput { /** * Undocumented function * * @param string $name * @param string|null $alias * @param string|null $geoCoords * @param string|null $comment * @param int|null $iconId * @param int[] $hosts * @param int[] $resourceAccessRules */ public function __construct( #[Assert\NotNull()] #[Assert\Type('string')] public readonly mixed $name, #[Assert\Type('string')] public readonly mixed $alias, #[Assert\Type('string')] public readonly mixed $geoCoords, #[Assert\Type('string')] public readonly mixed $comment, #[Assert\Type('integer')] public readonly mixed $iconId, #[Assert\NotNull()] #[Assert\Type('array')] #[Assert\All( new Assert\Type('integer') )] public readonly mixed $hosts, /** * This field MUST NOT be used outside of a Cloud Platform Context. */ #[WhenPlatform(PlatformType::CLOUD, [ new Assert\NotNull(), new Assert\Type('array'), new Assert\All( new Assert\Type('integer') ), new Assert\Count(min: 1), ])] public readonly mixed $resourceAccessRules, ) { } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Infrastructure/API/DeleteHostGroups/DeleteHostGroupsInput.php
centreon/src/Core/HostGroup/Infrastructure/API/DeleteHostGroups/DeleteHostGroupsInput.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Infrastructure\API\DeleteHostGroups; use Symfony\Component\Validator\Constraints as Assert; final class DeleteHostGroupsInput { /** * @param int[] $ids */ public function __construct( #[Assert\NotNull()] #[Assert\Type('array')] #[Assert\All( new Assert\Type('integer') )] public readonly mixed $ids, ) { } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Infrastructure/API/DeleteHostGroups/DeleteHostGroupsRequestTransformer.php
centreon/src/Core/HostGroup/Infrastructure/API/DeleteHostGroups/DeleteHostGroupsRequestTransformer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Infrastructure\API\DeleteHostGroups; use Core\HostGroup\Application\UseCase\DeleteHostGroups\DeleteHostGroupsRequest; final class DeleteHostGroupsRequestTransformer { /** * @param DeleteHostGroupsInput $input * * @return DeleteHostGroupsRequest */ public static function transform(DeleteHostGroupsInput $input): DeleteHostGroupsRequest { return new DeleteHostGroupsRequest($input->ids); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostGroup/Infrastructure/API/DeleteHostGroups/DeleteHostGroupsController.php
centreon/src/Core/HostGroup/Infrastructure/API/DeleteHostGroups/DeleteHostGroupsController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostGroup\Infrastructure\API\DeleteHostGroups; use Centreon\Application\Controller\AbstractController; use Core\HostGroup\Application\UseCase\DeleteHostGroups\DeleteHostGroups; use Core\Infrastructure\Common\Api\StandardPresenter; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Attribute\MapRequestPayload; use Symfony\Component\Security\Http\Attribute\IsGranted; #[IsGranted( 'hostgroup_delete', null, 'You are not allowed to delete host groups', Response::HTTP_FORBIDDEN )] final class DeleteHostGroupsController extends AbstractController { public function __invoke( DeleteHostGroups $useCase, #[MapRequestPayload()] DeleteHostGroupsInput $request, StandardPresenter $presenter, ): Response { $response = $useCase(DeleteHostGroupsRequestTransformer::transform($request)); return JsonResponse::fromJsonString($presenter->present($response)); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Engine/Application/Exception/EngineSecretsDoesNotExistException.php
centreon/src/Core/Engine/Application/Exception/EngineSecretsDoesNotExistException.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Engine\Application\Exception; final class EngineSecretsDoesNotExistException extends \InvalidArgumentException { public function __construct( string $message = 'Engine secrets do not exist.', int $code = 0, \Throwable|null $previous = null, ) { parent::__construct($message, $code, $previous); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Engine/Application/Exception/EngineSecretsBadFormatException.php
centreon/src/Core/Engine/Application/Exception/EngineSecretsBadFormatException.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Engine\Application\Exception; final class EngineSecretsBadFormatException extends \InvalidArgumentException { public function __construct( string $message = 'Engine secrets are not well formated.', int $code = 0, \Throwable|null $previous = null, ) { parent::__construct($message, $code, $previous); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Engine/Application/Repository/EngineRepositoryInterface.php
centreon/src/Core/Engine/Application/Repository/EngineRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Engine\Application\Repository; use Centreon\Domain\Common\Assertion\AssertionException; use Core\Common\Domain\Exception\RepositoryException; use Core\Engine\Domain\Model\EngineSecrets; interface EngineRepositoryInterface { /** * Get engine secrets. * * @throws RepositoryException|AssertionException * @return EngineSecrets */ public function getEngineSecrets(): EngineSecrets; /** * Update engine secrets. * * @throws RepositoryException */ public function writeEngineSecrets(EngineSecrets $engineSecrets): void; /** * Check that Engine Context has content. * * @throws RepositoryException */ public function engineSecretsHasContent(): 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/Engine/Domain/Model/EngineKey.php
centreon/src/Core/Engine/Domain/Model/EngineKey.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Engine\Domain\Model; use Centreon\Domain\Common\Assertion\Assertion; final readonly class EngineKey { public function __construct(public string $key) { Assertion::notEmptyString($key, 'EngineKey::key'); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Engine/Domain/Model/EngineSecrets.php
centreon/src/Core/Engine/Domain/Model/EngineSecrets.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Engine\Domain\Model; final readonly class EngineSecrets { public function __construct( public EngineKey $firstKey, public EngineKey $secondKey, ) { } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Engine/Infrastructure/Serializer/EngineSecretsNormalizer.php
centreon/src/Core/Engine/Infrastructure/Serializer/EngineSecretsNormalizer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Engine\Infrastructure\Serializer; use Core\Engine\Domain\Model\EngineSecrets; use Symfony\Component\DependencyInjection\Attribute\Autowire; use Symfony\Component\Serializer\Normalizer\NormalizerInterface; class EngineSecretsNormalizer implements NormalizerInterface { public function __construct( #[Autowire(service: 'serializer.normalizer.object')] private readonly NormalizerInterface $normalizer, ) { } /** * @param EngineSecrets $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{app_secret: array{key: string}, salt: array{key: string}} $data */ $data = $this->normalizer->normalize($object, $format, $context); return array_map(fn ($property) => $property['key'], $data); } /** * @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 EngineSecrets; } /** * @param ?string $format * @return array<class-string|'*'|'object'|string, bool|null> */ public function getSupportedTypes(?string $format): array { return [ EngineSecrets::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/Engine/Infrastructure/Repository/FsEngineRepository.php
centreon/src/Core/Engine/Infrastructure/Repository/FsEngineRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Engine\Infrastructure\Repository; use Core\Common\Domain\Exception\RepositoryException; use Core\Engine\Application\Exception\EngineSecretsBadFormatException; use Core\Engine\Application\Exception\EngineSecretsDoesNotExistException; use Core\Engine\Application\Repository\EngineRepositoryInterface; use Core\Engine\Domain\Model\EngineKey; use Core\Engine\Domain\Model\EngineSecrets; use Symfony\Component\Filesystem\Exception\IOException; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Serializer\Exception\ExceptionInterface; use Symfony\Component\Serializer\SerializerInterface; final readonly class FsEngineRepository implements EngineRepositoryInterface { private Filesystem $filesystem; public function __construct( private string $engineContextPath, private SerializerInterface $serializer, ) { $this->filesystem = new Filesystem(); } public function getEngineSecrets(): EngineSecrets { try { $engineContextContent = $this->filesystem->readFile($this->engineContextPath); $engineContext = json_decode($engineContextContent, true, flags: JSON_THROW_ON_ERROR); return new EngineSecrets( new EngineKey($engineContext['app_secret']), new EngineKey($engineContext['salt']) ); } catch (IOException $ex) { throw new EngineSecretsDoesNotExistException(previous: $ex); } catch (\JsonException $ex) { throw new EngineSecretsBadFormatException(previous: $ex); } } public function writeEngineSecrets(EngineSecrets $engineSecrets): void { try { if ($this->engineSecretsHasContent()) { throw new RepositoryException( 'engine-context already has content, unable to write in the file', ['path' => $this->engineContextPath] ); } $engineContent = $this->serializer->serialize($engineSecrets, 'json'); // Don't use the Filesystem::dumpFile method here because it will override the rights of the file. file_put_contents($this->engineContextPath, $engineContent); } catch (IOException $ex) { throw new RepositoryException( 'Unable to write content of engine-context file. check that file exists', [ 'path' => $this->engineContextPath, 'exception' => $ex, ] ); } catch (ExceptionInterface $ex) { throw new RepositoryException( 'Unable to serialize content for engine-context file', ['path' => $this->engineContextPath, 'exception' => $ex] ); } } public function engineSecretsHasContent(): bool { try { return ! empty($this->filesystem->readFile($this->engineContextPath)); } catch (IOException $ex) { throw new RepositoryException( 'Unable to get content of engine-context file. check that file exists', ['path' => $this->engineContextPath, 'exception' => $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/Engine/Infrastructure/API/GetEngineSecrets/GetEngineSecretsController.php
centreon/src/Core/Engine/Infrastructure/API/GetEngineSecrets/GetEngineSecretsController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Engine\Infrastructure\API\GetEngineSecrets; use Centreon\Application\Controller\AbstractController; use Centreon\Domain\Common\Assertion\AssertionException; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\InvalidArgumentResponse; use Core\Common\Infrastructure\ExceptionLogger\ExceptionLogger; use Core\Engine\Application\Exception\EngineSecretsBadFormatException; use Core\Engine\Application\Exception\EngineSecretsDoesNotExistException; use Core\Engine\Application\Repository\EngineRepositoryInterface; use Symfony\Component\ExpressionLanguage\Expression; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Attribute\Route; use Symfony\Component\Security\Http\Attribute\CurrentUser; use Symfony\Component\Security\Http\Attribute\IsGranted; use Symfony\Component\Serializer\SerializerInterface; final class GetEngineSecretsController extends AbstractController { public function __construct( private readonly SerializerInterface $serializer, private readonly EngineRepositoryInterface $engineRepository, ) { } #[Route(path: '/administration/engine/secrets', name: 'GetEngineSecrets', methods: ['GET'])] #[IsGranted( new Expression('subject.isAdmin() === true'), subject: new Expression('args["currentUser"]'), message:'You must be an admin to access engine secrets', statusCode: Response::HTTP_FORBIDDEN )] public function __invoke(#[CurrentUser] ContactInterface $currentUser): Response { try { $engineSecrets = $this->engineRepository->getEngineSecrets(); return JsonResponse::fromJsonString( $this->serializer->serialize($engineSecrets, 'json') ); } catch (EngineSecretsDoesNotExistException|EngineSecretsBadFormatException $ex) { ExceptionLogger::create()->log($ex); return $this->createResponse(new ErrorResponse($ex->getMessage())); } catch (AssertionException $ex) { ExceptionLogger::create()->log($ex); return $this->createResponse(new InvalidArgumentResponse($ex->getMessage())); } catch (\Throwable $ex) { ExceptionLogger::create()->log($ex); return $this->createResponse(new ErrorResponse('Unable to retrieve engine secrets')); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/UserProfile/Application/Repository/ReadUserProfileRepositoryInterface.php
centreon/src/Core/UserProfile/Application/Repository/ReadUserProfileRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\UserProfile\Application\Repository; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Repository\RepositoryException; use Core\UserProfile\Domain\Model\UserProfile; interface ReadUserProfileRepositoryInterface { /** * @param ContactInterface $contact * * @throws RepositoryException * @return UserProfile|null */ public function findByContact(ContactInterface $contact): ?UserProfile; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/UserProfile/Application/Repository/WriteUserProfileRepositoryInterface.php
centreon/src/Core/UserProfile/Application/Repository/WriteUserProfileRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\UserProfile\Application\Repository; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Repository\RepositoryException; interface WriteUserProfileRepositoryInterface { /** * @param int $profileId * @param int $dashboardId * * @throws RepositoryException */ public function addDashboardAsFavorites(int $profileId, int $dashboardId): void; /** * @param int $profileId * @param int $dashboardId * * @throws RepositoryException */ public function removeDashboardFromFavorites(int $profileId, int $dashboardId): void; /** * @param ContactInterface $contact * * @throws RepositoryException * @return int */ public function addDefaultProfileForUser(ContactInterface $contact): 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/UserProfile/Domain/Model/UserProfile.php
centreon/src/Core/UserProfile/Domain/Model/UserProfile.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\UserProfile\Domain\Model; final class UserProfile { /** @var int[] */ private array $favoriteDashboards = []; /** * @param int $id * @param int $userId */ public function __construct( private readonly int $id, private readonly int $userId, ) { } /** * @param int $dashboardId */ public function addFavoriteDashboard(int $dashboardId): void { $this->favoriteDashboards[] = $dashboardId; } /** * @param int[] $dashboardIds * @return self */ public function setFavoriteDashboards(array $dashboardIds): self { foreach ($dashboardIds as $dashboardId) { $this->addFavoriteDashboard($dashboardId); } return $this; } /** * @return int[] */ public function getFavoriteDashboards(): array { return $this->favoriteDashboards; } /** * @return int */ public function getId(): int { return $this->id; } /** * @return int */ public function getUserId(): int { return $this->userId; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/UserProfile/Infrastructure/Repository/DbWriteUserProfileRepository.php
centreon/src/Core/UserProfile/Infrastructure/Repository/DbWriteUserProfileRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\UserProfile\Infrastructure\Repository; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Log\LoggerTrait; use Centreon\Domain\Repository\RepositoryException; use Centreon\Infrastructure\DatabaseConnection; use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB; use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait; use Core\UserProfile\Application\Repository\WriteUserProfileRepositoryInterface; use PDO; use PDOException; final class DbWriteUserProfileRepository extends AbstractRepositoryRDB implements WriteUserProfileRepositoryInterface { use SqlMultipleBindTrait; use LoggerTrait; /** * @param DatabaseConnection $db */ public function __construct(DatabaseConnection $db) { $this->db = $db; } /** * @param ContactInterface $contact * * @throws RepositoryException * @return int */ public function addDefaultProfileForUser(ContactInterface $contact): int { try { $query = <<<'SQL' INSERT INTO `:db`.user_profile (contact_id) VALUES (:contactId) SQL; $alreadyInTransaction = $this->db->inTransaction(); if (! $alreadyInTransaction) { $this->db->beginTransaction(); } $statement = $this->db->prepare($this->translateDbName($query)); $statement->bindValue(':contactId', $contact->getId(), PDO::PARAM_INT); $statement->execute(); $profileId = (int) $this->db->lastInsertId(); if (! $alreadyInTransaction) { $this->db->commit(); } return $profileId; } catch (PDOException $exception) { if (! $alreadyInTransaction) { try { $this->db->rollBack(); } catch (PDOException $rollbackException) { $errorMessage = "Error while rolling back transaction: {$rollbackException->getMessage()}"; $this->error( $errorMessage, [ 'contact_id' => $contact->getId(), 'query' => $query, 'exception' => [ 'message' => $rollbackException->getMessage(), 'pdo_code' => $rollbackException->getCode(), 'pdo_info' => $rollbackException->errorInfo, 'trace' => $rollbackException->getTraceAsString(), ], ] ); throw new RepositoryException($errorMessage, previous: $exception); } } $errorMessage = "Error while creating default profile for user: {$exception->getMessage()}"; $this->error( $errorMessage, [ 'contact_id' => $contact->getId(), 'query' => $query, 'exception' => [ 'message' => $exception->getMessage(), 'pdo_code' => $exception->getCode(), 'pdo_info' => $exception->errorInfo, 'trace' => $exception->getTraceAsString(), ], ] ); throw new RepositoryException($errorMessage, previous: $exception); } } /** * @param int $profileId * @param int $dashboardId * * @throws RepositoryException * @return void */ public function addDashboardAsFavorites(int $profileId, int $dashboardId): void { try { $query = <<<'SQL' INSERT INTO `:db`.user_profile_favorite_dashboards (profile_id, dashboard_id) VALUES (:profileId, :dashboardId) SQL; $alreadyInTransaction = $this->db->inTransaction(); if (! $alreadyInTransaction) { $this->db->beginTransaction(); } $statement = $this->db->prepare($this->translateDbName($query)); $statement->bindValue(':profileId', $profileId, PDO::PARAM_INT); $statement->bindValue(':dashboardId', $dashboardId, PDO::PARAM_INT); $statement->execute(); if (! $alreadyInTransaction) { $this->db->commit(); } } catch (PDOException $exception) { if (! $alreadyInTransaction) { try { $this->db->rollBack(); } catch (PDOException $rollbackException) { $errorMessage = "Error while rolling back transaction: {$rollbackException->getMessage()}"; $this->error( $errorMessage, [ 'profile_id' => $profileId, 'dashboard_id' => $dashboardId, 'query' => $query, 'exception' => [ 'message' => $rollbackException->getMessage(), 'pdo_code' => $rollbackException->getCode(), 'pdo_info' => $rollbackException->errorInfo, 'trace' => $rollbackException->getTraceAsString(), ], ] ); throw new RepositoryException($errorMessage, previous: $exception); } } $errorMessage = "Error while creating default profile for user: {$exception->getMessage()}"; $this->error( $errorMessage, [ 'profile_id' => $profileId, 'dashboard_id' => $dashboardId, 'query' => $query, 'exception' => [ 'message' => $exception->getMessage(), 'pdo_code' => $exception->getCode(), 'pdo_info' => $exception->errorInfo, 'trace' => $exception->getTraceAsString(), ], ] ); throw new RepositoryException($errorMessage, previous: $exception); } } /** * @param int $profileId * @param int $dashboardId * * @throws RepositoryException * @return void */ public function removeDashboardFromFavorites(int $profileId, int $dashboardId): void { try { $query = <<<'SQL' DELETE FROM `:db`.user_profile_favorite_dashboards WHERE profile_id = :profileId AND dashboard_id = :dashboardId SQL; $statement = $this->db->prepare($this->translateDbName($query)); $statement->bindValue(':profileId', $profileId, PDO::PARAM_INT); $statement->bindValue(':dashboardId', $dashboardId, PDO::PARAM_INT); $statement->execute(); } catch (PDOException $exception) { $errorMessage = "Error while removing dashboard from user favorite dashboards : {$exception->getMessage()}"; $this->error($errorMessage, [ 'profile_id' => $profileId, 'dashboard_id' => $dashboardId, 'query' => $query, 'exception' => [ 'message' => $exception->getMessage(), 'pdo_code' => $exception->getCode(), 'pdo_info' => $exception->errorInfo, 'trace' => $exception->getTraceAsString(), ], ]); throw new RepositoryException($errorMessage, previous: $exception); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/UserProfile/Infrastructure/Repository/DbReadUserProfileRepository.php
centreon/src/Core/UserProfile/Infrastructure/Repository/DbReadUserProfileRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\UserProfile\Infrastructure\Repository; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Log\LoggerTrait; use Centreon\Domain\Repository\RepositoryException; use Centreon\Infrastructure\DatabaseConnection; use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB; use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait; use Core\UserProfile\Application\Repository\ReadUserProfileRepositoryInterface; use Core\UserProfile\Domain\Model\UserProfile; use PDO; use PDOException; /** * @phpstan-type _UserProfileRecord array{ * id:int, * contact_id:int, * favorite_dashboards:string|null * } */ final class DbReadUserProfileRepository extends AbstractRepositoryRDB implements ReadUserProfileRepositoryInterface { use SqlMultipleBindTrait; use LoggerTrait; /** * @param DatabaseConnection $db */ public function __construct(DatabaseConnection $db) { $this->db = $db; } /** * @param ContactInterface $contact * * @throws RepositoryException * @return UserProfile|null */ public function findByContact(ContactInterface $contact): ?UserProfile { try { $query = <<<'SQL' SELECT `id`, `contact_id`, GROUP_CONCAT(DISTINCT user_profile_favorite_dashboards.dashboard_id) AS `favorite_dashboards` FROM `:db`.user_profile LEFT JOIN `:db`.user_profile_favorite_dashboards ON user_profile_favorite_dashboards.profile_id = user_profile.id WHERE contact_id = :contactId GROUP BY id, contact_id SQL; $statement = $this->db->prepare($this->translateDbName($query)); $statement->bindValue(':contactId', $contact->getId(), PDO::PARAM_INT); $statement->execute(); if (false !== ($record = $statement->fetch(PDO::FETCH_ASSOC))) { /** @var _UserProfileRecord $record */ return $this->createUserProfileFromRecord($record); } return null; } catch (PDOException $exception) { $errorMessage = "Error while fetching user profile with contact_id {$contact->getId()} : {$exception->getMessage()}"; $this->error($errorMessage, [ 'contact_id' => $contact->getId(), 'query' => $query, 'exception' => [ 'message' => $exception->getMessage(), 'pdo_code' => $exception->getCode(), 'pdo_info' => $exception->errorInfo, 'trace' => $exception->getTraceAsString(), ], ]); throw new RepositoryException($errorMessage, previous: $exception); } } /** * @param _UserProfileRecord $record * @return UserProfile */ private function createUserProfileFromRecord(array $record): UserProfile { $profile = new UserProfile( id: (int) $record['id'], userId: (int) $record['contact_id'], ); if ($record['favorite_dashboards'] !== null) { $favoriteDashboardIds = array_map( static fn (string $dashboardId) => (int) $dashboardId, explode(',', $record['favorite_dashboards']) ); $profile->setFavoriteDashboards($favoriteDashboardIds); } return $profile; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Application/UseCase/FindImageFolders/FindImageFolders.php
centreon/src/Core/Media/Application/UseCase/FindImageFolders/FindImageFolders.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Media\Application\UseCase\FindImageFolders; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Core\Common\Domain\Exception\RepositoryException; use Core\Media\Application\Repository\ReadImageFolderRepositoryInterface; use Core\Media\Domain\Model\ImageFolder\ImageFolder; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; final readonly class FindImageFolders { public function __construct( private ContactInterface $user, private RequestParametersInterface $requestParameters, private ReadAccessGroupRepositoryInterface $accessGroupReader, private ReadImageFolderRepositoryInterface $imageFolderReader, ) { } /** * @throws RepositoryException * @return FindImageFoldersResponse */ public function __invoke(): FindImageFoldersResponse { return new FindImageFoldersResponse( $this->user->isAdmin() ? $this->findAsAdmin() : $this->findAsUser() ); } /** * @throws RepositoryException * * @return array<ImageFolder> */ private function findAsAdmin(): array { return $this->imageFolderReader->findByRequestParameters($this->requestParameters); } /** * @throws RepositoryException * * @return array<ImageFolder> */ private function findAsUser(): array { $accessGroups = $this->accessGroupReader->findByContact($this->user); return $this->imageFolderReader->hasAccessToAllImageFolders($accessGroups) ? $this->imageFolderReader->findByRequestParameters($this->requestParameters) : $this->imageFolderReader->findByRequestParametersAndAccessGroups( $this->requestParameters, $accessGroups ); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Application/UseCase/FindImageFolders/FindImageFoldersResponse.php
centreon/src/Core/Media/Application/UseCase/FindImageFolders/FindImageFoldersResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Media\Application\UseCase\FindImageFolders; use Core\Media\Domain\Model\ImageFolder\ImageFolder; final readonly class FindImageFoldersResponse { /** * @param ImageFolder[] $imageFolders */ public function __construct( public array $imageFolders, ) { } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Application/UseCase/AddMedia/AddMediaRequest.php
centreon/src/Core/Media/Application/UseCase/AddMedia/AddMediaRequest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Media\Application\UseCase\AddMedia; final class AddMediaRequest { public string $directory = ''; /** * @param \Iterator<string, string> $medias */ public function __construct(public \Iterator $medias) { } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Application/UseCase/AddMedia/AddMedia.php
centreon/src/Core/Media/Application/UseCase/AddMedia/AddMedia.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Media\Application\UseCase\AddMedia; use Assert\AssertionFailedException; use Centreon\Domain\Log\LoggerTrait; use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\InvalidArgumentResponse; use Core\Media\Application\Exception\MediaException; use Core\Media\Application\Repository\ReadMediaRepositoryInterface; use Core\Media\Application\Repository\WriteMediaRepositoryInterface; use Core\Media\Domain\Model\NewMedia; use enshrined\svgSanitize\Sanitizer; use Symfony\Component\Mime\MimeTypes; /** * @phpstan-import-type _MediaRecorded from AddMediaResponse * @phpstan-import-type _Errors from AddMediaResponse */ final class AddMedia { use LoggerTrait; /** @var list<string> */ private array $fileExtensionsAllowed; /** * @param WriteMediaRepositoryInterface $writeMediaRepository * @param ReadMediaRepositoryInterface $readMediaRepository * @param DataStorageEngineInterface $dataStorageEngine * @param Sanitizer $svgSanitizer */ public function __construct( private readonly WriteMediaRepositoryInterface $writeMediaRepository, private readonly ReadMediaRepositoryInterface $readMediaRepository, private readonly DataStorageEngineInterface $dataStorageEngine, private readonly Sanitizer $svgSanitizer, ) { } /** * @param AddMediaRequest $request * @param AddMediaPresenterInterface $presenter */ public function __invoke(AddMediaRequest $request, AddMediaPresenterInterface $presenter): void { try { $this->addMimeTypeFilter('image/png', 'image/gif', 'image/jpeg', 'image/svg+xml'); [$mediasRecorded, $errors] = $this->addMedias($this->createMedias($request)); $presenter->presentResponse($this->createResponse($mediasRecorded, $errors)); } catch (AssertionFailedException $ex) { $presenter->presentResponse(new InvalidArgumentResponse($ex)); $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); } catch (\Throwable $ex) { $presenter->presentResponse( new ErrorResponse(MediaException::errorWhileAddingMedia()) ); $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); } } /** * @param string $mimeType */ private function addFileExtensions(string $mimeType): void { foreach (MimeTypes::getDefault()->getExtensions($mimeType) as $oneMimeType) { $this->fileExtensionsAllowed[] = $oneMimeType; } } private function addMimeTypeFilter(string ...$mimeTypes): void { foreach ($mimeTypes as $mimeType) { $this->addFileExtensions($mimeType); } } /** * @param \Iterator<int, NewMedia> $medias * * @throws \Throwable * * @return array{0: list<_MediaRecorded>, 1: list<_Errors>} */ private function addMedias(\Iterator $medias): array { $mediaRecorded = []; $errors = []; try { $this->dataStorageEngine->startTransaction(); foreach ($medias as $media) { $fileInfo = pathinfo($media->getFilename()); if (! in_array($fileInfo['extension'] ?? '', $this->fileExtensionsAllowed, true)) { $errors[] = $this->createMediaError($media, MediaException::fileExtensionNotAuthorized()->getMessage()); continue; } /** @var NewMedia $media */ if (! $this->readMediaRepository->existsByPath( $media->getDirectory() . DIRECTORY_SEPARATOR . $media->getFilename() ) ) { $fileContent = $media->getData(); if (array_key_exists('extension', $fileInfo) && $fileInfo['extension'] === 'svg') { $this->svgSanitizer->minify(true); $fileContent = $this->svgSanitizer->sanitize($fileContent); } $media->setData($fileContent); $hash = $media->hash(); $this->info('Add media', [ 'filename' => $media->getFilename(), 'directory' => $media->getDirectory(), 'md5' => $hash, ]); $mediaRecorded[] = [ 'id' => $this->writeMediaRepository->add( new NewMedia($media->getFilename(), $media->getDirectory(), $fileContent) ), 'filename' => $media->getFilename(), 'directory' => $media->getDirectory(), 'md5' => $hash, ]; } else { $errors[] = $this->createMediaError($media, MediaException::mediaAlreadyExists()->getMessage()); } } $this->dataStorageEngine->commitTransaction(); } catch (\Throwable $ex) { $this->dataStorageEngine->rollbackTransaction(); throw $ex; } return [$mediaRecorded, $errors]; } /** * @param NewMedia $newMedia * @param string $reason * * @return _Errors */ private function createMediaError(NewMedia $newMedia, string $reason): array { $this->info('Media already exists', [ 'filename' => $newMedia->getFilename(), 'directory' => $newMedia->getDirectory(), ]); return [ 'filename' => $newMedia->getFilename(), 'directory' => $newMedia->getDirectory(), 'reason' => $reason, ]; } /** * @param AddMediaRequest $request * * @return \Iterator<int, NewMedia> */ private function createMedias(AddMediaRequest $request): \Iterator { return new class ($request->medias, $request->directory) implements \Iterator { private int $position = 0; /** * @param \Iterator<string, string> $medias * @param string $directory */ public function __construct(readonly private \Iterator $medias, readonly private string $directory) { } public function current(): NewMedia { $data = $this->medias->current(); // 'current' method must be called before the 'key' method return new NewMedia( $this->medias->key(), $this->directory, $data ); } public function next(): void { $this->position++; $this->medias->next(); } public function key(): int { return $this->position; } public function valid(): bool { return $this->medias->valid(); } public function rewind(): void { $this->position = 0; $this->medias->rewind(); } }; } /** * @param list<_MediaRecorded> $mediasRecorded * @param list<_Errors> $errors * * @return AddMediaResponse */ private function createResponse(array $mediasRecorded, array $errors): AddMediaResponse { $response = new AddMediaResponse(); $response->mediasRecorded = $mediasRecorded; $response->errors = $errors; return $response; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Application/UseCase/AddMedia/AddMediaResponse.php
centreon/src/Core/Media/Application/UseCase/AddMedia/AddMediaResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Media\Application\UseCase\AddMedia; /** * @phpstan-type _MediaRecorded array{ * id: int, * filename: string, * directory: string, * md5: string, * } * @phpstan-type _Errors array{ * filename: string, * directory: string, * reason: string, * } */ final class AddMediaResponse { /** @var list<_MediaRecorded> */ public array $mediasRecorded; /** @var list<_Errors> */ public array $errors; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Application/UseCase/AddMedia/AddMediaPresenterInterface.php
centreon/src/Core/Media/Application/UseCase/AddMedia/AddMediaPresenterInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Media\Application\UseCase\AddMedia; use Core\Application\Common\UseCase\ResponseStatusInterface; interface AddMediaPresenterInterface { public function presentResponse(AddMediaResponse|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/Media/Application/UseCase/FindMedias/MediaDto.php
centreon/src/Core/Media/Application/UseCase/FindMedias/MediaDto.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Media\Application\UseCase\FindMedias; class MediaDto { public int $id = 0; public string $filename = ''; public string $directory = ''; public ?string $md5 = 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/Media/Application/UseCase/FindMedias/FindMedias.php
centreon/src/Core/Media/Application/UseCase/FindMedias/FindMedias.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Media\Application\UseCase\FindMedias; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Core\Application\Common\UseCase\ErrorResponse; use Core\Common\Domain\Exception\RepositoryException; use Core\Media\Application\Exception\MediaException; use Core\Media\Application\Repository\ReadImageFolderRepositoryInterface; use Core\Media\Application\Repository\ReadMediaRepositoryInterface; use Core\Media\Domain\Model\Media; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; final readonly class FindMedias { public function __construct( private RequestParametersInterface $requestParameters, private ReadMediaRepositoryInterface $mediaReader, private ReadAccessGroupRepositoryInterface $accessGroupReader, private ReadImageFolderRepositoryInterface $mediaFolderReader, private ContactInterface $user, ) { } /** * @param FindMediasPresenterInterface $presenter */ public function __invoke(FindMediasPresenterInterface $presenter): void { try { $medias = $this->user->isAdmin() ? $this->findAsAdmin() : $this->findAsUser(); $presenter->presentResponse($this->createResponse($medias)); } catch (\Exception $ex) { $presenter->presentResponse( new ErrorResponse( message: MediaException::errorWhileSearchingForMedias(), context: [ 'user_id' => $this->user->getId(), 'request_parameters' => $this->requestParameters->toArray(), ], exception: $ex ) ); } } /** * @throws RepositoryException * * @return \Traversable<int, Media> */ private function findAsAdmin(): \Traversable { return $this->mediaReader->findByRequestParameters($this->requestParameters); } /** * @throws RepositoryException * * @return \Traversable<int, Media> */ private function findAsUser(): \Traversable { $accessGroups = $this->accessGroupReader->findByContact($this->user); if ($this->mediaFolderReader->hasAccessToAllImageFolders($accessGroups)) { return $this->mediaReader->findByRequestParameters($this->requestParameters); } return $this->mediaReader->findByRequestParametersAndAccessGroups($this->requestParameters, $accessGroups); } /** * @param \Traversable<int, Media> $medias * * @return FindMediasResponse */ private function createResponse(\Traversable $medias): FindMediasResponse { $response = new FindMediasResponse(); foreach ($medias as $media) { $dto = new MediaDto(); $dto->id = $media->getId(); $dto->filename = $media->getFilename(); $dto->directory = $media->getDirectory(); $dto->md5 = $media->hash(); $response->medias[] = $dto; } return $response; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Application/UseCase/FindMedias/FindMediasPresenterInterface.php
centreon/src/Core/Media/Application/UseCase/FindMedias/FindMediasPresenterInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Media\Application\UseCase\FindMedias; use Core\Application\Common\UseCase\PresenterInterface; use Core\Application\Common\UseCase\ResponseStatusInterface; interface FindMediasPresenterInterface extends PresenterInterface { public function presentResponse(FindMediasResponse|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/Media/Application/UseCase/FindMedias/FindMediasResponse.php
centreon/src/Core/Media/Application/UseCase/FindMedias/FindMediasResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Media\Application\UseCase\FindMedias; final class FindMediasResponse { /** @var list<MediaDto> */ public array $medias = []; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Application/UseCase/UpdateMedia/UpdateMediaRequest.php
centreon/src/Core/Media/Application/UseCase/UpdateMedia/UpdateMediaRequest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Media\Application\UseCase\UpdateMedia; final class UpdateMediaRequest { /** * @param string $fileName * @param string $data */ public function __construct(public string $fileName, public string $data) { } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Application/UseCase/UpdateMedia/UpdateMediaPresenterInterface.php
centreon/src/Core/Media/Application/UseCase/UpdateMedia/UpdateMediaPresenterInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Media\Application\UseCase\UpdateMedia; use Core\Application\Common\UseCase\ResponseStatusInterface; interface UpdateMediaPresenterInterface { public function presentResponse(UpdateMediaResponse|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/Media/Application/UseCase/UpdateMedia/UpdateMedia.php
centreon/src/Core/Media/Application/UseCase/UpdateMedia/UpdateMedia.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Media\Application\UseCase\UpdateMedia; use Assert\AssertionFailedException; use Centreon\Domain\Log\LoggerTrait; use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\InvalidArgumentResponse; use Core\Application\Common\UseCase\NotFoundResponse; use Core\Media\Application\Exception\MediaException; use Core\Media\Application\Repository\ReadMediaRepositoryInterface; use Core\Media\Application\Repository\WriteMediaRepositoryInterface; use Core\Media\Domain\Model\Media; use Symfony\Component\Mime\MimeTypes; /** * @phpstan-import-type _UpdatedMedia from UpdateMediaResponse */ final class UpdateMedia { use LoggerTrait; /** @var list<string> */ private array $fileExtensionsAllowed; public function __construct( private readonly WriteMediaRepositoryInterface $writeMediaRepository, private readonly ReadMediaRepositoryInterface $readMediaRepository, private readonly DataStorageEngineInterface $dataStorageEngine, ) { } /** * @param UpdateMediaRequest $request * @param UpdateMediaPresenterInterface $presenter * @param int $mediaId */ public function __invoke(int $mediaId, UpdateMediaRequest $request, UpdateMediaPresenterInterface $presenter): void { try { $media = $this->readMediaRepository->findById($mediaId); if ($media === null) { $this->error('Media not found', ['media_id' => $mediaId]); $presenter->presentResponse(new NotFoundResponse('Media')); return; } $this->addMimeTypeFilter('image/png', 'image/gif', 'image/jpeg', 'image/svg+xml'); $this->updateExistingMediaContent($media, $request); $updateResult = $this->updateMedia($media); $presenter->presentResponse($this->createResponse($updateResult)); } catch (AssertionFailedException $ex) { $presenter->presentResponse(new InvalidArgumentResponse($ex)); $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); } catch (\Throwable $ex) { $presenter->presentResponse( new ErrorResponse(MediaException::errorWhileUpdatingMedia()) ); $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); } } /** * @param string $fileName * * @return bool */ private function isExtensionAllowed(string $fileName): bool { $fileInformation = pathinfo($fileName); return in_array($fileInformation['extension'] ?? '', $this->fileExtensionsAllowed, true); } /** * @param Media $existingMedia * @param UpdateMediaRequest $request * * @throws MediaException * * @return Media */ private function updateExistingMediaContent(Media $existingMedia, UpdateMediaRequest $request): Media { if (! $this->isExtensionAllowed($request->fileName)) { throw MediaException::fileExtensionNotAuthorized(); } $existingMedia->setData($request->data); return $existingMedia; } /** * @param string $mimeType */ private function addFileExtensions(string $mimeType): void { foreach (MimeTypes::getDefault()->getExtensions($mimeType) as $oneMimeType) { $this->fileExtensionsAllowed[] = $oneMimeType; } } private function addMimeTypeFilter(string ...$mimeTypes): void { foreach ($mimeTypes as $mimeType) { $this->addFileExtensions($mimeType); } } /** * @param Media $media * * @throws \Throwable * * @return _UpdatedMedia */ private function updateMedia(Media $media): array { try { $this->dataStorageEngine->startTransaction(); $hash = $media->hash(); $this->writeMediaRepository->update($media); $this->info( 'Updating media', [ 'id' => $media->getId(), 'filename' => $media->getFilename(), 'directory' => $media->getDirectory(), 'md5' => $hash, ] ); $this->dataStorageEngine->commitTransaction(); } catch (\Throwable $ex) { $this->dataStorageEngine->rollbackTransaction(); throw $ex; } return [ 'id' => $media->getId(), 'filename' => $media->getFilename(), 'directory' => $media->getDirectory(), 'md5' => $hash, ]; } /** * @param _UpdatedMedia $updatedMedia * * @return UpdateMediaResponse */ private function createResponse(array $updatedMedia): UpdateMediaResponse { $response = new UpdateMediaResponse(); $response->updatedMedia = $updatedMedia; return $response; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Application/UseCase/UpdateMedia/UpdateMediaResponse.php
centreon/src/Core/Media/Application/UseCase/UpdateMedia/UpdateMediaResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Media\Application\UseCase\UpdateMedia; /** * @phpstan-type _UpdatedMedia array{ * id: int, * filename: string, * directory: string, * md5: string|null, * } */ final class UpdateMediaResponse { /** @var _UpdatedMedia */ public array $updatedMedia; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Application/UseCase/MigrateAllMedias/MigrationErrorDto.php
centreon/src/Core/Media/Application/UseCase/MigrateAllMedias/MigrationErrorDto.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Media\Application\UseCase\MigrateAllMedias; class MigrationErrorDto { public string $filename = ''; public string $directory = ''; public string $reason = ''; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Application/UseCase/MigrateAllMedias/MigrateAllMedias.php
centreon/src/Core/Media/Application/UseCase/MigrateAllMedias/MigrateAllMedias.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Media\Application\UseCase\MigrateAllMedias; use Centreon\Domain\Log\LoggerTrait; use Core\Application\Common\UseCase\ErrorResponse; use Core\Media\Application\Exception\MediaException; use Core\Media\Application\Repository\ReadMediaRepositoryInterface; use Core\Media\Application\Repository\WriteMediaRepositoryInterface; use Core\Media\Domain\Model\Media; use Core\Media\Domain\Model\NewMedia; final class MigrateAllMedias { use LoggerTrait; private MigrationAllMediasResponse $response; public function __construct( readonly private ReadMediaRepositoryInterface $readMediaRepository, readonly private WriteMediaRepositoryInterface $writeMediaRepository, ) { $this->response = new MigrationAllMediasResponse(); } public function __invoke(MigrateAllMediasRequest $request, MigrateAllMediasPresenterInterface $presenter): void { try { if ($request->contact !== null && ! $request->contact->isAdmin()) { throw MediaException::operationRequiresAdminUser(); } $medias = $this->readMediaRepository->findAll(); $this->migrateMedias($medias, $this->response); $presenter->presentResponse($this->response); } catch (MediaException $ex) { $this->error('Media migration requires an admin user', ['user_name' => $request->contact?->getName()]); $presenter->presentResponse(new ErrorResponse($ex->getMessage())); } catch (\Throwable $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); $presenter->presentResponse(new ErrorResponse($ex->getMessage())); } } /** * @param \Traversable<int, Media>&\Countable $medias * @param MigrationAllMediasResponse $response */ private function migrateMedias(\Traversable&\Countable $medias, MigrationAllMediasResponse $response): void { $response->results = new class ($medias, $this->writeMediaRepository) implements \IteratorAggregate, \Countable { /** * @param \Traversable<int, Media>&\Countable $medias * @param WriteMediaRepositoryInterface $writeMediaRepository */ public function __construct( readonly private \Traversable&\Countable $medias, readonly private WriteMediaRepositoryInterface $writeMediaRepository, ) { } public function getIterator(): \Traversable { foreach ($this->medias as $media) { try { if ($media->getData() === null) { throw new \Exception(sprintf('The file %s does not exist', $media->getRelativePath())); } $destinationNewMediaId = $this->writeMediaRepository->add(NewMedia::createFromMedia($media)); $status = new MediaRecordedDto(); $status->id = $destinationNewMediaId; $status->filename = $media->getFilename(); $status->directory = $media->getDirectory(); $status->md5 = md5($media->getData()); yield $status; } catch (\Throwable $ex) { $status = new MigrationErrorDto(); $status->filename = $media->getFilename(); $status->directory = $media->getDirectory(); $status->reason = $ex->getMessage(); yield $status; } } } public function count(): int { return count($this->medias); } }; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Application/UseCase/MigrateAllMedias/MediaRecordedDto.php
centreon/src/Core/Media/Application/UseCase/MigrateAllMedias/MediaRecordedDto.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Media\Application\UseCase\MigrateAllMedias; class MediaRecordedDto { public int $id = 0; public string $filename = ''; public string $directory = ''; public string $md5 = ''; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Application/UseCase/MigrateAllMedias/MigrateAllMediasPresenterInterface.php
centreon/src/Core/Media/Application/UseCase/MigrateAllMedias/MigrateAllMediasPresenterInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Media\Application\UseCase\MigrateAllMedias; use Core\Application\Common\UseCase\ResponseStatusInterface; interface MigrateAllMediasPresenterInterface { public function presentResponse(MigrationAllMediasResponse|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/Media/Application/UseCase/MigrateAllMedias/MigrateAllMediasRequest.php
centreon/src/Core/Media/Application/UseCase/MigrateAllMedias/MigrateAllMediasRequest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Media\Application\UseCase\MigrateAllMedias; use Centreon\Domain\Contact\Interfaces\ContactInterface; final class MigrateAllMediasRequest { public int $maxFile = 0; public int $maxFilesize = 0; public int $postMax = 0; public ?ContactInterface $contact = 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/Media/Application/UseCase/MigrateAllMedias/MigrationAllMediasResponse.php
centreon/src/Core/Media/Application/UseCase/MigrateAllMedias/MigrationAllMediasResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Media\Application\UseCase\MigrateAllMedias; final class MigrationAllMediasResponse { /** @var \Traversable<MediaRecordedDto|MigrationErrorDto> */ public \Traversable $results; public function __construct() { $this->results = new \ArrayIterator([]); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Application/Exception/MediaException.php
centreon/src/Core/Media/Application/Exception/MediaException.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Media\Application\Exception; class MediaException extends \Exception { /** * @return self */ public static function addNotAllowed(): self { return new self(_('You are not allowed to add media')); } /** * @return self */ public static function updateNotAllowed(): self { return new self(_('You are not allowed to update media')); } /** * @return self */ public static function errorWhileAddingMedia(): self { return new self(_('Error while adding a media')); } /** * @return self */ public static function errorWhileUpdatingMedia(): self { return new self(_('Error while updating a media')); } /** * @return self */ public static function errorWhileSearchingForMedias(): self { return new self(_('Error while searching for media')); } /** * @return self */ public static function fileExtensionNotAuthorized(): self { return new self(_('File extension not authorized')); } /** * @return self */ public static function listingNotAllowed(): self { return new self(_('You are not allowed to list media')); } /** * @return self */ public static function mediaAlreadyExists(): self { return new self(_('Media already exists')); } public static function operationRequiresAdminUser(): self { return new self(_('This operation requires an admin user')); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false