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/ServiceCategory/Application/UseCase/FindServiceCategories/FindServiceCategoriesResponse.php
centreon/src/Core/ServiceCategory/Application/UseCase/FindServiceCategories/FindServiceCategoriesResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\ServiceCategory\Application\UseCase\FindServiceCategories; final class FindServiceCategoriesResponse { /** @var array<array{id:int,name:string,alias:string,is_activated:bool}> */ public array $serviceCategories = []; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceCategory/Application/UseCase/FindServiceCategories/FindServiceCategories.php
centreon/src/Core/ServiceCategory/Application/UseCase/FindServiceCategories/FindServiceCategories.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\ServiceCategory\Application\UseCase\FindServiceCategories; use Centreon\Domain\Contact\Contact; 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\ForbiddenResponse; use Core\Application\Common\UseCase\PresenterInterface; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\Security\AccessGroup\Domain\Model\AccessGroup; use Core\ServiceCategory\Application\Exception\ServiceCategoryException; use Core\ServiceCategory\Application\Repository\ReadServiceCategoryRepositoryInterface; use Core\ServiceCategory\Domain\Model\ServiceCategory; final class FindServiceCategories { use LoggerTrait; public const AUTHORIZED_ACL_GROUPS = ['customer_admin_acl']; /** * @param ReadServiceCategoryRepositoryInterface $readServiceCategoryRepository * @param ReadAccessGroupRepositoryInterface $accessGroupRepository * @param RequestParametersInterface $requestParameters * @param ContactInterface $user * @param bool $isCloudPlatform */ public function __construct( private readonly ReadServiceCategoryRepositoryInterface $readServiceCategoryRepository, private readonly ReadAccessGroupRepositoryInterface $accessGroupRepository, private readonly RequestParametersInterface $requestParameters, private readonly ContactInterface $user, private readonly bool $isCloudPlatform, ) { } /** * @param PresenterInterface $presenter */ public function __invoke(PresenterInterface $presenter): void { try { if ($this->isUserAdmin()) { $serviceCategories = $this->readServiceCategoryRepository->findByRequestParameter($this->requestParameters); $presenter->present($this->createResponse($serviceCategories)); } elseif ( $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_SERVICES_CATEGORIES_READ) || $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_SERVICES_CATEGORIES_READ_WRITE) ) { $this->debug('User is not admin, use ACLs to retrieve service categories', ['user' => $this->user->getName()]); $accessGroups = $this->accessGroupRepository->findByContact($this->user); $serviceCategories = $this->readServiceCategoryRepository->findByRequestParameterAndAccessGroups( $accessGroups, $this->requestParameters ); $presenter->present($this->createResponse($serviceCategories)); } else { $this->error('User doesn\'t have sufficient rights to see service categories', [ 'user_id' => $this->user->getId(), ]); $presenter->setResponseStatus( new ForbiddenResponse(ServiceCategoryException::accessNotAllowed()) ); } } catch (\Throwable $ex) { $this->error((string) $ex); $presenter->setResponseStatus( new ErrorResponse(ServiceCategoryException::findServiceCategories($ex)) ); } } /** * Indicates if the current user is admin or not (cloud + onPremise context). * * @return bool */ private function isUserAdmin(): bool { if ($this->user->isAdmin()) { return true; } $userAccessGroupNames = array_map( static fn (AccessGroup $accessGroup): string => $accessGroup->getName(), $this->accessGroupRepository->findByContact($this->user) ); return ! empty(array_intersect($userAccessGroupNames, self::AUTHORIZED_ACL_GROUPS)) && $this->isCloudPlatform; } /** * @param ServiceCategory[] $serviceCategories * * @return FindServiceCategoriesResponse */ private function createResponse( array $serviceCategories, ): FindServiceCategoriesResponse { $response = new FindServiceCategoriesResponse(); foreach ($serviceCategories as $serviceCategory) { $response->serviceCategories[] = [ 'id' => $serviceCategory->getId(), 'name' => $serviceCategory->getName(), 'alias' => $serviceCategory->getAlias(), 'is_activated' => $serviceCategory->isActivated(), ]; } 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/ServiceCategory/Application/UseCase/FindRealTimeServiceCategories/FindRealTimeServiceCategoriesPresenterInterface.php
centreon/src/Core/ServiceCategory/Application/UseCase/FindRealTimeServiceCategories/FindRealTimeServiceCategoriesPresenterInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\ServiceCategory\Application\UseCase\FindRealTimeServiceCategories; use Core\Application\Common\UseCase\PresenterInterface; use Core\Application\Common\UseCase\ResponseStatusInterface; interface FindRealTimeServiceCategoriesPresenterInterface extends PresenterInterface { /** * @param FindRealTimeServiceCategoriesResponse|ResponseStatusInterface $response */ public function presentResponse(FindRealTimeServiceCategoriesResponse|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/ServiceCategory/Application/UseCase/FindRealTimeServiceCategories/FindRealTimeServiceCategories.php
centreon/src/Core/ServiceCategory/Application/UseCase/FindRealTimeServiceCategories/FindRealTimeServiceCategories.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\ServiceCategory\Application\UseCase\FindRealTimeServiceCategories; 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\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\Security\AccessGroup\Domain\Model\AccessGroup; use Core\ServiceCategory\Application\Exception\ServiceCategoryException; use Core\ServiceCategory\Application\Repository\ReadRealTimeServiceCategoryRepositoryInterface; use Core\ServiceCategory\Application\Repository\ReadServiceCategoryRepositoryInterface; use Core\Tag\RealTime\Domain\Model\Tag; final class FindRealTimeServiceCategories { use LoggerTrait; public function __construct( private readonly ContactInterface $user, private readonly ReadRealTimeServiceCategoryRepositoryInterface $repository, private readonly ReadServiceCategoryRepositoryInterface $configurationRepository, private readonly RequestParametersInterface $requestParameters, private readonly ReadAccessGroupRepositoryInterface $accessGroupRepository, ) { } /** * @param FindRealTimeServiceCategoriesPresenterInterface $presenter */ public function __invoke(FindRealTimeServiceCategoriesPresenterInterface $presenter): void { $this->info('Find service categories', ['user_id' => $this->user->getId()]); try { $serviceCategories = $this->user->isAdmin() ? $this->findServiceCategoriesAsAdmin() : $this->findServiceCategoriesAsUser(); $presenter->presentResponse($this->createResponse($serviceCategories)); } catch (\Throwable $exception) { $presenter->presentResponse( new ErrorResponse(ServiceCategoryException::errorWhileRetrievingRealTimeServiceCategories($exception)) ); $this->error($exception->getMessage(), ['trace' => $exception->getTraceAsString()]); } } /** * @param Tag[] $serviceCategories * * @return FindRealTimeServiceCategoriesResponse */ private function createResponse(array $serviceCategories): FindRealTimeServiceCategoriesResponse { return new FindRealTimeServiceCategoriesResponse($serviceCategories); } /** * @return Tag[] */ private function findServiceCategoriesAsUser(): array { $categories = []; $this->debug( 'User is not admin, use ACLs to retrieve service categories', ['user' => $this->user->getName()] ); $accessGroupIds = array_map( static fn (AccessGroup $accessGroup): int => $accessGroup->getId(), $this->accessGroupRepository->findByContact($this->user) ); if ($accessGroupIds === []) { return $categories; } // If the current user has ACL filter on Service Categories it means that not all categories are visible so // we need to apply the ACL if ($this->configurationRepository->hasRestrictedAccessToServiceCategories($accessGroupIds)) { return $this->repository->findAllByAccessGroupIds( $this->requestParameters, $accessGroupIds, ); } $this->debug( 'No ACL filter found on service categories for user. Retrieving all service categories', ['user' => $this->user->getName()] ); return $this->repository->findAll($this->requestParameters); } /** * @return Tag[] */ private function findServiceCategoriesAsAdmin(): array { return $this->repository->findAll($this->requestParameters); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceCategory/Application/UseCase/FindRealTimeServiceCategories/FindRealTimeServiceCategoriesResponse.php
centreon/src/Core/ServiceCategory/Application/UseCase/FindRealTimeServiceCategories/FindRealTimeServiceCategoriesResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\ServiceCategory\Application\UseCase\FindRealTimeServiceCategories; use Core\Tag\RealTime\Application\UseCase\FindTag\FindTagResponse; final class FindRealTimeServiceCategoriesResponse extends FindTagResponse { }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceCategory/Application/UseCase/DeleteServiceCategory/DeleteServiceCategory.php
centreon/src/Core/ServiceCategory/Application/UseCase/DeleteServiceCategory/DeleteServiceCategory.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\ServiceCategory\Application\UseCase\DeleteServiceCategory; 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\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\ServiceCategory\Application\Exception\ServiceCategoryException; use Core\ServiceCategory\Application\Repository\ReadServiceCategoryRepositoryInterface; use Core\ServiceCategory\Application\Repository\WriteServiceCategoryRepositoryInterface; final class DeleteServiceCategory { use LoggerTrait; public function __construct( private readonly WriteServiceCategoryRepositoryInterface $writeServiceCategoryRepository, private readonly ReadServiceCategoryRepositoryInterface $readServiceCategoryRepository, private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepositoryInterface, private readonly ContactInterface $user, ) { } /** * @param int $serviceCategoryId * @param PresenterInterface $presenter */ public function __invoke(int $serviceCategoryId, PresenterInterface $presenter): void { try { if ($this->user->isAdmin()) { if ($this->readServiceCategoryRepository->exists($serviceCategoryId)) { $this->writeServiceCategoryRepository->deleteById($serviceCategoryId); $presenter->setResponseStatus(new NoContentResponse()); } else { $this->error('Service category not found', [ 'servicecategory_id' => $serviceCategoryId, ]); $presenter->setResponseStatus(new NotFoundResponse('Service category')); } } elseif ($this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_SERVICES_CATEGORIES_READ_WRITE)) { $accessGroups = $this->readAccessGroupRepositoryInterface->findByContact($this->user); if ($this->readServiceCategoryRepository->existsByAccessGroups($serviceCategoryId, $accessGroups)) { $this->writeServiceCategoryRepository->deleteById($serviceCategoryId); $presenter->setResponseStatus(new NoContentResponse()); } else { $this->error('Service category not found', [ 'servicecategory_id' => $serviceCategoryId, 'accessgroups' => $accessGroups, ]); $presenter->setResponseStatus(new NotFoundResponse('Service category')); } } else { $this->error('User doesn\'t have sufficient rights to see service category', [ 'user_id' => $this->user->getId(), ]); $presenter->setResponseStatus( new ForbiddenResponse(ServiceCategoryException::deleteNotAllowed()) ); } } catch (\Throwable $ex) { $presenter->setResponseStatus( new ErrorResponse(ServiceCategoryException::deleteServiceCategory($ex)) ); $this->error((string) $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/ServiceCategory/Application/Exception/ServiceCategoryException.php
centreon/src/Core/ServiceCategory/Application/Exception/ServiceCategoryException.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\ServiceCategory\Application\Exception; class ServiceCategoryException extends \Exception { /** * @return self */ public static function accessNotAllowed(): self { return new self(_('You are not allowed to access service categories')); } /** * @return self */ public static function deleteNotAllowed(): self { return new self(_('You are not allowed to delete service categories')); } /** * @return self */ public static function addNotAllowed(): self { return new self(_('You are not allowed to create service categories')); } /** * @param \Throwable $ex * * @return self */ public static function findServiceCategories(\Throwable $ex): self { return new self(_('Error while searching for service categories'), 0, $ex); } /** * @param \Throwable $ex * * @return self */ public static function deleteServiceCategory(\Throwable $ex): self { return new self(_('Error while deleting service category'), 0, $ex); } /** * @param \Throwable $ex * * @return self */ public static function addServiceCategory(\Throwable $ex): self { return new self(_('Error while creating service category'), 0, $ex); } /** * @return self */ public static function serviceNameAlreadyExists(): self { return new self(_('Service category name already exists')); } /** * @return self */ public static function errorWhileRetrievingJustCreated(): self { return new self(_('Error while retrieving recently created service category')); } /** * @param \Throwable $exception * * @return ServiceCategoryException */ public static function errorWhileRetrievingRealTimeServiceCategories(\Throwable $exception): self { return new self(_('Error while searching service categories in real time context'), 0, $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/ServiceCategory/Application/Repository/WriteServiceCategoryRepositoryInterface.php
centreon/src/Core/ServiceCategory/Application/Repository/WriteServiceCategoryRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\ServiceCategory\Application\Repository; use Core\ServiceCategory\Domain\Model\NewServiceCategory; interface WriteServiceCategoryRepositoryInterface { /** * Delete service category by id. * * @param int $serviceCategoryId * * @throws \Throwable */ public function deleteById(int $serviceCategoryId): void; /** * Add a service category and return its id. * * @param NewServiceCategory $serviceCategory * * @throws \Throwable * * @return int */ public function add(NewServiceCategory $serviceCategory): int; /** * Link a service to a list of service categories. * * @param int $serviceId * @param list<int> $serviceCategoriesIds * * @throws \Throwable */ public function linkToService(int $serviceId, array $serviceCategoriesIds): void; /** * Unlink a service from a list of service categories. * * @param int $serviceId * @param list<int> $serviceCategoriesIds * * @throws \Throwable */ public function unlinkFromService(int $serviceId, array $serviceCategoriesIds): 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/ServiceCategory/Application/Repository/ReadServiceCategoryRepositoryInterface.php
centreon/src/Core/ServiceCategory/Application/Repository/ReadServiceCategoryRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\ServiceCategory\Application\Repository; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Core\Common\Domain\TrimmedString; use Core\Security\AccessGroup\Domain\Model\AccessGroup; use Core\ServiceCategory\Domain\Model\ServiceCategory; use Core\ServiceCategory\Domain\Model\ServiceCategoryNamesById; interface ReadServiceCategoryRepositoryInterface { /** * Find all existing service categories ids. * * @param list<int> $serviceCategoriesIds * * @throws \Throwable * * @return list<int> */ public function findAllExistingIds(array $serviceCategoriesIds): array; /** * Find all existing service categories ids and according to access groups. * * @param list<int> $serviceCategoriesIds * @param AccessGroup[] $accessGroups * * @throws \Throwable * * @return list<int> */ public function findAllExistingIdsByAccessGroups(array $serviceCategoriesIds, array $accessGroups): array; /** * Find all service categories. * * @param RequestParametersInterface $requestParameters * * @throws \Throwable * * @return ServiceCategory[] */ public function findByRequestParameter(RequestParametersInterface $requestParameters): array; /** * Find all service categories by access groups. * * @param AccessGroup[] $accessGroups * @param RequestParametersInterface $requestParameters * * @throws \Throwable * * @return ServiceCategory[] */ public function findByRequestParameterAndAccessGroups( array $accessGroups, RequestParametersInterface $requestParameters, ): array; /** * Find all service categories linked to a service. * * @param int $serviceId * * @return ServiceCategory[] */ public function findByService(int $serviceId): array; /** * Find all service categories linked to a service and according to access groups. * * @param int $serviceId * @param AccessGroup[] $accessGroups * * @return ServiceCategory[] */ public function findByServiceAndAccessGroups(int $serviceId, array $accessGroups): array; /** * Check existence of a service category. * * @param int $serviceCategoryId * * @throws \Throwable * * @return bool */ public function exists(int $serviceCategoryId): bool; /** * Check existence of a service category by access groups. * * @param int $serviceCategoryId * @param AccessGroup[] $accessGroups * * @throws \Throwable * * @return bool */ public function existsByAccessGroups(int $serviceCategoryId, array $accessGroups): bool; /** * Check existance of a service category by name. * * @param TrimmedString $serviceCategoryName * * @throws \Throwable * * @return bool */ public function existsByName(TrimmedString $serviceCategoryName): bool; /** * Find one service category. * * @param int $serviceCategoryId * * @return ServiceCategory|null */ public function findById(int $serviceCategoryId): ?ServiceCategory; /** * Find service categoriy names by their IDs. * * @param int[] $serviceCategoryIds * * @return ServiceCategoryNamesById */ public function findNames(array $serviceCategoryIds): ServiceCategoryNamesById; /** * @param int[] $serviceCategoryIds * * @return int[] */ public function exist(array $serviceCategoryIds): array; /** * Determine if service categories are filtered for given access group ids * true: accessible service categories are filtered (only specified are accessible) * false: accessible service categories are not filtered (all are accessible). * * @param int[] $accessGroupIds * * @phpstan-param non-empty-array<int> $accessGroupIds * * @return bool */ public function hasRestrictedAccessToServiceCategories(array $accessGroupIds): 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/ServiceCategory/Application/Repository/ReadRealTimeServiceCategoryRepositoryInterface.php
centreon/src/Core/ServiceCategory/Application/Repository/ReadRealTimeServiceCategoryRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\ServiceCategory\Application\Repository; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Core\Tag\RealTime\Domain\Model\Tag; interface ReadRealTimeServiceCategoryRepositoryInterface { /** * @param null|RequestParametersInterface $requestParameters * * @return Tag[] */ public function findAll(?RequestParametersInterface $requestParameters): array; /** * @param null|RequestParametersInterface $requestParameters * @param int[] $accessGroupIds * * @return Tag[] */ public function findAllByAccessGroupIds(?RequestParametersInterface $requestParameters, array $accessGroupIds): 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/ServiceCategory/Domain/Model/NewServiceCategory.php
centreon/src/Core/ServiceCategory/Domain/Model/NewServiceCategory.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\ServiceCategory\Domain\Model; use Centreon\Domain\Common\Assertion\Assertion; class NewServiceCategory { public const MAX_NAME_LENGTH = 200; public const MAX_ALIAS_LENGTH = 200; public const MIN_NAME_LENGTH = 1; public const MIN_ALIAS_LENGTH = 1; protected bool $isActivated = true; /** * @param string $name * @param string $alias */ public function __construct( protected string $name, protected string $alias, ) { $this->name = trim($name); $this->alias = trim($alias); $classShortName = (new \ReflectionClass($this))->getShortName(); Assertion::maxLength($name, self::MAX_NAME_LENGTH, $classShortName . '::name'); Assertion::minLength($name, self::MIN_NAME_LENGTH, $classShortName . '::name'); Assertion::maxLength($alias, self::MAX_ALIAS_LENGTH, $classShortName . '::alias'); Assertion::minLength($alias, self::MIN_ALIAS_LENGTH, $classShortName . '::alias'); } /** * @return string */ public function getName(): string { return $this->name; } /** * @return string */ public function getAlias(): string { return $this->alias; } /** * @return bool */ public function isActivated(): bool { return $this->isActivated; } /** * @param bool $isActivated */ public function setActivated(bool $isActivated): void { $this->isActivated = $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/ServiceCategory/Domain/Model/ServiceCategoryNamesById.php
centreon/src/Core/ServiceCategory/Domain/Model/ServiceCategoryNamesById.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\ServiceCategory\Domain\Model; use Core\Common\Domain\TrimmedString; class ServiceCategoryNamesById { /** @var array<int,TrimmedString> */ private array $names = []; public function __construct() { } /** * @param int $categoryId * @param TrimmedString $categoryName */ public function addName(int $categoryId, TrimmedString $categoryName): void { $this->names[$categoryId] = $categoryName; } /** * @param int $categoryId * * @return null|string */ public function getName(int $categoryId): ?string { return isset($this->names[$categoryId]) ? $this->names[$categoryId]->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/ServiceCategory/Domain/Model/ServiceCategory.php
centreon/src/Core/ServiceCategory/Domain/Model/ServiceCategory.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\ServiceCategory\Domain\Model; class ServiceCategory extends NewServiceCategory { /** * @param int $id * @param string $name * @param string $alias */ public function __construct( private int $id, string $name, string $alias, ) { parent::__construct($name, $alias); } /** * @return int */ public function getId(): int { return $this->id; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceCategory/Infrastructure/Repository/ServiceCategoryRepositoryTrait.php
centreon/src/Core/ServiceCategory/Infrastructure/Repository/ServiceCategoryRepositoryTrait.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\ServiceCategory\Infrastructure\Repository; use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait; trait ServiceCategoryRepositoryTrait { use SqlMultipleBindTrait; /** * @param int[] $accessGroupIds * * @return bool */ public function hasRestrictedAccessToServiceCategories(array $accessGroupIds): bool { if ($accessGroupIds === []) { return false; } [$bindValues, $bindQuery] = $this->createMultipleBindQuery($accessGroupIds, ':access_group_id_'); $request = <<<SQL SELECT 1 FROM `:db`.acl_resources_sc_relations arscr INNER JOIN `:db`.acl_resources res ON res.acl_res_id = arscr.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 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(); return (bool) $statement->fetchColumn(); } /** * @param int[] $accessGroupIds * * @return string */ private function generateServiceCategoryAclSubRequest(array $accessGroupIds = []): string { $request = ''; if ( $accessGroupIds !== [] && $this->hasRestrictedAccessToServiceCategories($accessGroupIds) ) { [, $bindQuery] = $this->createMultipleBindQuery($accessGroupIds, ':access_group_id_'); $request = <<<SQL SELECT arscr.sc_id FROM `:db`.acl_resources_sc_relations arscr INNER JOIN `:db`.acl_resources res ON res.acl_res_id = arscr.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/ServiceCategory/Infrastructure/Repository/DbReadServiceCategoryRepository.php
centreon/src/Core/ServiceCategory/Infrastructure/Repository/DbReadServiceCategoryRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\ServiceCategory\Infrastructure\Repository; use Centreon\Domain\Log\LoggerTrait; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Centreon\Infrastructure\DatabaseConnection; use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator; use Core\Common\Domain\TrimmedString; use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB; use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait; use Core\Common\Infrastructure\RequestParameters\Normalizer\BoolToEnumNormalizer; use Core\ServiceCategory\Application\Repository\ReadServiceCategoryRepositoryInterface; use Core\ServiceCategory\Domain\Model\ServiceCategory; use Core\ServiceCategory\Domain\Model\ServiceCategoryNamesById; use Core\ServiceGroup\Infrastructure\Repository\ServiceGroupRepositoryTrait; use Utility\SqlConcatenator; /** * @phpstan-type _ServiceCategory array{ * sc_id: int, * sc_name: string, * sc_description: string, * sc_activate: '0'|'1' * } */ class DbReadServiceCategoryRepository extends AbstractRepositoryRDB implements ReadServiceCategoryRepositoryInterface { use LoggerTrait; use ServiceGroupRepositoryTrait; use SqlMultipleBindTrait; public function __construct(DatabaseConnection $db) { $this->db = $db; } /** * @inheritDoc */ public function exist(array $serviceCategoryIds): array { $this->info('Check existence of service categories', ['service_category_ids' => $serviceCategoryIds]); if ($serviceCategoryIds === []) { return []; } $bindValues = []; foreach ($serviceCategoryIds as $key => $serviceCategoryId) { $bindValues[":service_category_{$key}"] = $serviceCategoryId; } $serviceCategoryIdList = implode(', ', array_keys($bindValues)); $request = $this->translateDbName( <<<SQL SELECT sc_id FROM `:db`.service_categories WHERE sc_id IN ({$serviceCategoryIdList}) SQL ); $statement = $this->db->prepare($request); foreach ($bindValues as $key => $value) { $statement->bindValue($key, $value, \PDO::PARAM_INT); } $statement->execute(); return $statement->fetchAll(\PDO::FETCH_COLUMN, 0); } /** * @inheritDoc */ public function findAllExistingIds(array $serviceCategoriesIds): array { if ($serviceCategoriesIds === []) { return []; } $sqlConcatenator = new SqlConcatenator(); $sqlConcatenator->defineSelect( $this->translateDbName( <<<'SQL' SELECT sc.sc_id FROM `:db`.service_categories sc WHERE sc.sc_id IN (:service_categories_ids) AND sc.level IS NULL SQL ) ); $sqlConcatenator->storeBindValueMultiple(':service_categories_ids', $serviceCategoriesIds, \PDO::PARAM_INT); $statement = $this->db->prepare((string) $sqlConcatenator); $sqlConcatenator->bindValuesToStatement($statement); $statement->execute(); $serviceCategoriesIdsFound = []; while (($id = $statement->fetchColumn()) !== false) { $serviceCategoriesIdsFound[] = (int) $id; } return $serviceCategoriesIdsFound; } /** * @inheritDoc */ public function findAllExistingIdsByAccessGroups(array $serviceCategoriesIds, array $accessGroups): array { if ($serviceCategoriesIds === [] || $accessGroups === []) { return []; } $accessGroupIds = array_map( static fn ($accessGroup): int => $accessGroup->getId(), $accessGroups ); // if service categories are not filtered in ACLs, then user has access to ALL service categories if (! $this->hasRestrictedAccessToServiceCategories($accessGroupIds)) { $this->info('Service categories access not filtered'); return $this->findAllExistingIds($serviceCategoriesIds); } $sqlConcatenator = new SqlConcatenator(); $sqlConcatenator->defineSelect( $this->translateDbName( <<<'SQL' SELECT sc.sc_id, sc.sc_name, sc.sc_description, sc.sc_activate FROM `:db`.service_categories sc INNER JOIN `:db`.service_categories_relation scr ON scr.sc_id = sc.sc_id INNER JOIN `:db`.acl_resources_sc_relations arhr ON sc.sc_id = arhr.sc_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 WHERE scr.sc_id IN (:service_categories_ids) AND sc.level IS NULL AND argr.acl_group_id IN (:access_group_ids) SQL ) ); $sqlConcatenator->storeBindValueMultiple(':service_categories_ids', $serviceCategoriesIds, \PDO::PARAM_INT); $sqlConcatenator->storeBindValueMultiple(':access_group_ids', $accessGroupIds, \PDO::PARAM_INT); $statement = $this->db->prepare((string) $sqlConcatenator); $sqlConcatenator->bindValuesToStatement($statement); $statement->execute(); $serviceCategoriesIdsFound = []; while (($id = $statement->fetchColumn()) !== false) { $serviceCategoriesIdsFound[] = (int) $id; } return $serviceCategoriesIdsFound; } /** * @inheritDoc */ public function findByRequestParameter(RequestParametersInterface $requestParameters): array { $this->info('Getting all service categories'); $concatenators = $this->findServiceCategoriesRequest($requestParameters); return $this->retrieveServiceCategories($concatenators, $requestParameters); } /** * @inheritDoc */ public function findByRequestParameterAndAccessGroups( array $accessGroups, RequestParametersInterface $requestParameters, ): array { $this->info('Getting all service categories by access groups'); if ($accessGroups === []) { $this->debug('No access group for this user, return empty'); return []; } $accessGroupIds = array_map( static fn ($accessGroup) => $accessGroup->getId(), $accessGroups ); // if service categories are not filtered in ACLs, then user has access to ALL service categories if (! $this->hasRestrictedAccessToServiceCategories($accessGroupIds)) { $this->info('Service categories access not filtered'); return $this->findByRequestParameter($requestParameters); } $concatenators = $this->findServiceCategoriesRequest($requestParameters, $accessGroupIds); foreach ($concatenators as $concatenator) { $concatenator->appendJoins( <<<'SQL' INNER JOIN `:db`.acl_resources_sc_relations arscr ON arscr.sc_id = sc.sc_id INNER JOIN `:db`.acl_resources res ON res.acl_res_id = arscr.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 SQL ); $concatenator->storeBindValueMultiple(':access_group_ids', $accessGroupIds, \PDO::PARAM_INT) ->appendWhere( <<<'SQL' ag.acl_group_id IN (:access_group_ids) SQL ); } return $this->retrieveServiceCategories($concatenators, $requestParameters); } /** * @inheritDoc */ public function findById(int $serviceCategoryId): ?ServiceCategory { $this->info('Get a service category with id #' . $serviceCategoryId); $request = $this->translateDbName( <<<'SQL' SELECT sc.sc_id, sc.sc_name, sc.sc_description, sc.sc_activate FROM `:db`.service_categories sc WHERE sc.sc_id = :serviceCategoryId AND sc.level IS NULL SQL ); $statement = $this->db->prepare($request); $statement->bindValue(':serviceCategoryId', $serviceCategoryId, \PDO::PARAM_INT); $statement->execute(); $result = $statement->fetch(\PDO::FETCH_ASSOC); if ($result === false) { return null; } /** @var _ServiceCategory $result */ return $this->createServiceCategoryFromArray($result); } /** * @inheritDoc */ public function findNames(array $serviceCategoryIds): ServiceCategoryNamesById { $concatenator = new SqlConcatenator(); $serviceCategoryIds = array_unique($serviceCategoryIds); $concatenator->defineSelect( <<<'SQL' SELECT sc.sc_id, sc.sc_name FROM `:db`.service_categories sc WHERE sc.sc_id IN (:serviceCategoryIds) AND sc.level IS NULL SQL ); $concatenator->storeBindValueMultiple(':serviceCategoryIds', $serviceCategoryIds, \PDO::PARAM_INT); $statement = $this->db->prepare($this->translateDbName($concatenator->__toString())); $concatenator->bindValuesToStatement($statement); $statement->setFetchMode(\PDO::FETCH_ASSOC); $statement->execute(); $categoryNames = new ServiceCategoryNamesById(); foreach ($statement as $result) { /** @var array{sc_id:int,sc_name:string} $result */ $categoryNames->addName( $result['sc_id'], new TrimmedString($result['sc_name']) ); } return $categoryNames; } /** * @inheritDoc */ public function findByService(int $serviceId): array { $request = $this->translateDbName( <<<'SQL' SELECT sc.sc_id, sc.sc_name, sc.sc_description, sc.sc_activate FROM `:db`.service_categories sc INNER JOIN `:db`.service_categories_relation scr ON scr.sc_id = sc.sc_id WHERE scr.service_service_id = :service_id AND sc.level IS NULL SQL ); $statement = $this->db->prepare($request); $statement->bindValue(':service_id', $serviceId, \PDO::PARAM_INT); $statement->execute(); $serviceCategories = []; while (is_array($result = $statement->fetch(\PDO::FETCH_ASSOC))) { /** @var _ServiceCategory $result */ $serviceCategories[] = $this->createServiceCategoryFromArray($result); } return $serviceCategories; } /** * @inheritDoc */ public function findByServiceAndAccessGroups(int $serviceId, array $accessGroups): array { if ($accessGroups === []) { return []; } $accessGroupIds = array_map( static fn ($accessGroup) => $accessGroup->getId(), $accessGroups ); // if service categories are not filtered in ACLs, then user has access to ALL service categories if (! $this->hasRestrictedAccessToServiceCategories($accessGroupIds)) { $this->info('Service categories access not filtered'); return $this->findByService($serviceId); } $sqlConcatenator = new SqlConcatenator(); $sqlConcatenator->defineSelect( $this->translateDbName( <<<'SQL' SELECT sc.sc_id, sc.sc_name, sc.sc_description, sc.sc_activate FROM `:db`.service_categories sc INNER JOIN `:db`.service_categories_relation scr ON scr.sc_id = sc.sc_id INNER JOIN `:db`.acl_resources_sc_relations arhr ON sc.sc_id = arhr.sc_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 WHERE scr.service_service_id = :service_id AND sc.level IS NULL AND argr.acl_group_id IN (:access_group_ids) GROUP BY sc.sc_id SQL ) ); $sqlConcatenator->storeBindValue(':service_id', $serviceId, \PDO::PARAM_INT); $sqlConcatenator->storeBindValueMultiple(':access_group_ids', $accessGroupIds, \PDO::PARAM_INT); $statement = $this->db->prepare((string) $sqlConcatenator); $sqlConcatenator->bindValuesToStatement($statement); $statement->execute(); $serviceCategories = []; while (is_array($result = $statement->fetch(\PDO::FETCH_ASSOC))) { /** @var _ServiceCategory $result */ $serviceCategories[] = $this->createServiceCategoryFromArray($result); } return $serviceCategories; } /** * @inheritDoc */ public function exists(int $serviceCategoryId): bool { $this->info('Check existence of service category with id #' . $serviceCategoryId); $request = $this->translateDbName( 'SELECT 1 FROM `:db`.service_categories sc WHERE sc.sc_id = :serviceCategoryId AND sc.level IS NULL' ); $statement = $this->db->prepare($request); $statement->bindValue(':serviceCategoryId', $serviceCategoryId, \PDO::PARAM_INT); $statement->execute(); return (bool) $statement->fetchColumn(); } /** * @inheritDoc */ public function existsByAccessGroups(int $serviceCategoryId, array $accessGroups): bool { $this->info( 'Check existence of service category by access groups', ['id' => $serviceCategoryId, 'accessgroups' => $accessGroups] ); if ($accessGroups === []) { $this->debug('Access groups array empty'); return false; } $concat = new SqlConcatenator(); $accessGroupIds = array_map( static fn ($accessGroup) => $accessGroup->getId(), $accessGroups ); // if service categories are not filtered in ACLs, then user has access to ALL service categories if (! $this->hasRestrictedAccessToServiceCategories($accessGroupIds)) { $this->info('Service categories access not filtered'); return $this->exists($serviceCategoryId); } $request = $this->translateDbName( 'SELECT 1 FROM `:db`.service_categories sc INNER JOIN `:db`.acl_resources_sc_relations arhr ON sc.sc_id = arhr.sc_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' ); $concat->appendWhere('sc.sc_id = :serviceCategoryId'); $concat->appendWhere('sc.level IS NULL'); $concat->storeBindValueMultiple(':access_group_ids', $accessGroupIds, \PDO::PARAM_INT) ->appendWhere('ag.acl_group_id IN (:access_group_ids)'); $statement = $this->db->prepare($this->translateDbName($request . ' ' . $concat)); foreach ($concat->retrieveBindValues() as $param => [$value, $type]) { $statement->bindValue($param, $value, $type); } $statement->bindValue(':serviceCategoryId', $serviceCategoryId, \PDO::PARAM_INT); $statement->execute(); return (bool) $statement->fetchColumn(); } /** * @inheritDoc */ public function existsByName(TrimmedString $serviceCategoryName): bool { $this->info('Check existence of service category with name ' . $serviceCategoryName); $request = $this->translateDbName( 'SELECT 1 FROM `:db`.service_categories sc WHERE sc.sc_name = :serviceCategoryName' ); $statement = $this->db->prepare($request); $statement->bindValue(':serviceCategoryName', $serviceCategoryName, \PDO::PARAM_STR); $statement->execute(); return (bool) $statement->fetchColumn(); } /** * Determine if service categories are filtered for given access group ids * true: accessible service categories are filtered (only specified are accessible) * false: accessible service categories are not filtered (all are accessible). * * @param int[] $accessGroupIds * * @phpstan-param non-empty-array<int> $accessGroupIds * * @return bool */ public function hasRestrictedAccessToServiceCategories(array $accessGroupIds): bool { $concatenator = new SqlConcatenator(); $concatenator->defineSelect( 'SELECT 1 FROM `:db`.acl_resources_sc_relations arhr 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' ); $concatenator->storeBindValueMultiple(':access_group_ids', $accessGroupIds, \PDO::PARAM_INT) ->appendWhere('ag.acl_group_id IN (:access_group_ids)'); $statement = $this->db->prepare($this->translateDbName($concatenator->__toString())); $concatenator->bindValuesToStatement($statement); $statement->execute(); return (bool) $statement->fetchColumn(); } /** * @param _ServiceCategory $result * * @return ServiceCategory */ private function createServiceCategoryFromArray(array $result): ServiceCategory { $serviceCategory = new ServiceCategory( $result['sc_id'], $result['sc_name'], $result['sc_description'] ); $serviceCategory->setActivated((bool) $result['sc_activate']); return $serviceCategory; } /** * @param RequestParametersInterface $requestParameters * @param int[] $accessGroupIds * * @return array<SqlConcatenator> */ private function findServiceCategoriesRequest(RequestParametersInterface $requestParameters, array $accessGroupIds = []): array { $hostAcls = ''; $hostGroupAcls = ''; $hostCategoryAcls = ''; $serviceGroupAcls = ''; if ($accessGroupIds !== []) { if (! $this->hasAccessToAllHosts($accessGroupIds)) { $hostAcls = <<<'SQL' AND hsr.host_host_id IN ( SELECT arhr.host_host_id FROM `:db`.acl_resources_host_relations arhr INNER JOIN `:db`.acl_resources res ON res.acl_res_id = arhr.acl_res_id INNER JOIN `:db`.acl_res_group_relations argr ON argr.acl_res_id = res.acl_res_id INNER JOIN `:db`.acl_groups ag ON ag.acl_group_id = argr.acl_group_id WHERE ag.acl_group_id IN (:access_group_ids) ) SQL; } if (! $this->hasAccessToAllHostGroups($accessGroupIds)) { $hostGroupAcls = <<<'SQL' AND hr.hostgroup_hg_id IN ( 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 (:access_group_ids) ) SQL; } 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 (:access_group_ids) ) SQL; } if (! $this->hasAccessToAllServiceGroups($accessGroupIds)) { $serviceGroupAcls = <<<'SQL' AND sgr.servicegroup_sg_id IN ( SELECT arsgr.sg_id FROM `:db`.acl_resources_sg_relations arsgr INNER JOIN `:db`.acl_resources res ON res.acl_res_id = arsgr.acl_res_id INNER JOIN `:db`.acl_res_group_relations argr ON arsgr.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 (:access_group_ids) ) SQL; } } $searchAsString = $requestParameters->getSearchAsString(); \preg_match_all('/\{"(?<object>\w+)\.\w+"/', $searchAsString, $matches); $findCategoryByServiceConcatenator = new SqlConcatenator(); $findCategoryByServiceConcatenator->defineSelect( <<<'SQL' SELECT sc.sc_id, sc.sc_name, sc.sc_description, sc.sc_activate FROM `:db`.service_categories sc SQL ); $findCategoryByServiceTemplateConcatenator = new SqlConcatenator(); $findCategoryByServiceTemplateConcatenator->defineSelect( <<<'SQL' SELECT sc.sc_id, sc.sc_name, sc.sc_description, sc.sc_activate FROM `:db`.service_categories sc SQL ); if (\in_array('hostcategory', $matches['object'], true)) { $findCategoryByServiceConcatenator->appendJoins( <<<SQL LEFT JOIN `:db`.service_categories_relation scr ON scr.sc_id = sc.sc_id LEFT JOIN `:db`.host_service_relation hsr ON hsr.service_service_id = scr.service_service_id {$hostAcls} LEFT JOIN `:db`.host ON host.host_id = hsr.host_host_id LEFT JOIN `:db`.hostgroup_relation hr ON hr.host_host_id = host.host_id {$hostGroupAcls} LEFT JOIN `:db`.hostgroup ON hostgroup.hg_id = hr.hostgroup_hg_id LEFT JOIN `:db`.hostcategories_relation hcr ON hcr.host_host_id = host.host_id {$hostCategoryAcls} LEFT JOIN `:db`.hostcategories ON hostcategories.hc_id = hcr.hostcategories_hc_id SQL ); $findCategoryByServiceTemplateConcatenator->appendJoins( <<<SQL LEFT JOIN `:db`.service_categories_relation scr ON scr.sc_id = sc.sc_id LEFT JOIN `:db`.service s ON s.service_template_model_stm_id = scr.service_service_id LEFT JOIN `:db`.host_service_relation hsr ON hsr.service_service_id = s.service_id {$hostAcls} LEFT JOIN `:db`.host ON host.host_id = hsr.host_host_id LEFT JOIN `:db`.hostgroup_relation hr ON hr.host_host_id = host.host_id {$hostGroupAcls} LEFT JOIN `:db`.hostgroup ON hostgroup.hg_id = hr.hostgroup_hg_id LEFT JOIN `:db`.hostcategories_relation hcr ON hcr.host_host_id = host.host_id {$hostCategoryAcls} LEFT JOIN `:db`.hostcategories ON hostcategories.hc_id = hcr.hostcategories_hc_id SQL ); } elseif (\in_array('hostgroup', $matches['object'], true)) { $findCategoryByServiceConcatenator->appendJoins( <<<SQL LEFT JOIN `:db`.service_categories_relation scr ON scr.sc_id = sc.sc_id LEFT JOIN `:db`.host_service_relation hsr ON hsr.service_service_id = scr.service_service_id {$hostAcls} LEFT JOIN `:db`.host ON host.host_id = hsr.host_host_id LEFT JOIN `:db`.hostgroup_relation hr ON hr.host_host_id = host.host_id {$hostGroupAcls} LEFT JOIN `:db`.hostgroup ON hostgroup.hg_id = hr.hostgroup_hg_id SQL ); $findCategoryByServiceTemplateConcatenator->appendJoins( <<<SQL LEFT JOIN `:db`.service_categories_relation scr ON scr.sc_id = sc.sc_id LEFT JOIN `:db`.service s ON s.service_template_model_stm_id = scr.service_service_id LEFT JOIN `:db`.host_service_relation hsr ON hsr.service_service_id = s.service_id {$hostAcls} LEFT JOIN `:db`.host ON host.host_id = hsr.host_host_id LEFT JOIN `:db`.hostgroup_relation hr ON hr.host_host_id = host.host_id {$hostGroupAcls} LEFT JOIN `:db`.hostgroup ON hostgroup.hg_id = hr.hostgroup_hg_id SQL ); } elseif (\in_array('host', $matches['object'], true)) { $findCategoryByServiceConcatenator->appendJoins( <<<SQL LEFT JOIN `:db`.service_categories_relation scr ON scr.sc_id = sc.sc_id LEFT JOIN `:db`.host_service_relation hsr ON hsr.service_service_id = scr.service_service_id {$hostAcls} LEFT JOIN `:db`.host ON host.host_id = hsr.host_host_id SQL ); $findCategoryByServiceTemplateConcatenator->appendJoins( <<<SQL LEFT JOIN `:db`.service_categories_relation scr ON scr.sc_id = sc.sc_id LEFT JOIN `:db`.service s ON s.service_template_model_stm_id = scr.service_service_id LEFT JOIN `:db`.host_service_relation hsr ON hsr.service_service_id = s.service_id {$hostAcls} LEFT JOIN `:db`.host ON host.host_id = hsr.host_host_id SQL ); } elseif (\in_array('servicegroup', $matches['object'], true)) { $findCategoryByServiceConcatenator->appendJoins( <<<SQL LEFT JOIN `:db`.service_categories_relation scr ON scr.sc_id = sc.sc_id LEFT JOIN `:db`.service s ON s.service_id = scr.service_service_id LEFT JOIN `:db`.servicegroup_relation sgr ON sgr.service_service_id = s.service_id {$serviceGroupAcls} LEFT JOIN `:db`.servicegroup ON sgr.servicegroup_sg_id = servicegroup.sg_id SQL ); $findCategoryByServiceTemplateConcatenator->appendJoins( <<<SQL LEFT JOIN `:db`.service_categories_relation scr ON scr.sc_id = sc.sc_id LEFT JOIN `:db`.service s ON s.service_template_model_stm_id = scr.service_service_id LEFT JOIN `:db`.servicegroup_relation sgr ON sgr.service_service_id = s.service_id {$serviceGroupAcls} LEFT JOIN `:db`.servicegroup ON sgr.servicegroup_sg_id = servicegroup.sg_id SQL ); } return [$findCategoryByServiceConcatenator, $findCategoryByServiceTemplateConcatenator]; } /** * @param array<SqlConcatenator> $concatenators * @param RequestParametersInterface $requestParameters * * @return ServiceCategory[] */ private function retrieveServiceCategories( array $concatenators, RequestParametersInterface $requestParameters, ): array { $concatenatorsAsString = []; // Settup for search, pagination, order $sqlTranslator = new SqlRequestParametersTranslator($requestParameters); $sqlTranslator->setConcordanceArray([ 'id' => 'sc.sc_id', 'name' => 'sc.sc_name', 'alias' => 'sc.sc_description', 'is_activated' => 'sc.sc_activate', 'host.id' => 'host.host_id', 'host.name' => 'host.host_name', 'hostgroup.id' => 'hostgroup.hg_id', 'hostgroup.name' => 'hostgroup.hg_name', 'hostcategory.id' => 'hostcategories.hc_id', 'hostcategory.name' => 'hostcategories.hc_name', 'servicegroup.id' => 'servicegroup.sg_id', 'servicegroup.name' => 'servicegroup.sg_name', ]); foreach ($concatenators as $concatenator) { // Exclude severities from the results $concatenator->appendWhere('sc.level IS NULL'); $sqlTranslator->addNormalizer('is_activated', new BoolToEnumNormalizer()); $sqlTranslator->translateForConcatenator($concatenator); $concatenator->withCalcFoundRows(false); $concatenatorsAsString[] = $concatenator->concatForUnion(); } $concatenator = new SqlConcatenator(); $concatenator->withCalcFoundRows(true); $concatenator->defineSelect( <<<'SQL' SELECT * SQL )->defineFrom('(' . \implode(' UNION ', $concatenatorsAsString) . ') AS union_table');
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
true
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceCategory/Infrastructure/Repository/DbReadRealTimeServiceCategoryRepository.php
centreon/src/Core/ServiceCategory/Infrastructure/Repository/DbReadRealTimeServiceCategoryRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\ServiceCategory\Infrastructure\Repository; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Centreon\Infrastructure\DatabaseConnection; use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator; use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB; use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait; use Core\ServiceCategory\Application\Repository\ReadRealTimeServiceCategoryRepositoryInterface; use Core\Tag\RealTime\Domain\Model\Tag; /** * @phpstan-type _ServiceCategoryResultSet array{ * id: int, * name: string, * type: int * } */ class DbReadRealTimeServiceCategoryRepository extends AbstractRepositoryRDB implements ReadRealTimeServiceCategoryRepositoryInterface { use SqlMultipleBindTrait; /** * @param DatabaseConnection $db */ public function __construct(DatabaseConnection $db) { $this->db = $db; } /** * @inheritDoc */ public function findAll(?RequestParametersInterface $requestParameters): array { $sqlTranslator = $requestParameters ? new SqlRequestParametersTranslator($requestParameters) : null; $sqlTranslator?->setConcordanceArray([ 'id' => 'service_categories.id', 'name' => 'service_categories.name', 'host_group.id' => 'host_groups.id', 'host_group.name' => 'host_groups.name', 'host_category.id' => 'host_categories.id', 'host_category.name' => 'host_categories.name', 'host.id' => 'parent_resource.id', 'host.name' => 'parent_resource.name', 'service_group.id' => 'service_groups.id', 'service_group.name' => 'service_groups.name', ]); /** * Tag types: * 0 = service groups, * 1 = host groups, * 2 = service categories. * 3 = host categories. */ $request = <<<'SQL' SELECT 1 AS REALTIME, service_categories.id AS id, service_categories.name AS name, service_categories.type AS `type` FROM `:dbstg`.resources INNER JOIN `:dbstg`.resources_tags rtags ON rtags.resource_id = resources.resource_id INNER JOIN `:dbstg`.tags AS service_categories ON service_categories.tag_id = rtags.tag_id AND service_categories.`type` = 2 SQL; $searchRequest = $sqlTranslator?->translateSearchParameterToSql(); if ($searchRequest !== null) { $request .= <<<'SQL' INNER JOIN `:dbstg`.resources AS parent_resource ON parent_resource.id = resources.parent_id LEFT JOIN `:dbstg`.resources_tags rtags_host_groups ON rtags_host_groups.resource_id = parent_resource.resource_id LEFT JOIN `:dbstg`.tags AS host_groups ON rtags_host_groups.tag_id = host_groups.tag_id AND host_groups.`type` = 1 LEFT JOIN `:dbstg`.resources_tags rtags_host_categories ON rtags_host_categories.resource_id = parent_resource.resource_id LEFT JOIN `:dbstg`.tags AS host_categories ON rtags_host_categories.tag_id = host_categories.tag_id AND host_categories.`type` = 3 LEFT JOIN `:dbstg`.resources_tags rtags_service_groups ON rtags_service_groups.resource_id = resources.resource_id LEFT JOIN `:dbstg`.tags AS service_groups ON rtags_service_groups.tag_id = service_groups.tag_id AND service_groups.`type` = 0 SQL; $request .= $searchRequest; } $request .= ' GROUP BY service_categories.id, service_categories.name'; $sortRequest = $sqlTranslator?->translateSortParameterToSql(); $request .= $sortRequest ?? ' ORDER BY service_categories.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); // Retrieve data $serviceCategories = []; foreach ($statement as $record) { /** @var _ServiceCategoryResultSet $record */ $serviceCategories[] = $this->createFromRecord($record); } return $serviceCategories; } /** * @inheritDoc */ public function findAllByAccessGroupIds(?RequestParametersInterface $requestParameters, array $accessGroupIds): array { $sqlTranslator = $requestParameters ? new SqlRequestParametersTranslator($requestParameters) : null; $sqlTranslator?->setConcordanceArray([ 'id' => 'service_categories.id', 'name' => 'service_categories.name', 'host_group.id' => 'host_groups.id', 'host_group.name' => 'host_groups.name', 'host_category.id' => 'host_categories.id', 'host_category.name' => 'host_categories.name', 'host.id' => 'parent_resource.id', 'host.name' => 'parent_resource.name', 'service_group.id' => 'service_groups.id', 'service_group.name' => 'service_groups.name', ]); [$bindValues, $bindQuery] = $this->createMultipleBindQuery($accessGroupIds, ':access_group_id_'); /** * Tag types: * 0 = service groups, * 1 = host groups, * 2 = service categories. * 3 = host categories. */ $request = <<<'SQL' SELECT 1 AS REALTIME, service_categories.id AS id, service_categories.name AS name, service_categories.type AS `type` FROM `:dbstg`.resources INNER JOIN `:dbstg`.resources_tags rtags ON rtags.resource_id = resources.resource_id INNER JOIN `:dbstg`.tags AS service_categories ON service_categories.tag_id = rtags.tag_id AND service_categories.`type` = 2 INNER JOIN `:db`.acl_resources_sc_relations arsr ON service_categories.id = arsr.sc_id INNER JOIN `:db`.acl_resources res ON arsr.acl_res_id = res.acl_res_id INNER JOIN `:db`.acl_res_group_relations argr ON res.acl_res_id = argr.acl_res_id INNER JOIN `:db`.acl_groups ag ON argr.acl_group_id = ag.acl_group_id SQL; $searchRequest = $sqlTranslator?->translateSearchParameterToSql(); if ($searchRequest !== null) { $request .= <<<'SQL' INNER JOIN `:dbstg`.resources AS parent_resource ON parent_resource.id = resources.parent_id LEFT JOIN `:dbstg`.resources_tags rtags_host_groups ON rtags_host_groups.resource_id = parent_resource.resource_id LEFT JOIN `:dbstg`.tags AS host_groups ON rtags_host_groups.tag_id = host_groups.tag_id AND host_groups.`type` = 1 LEFT JOIN `:dbstg`.resources_tags rtags_host_categories ON rtags_host_categories.resource_id = resources.resource_id LEFT JOIN `:dbstg`.tags AS host_categories ON rtags_host_categories.tag_id = host_categories.tag_id AND host_categories.`type` = 3 LEFT JOIN `:dbstg`.resources_tags rtags_service_groups ON rtags_service_groups.resource_id = resources.resource_id LEFT JOIN `:dbstg`.tags AS service_groups ON rtags_service_groups.tag_id = service_groups.tag_id AND service_groups.`type` = 0 SQL; } $request .= $searchRequest !== null ? $searchRequest . ' AND ' : ' WHERE '; $request .= " ag.acl_group_id IN ({$bindQuery})"; $request .= ' GROUP BY service_categories.id, service_categories.name'; $sortRequest = $sqlTranslator?->translateSortParameterToSql(); $request .= $sortRequest ?? ' ORDER BY service_categories.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); // Retrieve data $serviceCategories = []; foreach ($statement as $record) { /** @var _ServiceCategoryResultSet $record */ $serviceCategories[] = $this->createFromRecord($record); } return $serviceCategories; } /** * @param _ServiceCategoryResultSet $data * * @return Tag */ private function createFromRecord(array $data): Tag { return new Tag(id: $data['id'], name: $data['name'], type: $data['type']); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceCategory/Infrastructure/Repository/DbWriteServiceCategoryRepository.php
centreon/src/Core/ServiceCategory/Infrastructure/Repository/DbWriteServiceCategoryRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\ServiceCategory\Infrastructure\Repository; use Centreon\Domain\Log\LoggerTrait; use Centreon\Infrastructure\DatabaseConnection; use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB; use Core\Common\Infrastructure\RequestParameters\Normalizer\BoolToEnumNormalizer; use Core\ServiceCategory\Application\Repository\WriteServiceCategoryRepositoryInterface; use Core\ServiceCategory\Domain\Model\NewServiceCategory; class DbWriteServiceCategoryRepository extends AbstractRepositoryRDB implements WriteServiceCategoryRepositoryInterface { use LoggerTrait; public function __construct(DatabaseConnection $db) { $this->db = $db; } /** * @inheritDoc */ public function deleteById(int $serviceCategoryId): void { $this->debug('Delete service category', ['serviceCategoryId' => $serviceCategoryId]); $request = $this->translateDbName( 'DELETE sc FROM `:db`.service_categories sc WHERE sc.sc_id = :serviceCategoryId' ); $request .= ' AND sc.level IS NULL '; $statement = $this->db->prepare($request); $statement->bindValue(':serviceCategoryId', $serviceCategoryId, \PDO::PARAM_INT); $statement->execute(); } /** * @inheritDoc */ public function add(NewServiceCategory $serviceCategory): int { $this->debug('Add service category', ['serviceCategory' => $serviceCategory]); $request = $this->translateDbName( 'INSERT INTO `:db`.service_categories (sc_name, sc_description, sc_activate) VALUES (:name, :alias, :isActivated)' ); $statement = $this->db->prepare($request); $statement->bindValue(':name', $serviceCategory->getName(), \PDO::PARAM_STR); $statement->bindValue(':alias', $serviceCategory->getAlias(), \PDO::PARAM_STR); $statement->bindValue(':isActivated', (new BoolToEnumNormalizer())->normalize($serviceCategory->isActivated()), \PDO::PARAM_STR); $statement->execute(); return (int) $this->db->lastInsertId(); } /** * @inheritDoc */ public function linkToService(int $serviceId, array $serviceCategoriesIds): void { if ($serviceCategoriesIds === []) { return; } $request = <<<'SQL' INSERT INTO service_categories_relation (service_service_id, sc_id) VALUES (:service_id, :service_category_id) SQL; $alreadyInTransaction = $this->db->inTransaction(); try { if (! $alreadyInTransaction) { $this->db->beginTransaction(); } $statement = $this->db->prepare($request); $serviceCategoriesId = null; $statement->bindParam(':service_id', $serviceId, \PDO::PARAM_INT); $statement->bindParam(':service_category_id', $serviceCategoriesId, \PDO::PARAM_INT); foreach ($serviceCategoriesIds as $serviceCategoriesId) { $statement->execute(); } if (! $alreadyInTransaction) { $this->db->commit(); } } catch (\Throwable $ex) { if (! $alreadyInTransaction) { $this->db->rollBack(); } throw $ex; } } /** * @inheritDoc */ public function unlinkFromService(int $serviceId, array $serviceCategoriesIds): void { if ($serviceCategoriesIds === []) { return; } $alreadyInTransaction = $this->db->inTransaction(); try { if (! $alreadyInTransaction) { $this->db->beginTransaction(); } $bindServiceCategoriesIds = []; foreach ($serviceCategoriesIds as $index => $serviceCategoriesId) { $bindServiceCategoriesIds[':service_categories_' . $index] = [\PDO::PARAM_INT => $serviceCategoriesId]; } $serviceCategoriesFields = implode(',', array_keys($bindServiceCategoriesIds)); $request = $this->translateDbName( <<<"SQL" DELETE FROM `:db`.service_categories_relation WHERE service_service_id = :service_id AND sc_id IN ({$serviceCategoriesFields}) SQL ); $statement = $this->db->prepare($request); $statement->bindValue(':service_id', $serviceId, \PDO::PARAM_INT); foreach ($bindServiceCategoriesIds as $field => $details) { $type = key($details); $statement->bindValue($field, $details[$type], $type); } $statement->execute(); if (! $alreadyInTransaction) { $this->db->commit(); } } catch (\Throwable $ex) { if (! $alreadyInTransaction) { $this->db->rollBack(); } throw $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/ServiceCategory/Infrastructure/Repository/DbWriteServiceCategoryActionLogRepository.php
centreon/src/Core/ServiceCategory/Infrastructure/Repository/DbWriteServiceCategoryActionLogRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\ServiceCategory\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\ServiceCategory\Application\Repository\ReadServiceCategoryRepositoryInterface; use Core\ServiceCategory\Application\Repository\WriteServiceCategoryRepositoryInterface; use Core\ServiceCategory\Domain\Model\NewServiceCategory; class DbWriteServiceCategoryActionLogRepository extends AbstractRepositoryRDB implements WriteServiceCategoryRepositoryInterface { use LoggerTrait; public const SERVICE_CATEGORY_PROPERTIES_MAP = [ 'name' => 'sc_name', 'alias' => 'sc_alias', 'isActivated' => 'sc_activate', ]; public function __construct( private readonly WriteServiceCategoryRepositoryInterface $writeServiceCategoryRepository, private readonly WriteActionLogRepositoryInterface $writeActionLogRepository, private readonly ReadServiceCategoryRepositoryInterface $readServiceCategoryRepository, private readonly ContactInterface $user, DatabaseConnection $db, ) { $this->db = $db; } /** * @inheritDoc */ public function deleteById(int $serviceCategoryId): void { try { $serviceCategory = $this->readServiceCategoryRepository->findById($serviceCategoryId); if ($serviceCategory === null) { return; } $this->writeServiceCategoryRepository->deleteById($serviceCategoryId); $actionLog = new ActionLog( objectType: ActionLog::OBJECT_TYPE_SERVICECATEGORIES, objectId: $serviceCategoryId, objectName: $serviceCategory->getName(), actionType: ActionLog::ACTION_TYPE_DELETE, contactId: $this->user->getId() ); $this->writeActionLogRepository->addAction($actionLog); } catch (\Throwable $ex) { $this->error( 'Error while deleting a service category', ['serviceCategoryId' => $serviceCategoryId, 'trace' => (string) $ex] ); throw $ex; } } /** * @inheritDoc */ public function add(NewServiceCategory $serviceCategory): int { try { $serviceCategoryId = $this->writeServiceCategoryRepository->add($serviceCategory); if ($serviceCategoryId === 0) { throw new RepositoryException('Service Category ID cannot be 0'); } $actionLog = new ActionLog( objectType: ActionLog::OBJECT_TYPE_SERVICECATEGORIES, objectId: $serviceCategoryId, objectName: $serviceCategory->getName(), actionType: ActionLog::ACTION_TYPE_ADD, contactId: $this->user->getId() ); $actionLogId = $this->writeActionLogRepository->addAction($actionLog); $actionLog->setId($actionLogId); $details = $this->getServiceCategoryAsArray($serviceCategory); $this->writeActionLogRepository->addActionDetails($actionLog, $details); return $serviceCategoryId; } catch (\Throwable $ex) { $this->error( 'Error while adding a service category', ['serviceCategory' => $serviceCategory, 'trace' => (string) $ex] ); throw $ex; } } /** * @inheritDoc */ public function linkToService(int $serviceId, array $serviceCategoriesIds): void { $this->writeServiceCategoryRepository->linkToService($serviceId, $serviceCategoriesIds); } /** * @inheritDoc */ public function unlinkFromService(int $serviceId, array $serviceCategoriesIds): void { $this->writeServiceCategoryRepository->unlinkFromService($serviceId, $serviceCategoriesIds); } /** * Format the Service Category as property => value array. * * @param NewServiceCategory $serviceCategory * * @return array<string, string> */ private function getServiceCategoryAsArray( NewServiceCategory $serviceCategory, ): array { $reflection = new \ReflectionClass($serviceCategory); $properties = $reflection->getProperties(); $serviceCategoryAsArray = []; foreach ($properties as $property) { $property->setAccessible(true); if ($property->getName() === 'isActivated') { $serviceCategoryAsArray[self::SERVICE_CATEGORY_PROPERTIES_MAP[$property->getName()]] = $property->getValue($serviceCategory) ? '1' : '0'; } else { $serviceCategoryAsArray[self::SERVICE_CATEGORY_PROPERTIES_MAP[$property->getName()]] = is_string($property->getValue($serviceCategory)) ? $property->getValue($serviceCategory) : throw new RepositoryException('Property value is not a string'); } } return $serviceCategoryAsArray; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceCategory/Infrastructure/API/FindServiceCategories/FindServiceCategoriesPresenter.php
centreon/src/Core/ServiceCategory/Infrastructure/API/FindServiceCategories/FindServiceCategoriesPresenter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\ServiceCategory\Infrastructure\API\FindServiceCategories; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\ServiceCategory\Application\UseCase\FindServiceCategories\FindServiceCategoriesResponse; class FindServiceCategoriesPresenter extends AbstractPresenter { public function __construct( private RequestParametersInterface $requestParameters, protected PresenterFormatterInterface $presenterFormatter, ) { parent::__construct($presenterFormatter); } /** * @param FindServiceCategoriesResponse $data */ public function present(mixed $data): void { $result = []; foreach ($data->serviceCategories as $serviceCategory) { $result[] = [ 'id' => $serviceCategory['id'], 'name' => $serviceCategory['name'], 'alias' => $serviceCategory['alias'], 'is_activated' => $serviceCategory['is_activated'], ]; } parent::present([ 'result' => $result, 'meta' => $this->requestParameters->toArray(), ]); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceCategory/Infrastructure/API/FindServiceCategories/FindServiceCategoriesController.php
centreon/src/Core/ServiceCategory/Infrastructure/API/FindServiceCategories/FindServiceCategoriesController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\ServiceCategory\Infrastructure\API\FindServiceCategories; use Centreon\Application\Controller\AbstractController; use Core\ServiceCategory\Application\UseCase\FindServiceCategories\FindServiceCategories; final class FindServiceCategoriesController extends AbstractController { public function __invoke(FindServiceCategories $useCase, FindServiceCategoriesPresenter $presenter): object { $this->denyAccessUnlessGrantedForApiConfiguration(); $useCase($presenter); return $presenter->show(); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceCategory/Infrastructure/API/FindRealTimeServiceCategories/FindRealTimeServiceCategoriesPresenter.php
centreon/src/Core/ServiceCategory/Infrastructure/API/FindRealTimeServiceCategories/FindRealTimeServiceCategoriesPresenter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\ServiceCategory\Infrastructure\API\FindRealTimeServiceCategories; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\ServiceCategory\Application\UseCase\FindRealTimeServiceCategories\FindRealTimeServiceCategoriesPresenterInterface; use Core\ServiceCategory\Application\UseCase\FindRealTimeServiceCategories\FindRealTimeServiceCategoriesResponse; class FindRealTimeServiceCategoriesPresenter extends AbstractPresenter implements FindRealTimeServiceCategoriesPresenterInterface { /** * @param RequestParametersInterface $requestParameters * @param PresenterFormatterInterface $presenterFormatter */ public function __construct( private RequestParametersInterface $requestParameters, protected PresenterFormatterInterface $presenterFormatter, ) { } public function presentResponse(FindRealTimeServiceCategoriesResponse|ResponseStatusInterface $response): void { if ($response instanceof ResponseStatusInterface) { $this->setResponseStatus($response); } else { parent::present([ 'result' => $response->tags, '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/ServiceCategory/Infrastructure/API/FindRealTimeServiceCategories/FindRealTimeServiceCategoriesController.php
centreon/src/Core/ServiceCategory/Infrastructure/API/FindRealTimeServiceCategories/FindRealTimeServiceCategoriesController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\ServiceCategory\Infrastructure\API\FindRealTimeServiceCategories; use Centreon\Application\Controller\AbstractController; use Core\ServiceCategory\Application\UseCase\FindRealTimeServiceCategories\FindRealTimeServiceCategories; use Core\ServiceCategory\Application\UseCase\FindRealTimeServiceCategories\FindRealTimeServiceCategoriesPresenterInterface; final class FindRealTimeServiceCategoriesController extends AbstractController { /** * @param FindRealTimeServiceCategories $useCase * @param FindRealTimeServiceCategoriesPresenterInterface $presenter * * @return object */ public function __invoke( FindRealTimeServiceCategories $useCase, FindRealTimeServiceCategoriesPresenterInterface $presenter, ): object { /** * Access denied if no rights given to the realtime for the current user. */ $this->denyAccessUnlessGrantedForApiRealtime(); $useCase($presenter); return $presenter->show(); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceCategory/Infrastructure/API/DeleteServiceCategory/DeleteServiceCategoryController.php
centreon/src/Core/ServiceCategory/Infrastructure/API/DeleteServiceCategory/DeleteServiceCategoryController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\ServiceCategory\Infrastructure\API\DeleteServiceCategory; use Centreon\Application\Controller\AbstractController; use Core\Infrastructure\Common\Api\DefaultPresenter; use Core\ServiceCategory\Application\UseCase\DeleteServiceCategory\DeleteServiceCategory; final class DeleteServiceCategoryController extends AbstractController { public function __invoke( int $serviceCategoryId, DeleteServiceCategory $useCase, DefaultPresenter $presenter, ): object { $this->denyAccessUnlessGrantedForApiConfiguration(); $useCase($serviceCategoryId, $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/User/Application/Model/UserInterfaceDensityConverter.php
centreon/src/Core/User/Application/Model/UserInterfaceDensityConverter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\User\Application\Model; use Core\User\Domain\Model\UserInterfaceDensity; final class UserInterfaceDensityConverter { public static function fromString(?string $string): UserInterfaceDensity { return match ($string) { // We consider this should NOT fail and because this is not critical, we rely on the default. default => UserInterfaceDensity::Compact, 'extended' => UserInterfaceDensity::Extended, }; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/User/Application/Model/UserThemeConverter.php
centreon/src/Core/User/Application/Model/UserThemeConverter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\User\Application\Model; use Core\User\Domain\Model\UserTheme; final class UserThemeConverter { public static function fromString(?string $string): UserTheme { return match ($string) { // We consider this should NOT fail and because this is not critical, we rely on the default. default => UserTheme::Light, 'dark' => UserTheme::Dark, }; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/User/Application/UseCase/FindCurrentUserParameters/FindCurrentUserParameters.php
centreon/src/Core/User/Application/UseCase/FindCurrentUserParameters/FindCurrentUserParameters.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\User\Application\UseCase\FindCurrentUserParameters; use Centreon\Domain\Contact\Contact; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Log\LoggerTrait; use Core\Application\Common\UseCase\ErrorResponse; use Core\Dashboard\Domain\Model\DashboardRights; use Core\User\Application\Exception\UserException; use Core\User\Application\Model\UserInterfaceDensityConverter; use Core\User\Application\Model\UserThemeConverter; final class FindCurrentUserParameters { use LoggerTrait; public function __construct( private readonly ContactInterface $user, private readonly DashboardRights $rights, ) { } public function __invoke(FindCurrentUserParametersPresenterInterface $presenter): void { try { $response = $this->createResponse($this->user); $presenter->presentResponse($response); } catch (\Throwable $ex) { $presenter->presentResponse(new ErrorResponse(UserException::errorWhileSearchingForUser($ex))); $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); } } /** * @param ContactInterface $user * * @return FindCurrentUserParametersResponse */ public function createResponse(ContactInterface $user): FindCurrentUserParametersResponse { $dto = new FindCurrentUserParametersResponse(); $dto->id = $user->getId(); $dto->name = $user->getName(); $dto->alias = $user->getAlias(); $dto->email = $user->getEmail(); $dto->timezone = $user->getTimezone()->getName(); $dto->locale = $user->getLocale(); $dto->isAdmin = $user->isAdmin(); $dto->useDeprecatedPages = $user->isUsingDeprecatedPages(); $dto->useDeprecatedCustomViews = $user->isUsingDeprecatedCustomViews(); $dto->isExportButtonEnabled = $this->hasExportButtonRole($user); $dto->canManageApiTokens = $this->canManageApiTokens($user); $dto->theme = UserThemeConverter::fromString($user->getTheme()); $dto->userInterfaceDensity = UserInterfaceDensityConverter::fromString($user->getUserInterfaceDensity()); $dto->defaultPage = $user->getDefaultPage()?->getRedirectionUri(); $dto->dashboardPermissions->globalRole = $this->rights->getGlobalRole(); $dto->dashboardPermissions->hasViewerRole = $this->rights->hasViewerRole(); $dto->dashboardPermissions->hasCreatorRole = $this->rights->hasCreatorRole(); $dto->dashboardPermissions->hasAdminRole = $this->rights->hasAdminRole(); return $dto; } /** * @param ContactInterface $user * * @return bool */ private function hasExportButtonRole(ContactInterface $user): bool { return $user->isAdmin() || $user->hasRole(Contact::ROLE_GENERATE_CONFIGURATION); } /** * @param ContactInterface $user * * @return bool */ private function canManageApiTokens(ContactInterface $user): bool { return $user->isAdmin() || $user->hasRole(Contact::ROLE_MANAGE_TOKENS); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/User/Application/UseCase/FindCurrentUserParameters/FindCurrentUserParametersPresenterInterface.php
centreon/src/Core/User/Application/UseCase/FindCurrentUserParameters/FindCurrentUserParametersPresenterInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\User\Application\UseCase\FindCurrentUserParameters; use Core\Application\Common\UseCase\ResponseStatusInterface; interface FindCurrentUserParametersPresenterInterface { /** * @param FindCurrentUserParametersResponse|ResponseStatusInterface $data */ public function presentResponse(FindCurrentUserParametersResponse|ResponseStatusInterface $data): void; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/User/Application/UseCase/FindCurrentUserParameters/FindCurrentUserParametersResponse.php
centreon/src/Core/User/Application/UseCase/FindCurrentUserParameters/FindCurrentUserParametersResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\User\Application\UseCase\FindCurrentUserParameters; use Core\User\Application\UseCase\FindCurrentUserParameters\Response\DashboardPermissionsResponseDto; use Core\User\Domain\Model\UserInterfaceDensity; use Core\User\Domain\Model\UserTheme; final class FindCurrentUserParametersResponse { public UserTheme $theme; public UserInterfaceDensity $userInterfaceDensity; public function __construct( public int $id = 0, public string $name = '', public string $alias = '', public string $email = '', public string $timezone = '', public ?string $locale = null, public bool $isAdmin = false, public bool $useDeprecatedPages = false, public bool $useDeprecatedCustomViews = false, public bool $isExportButtonEnabled = false, public bool $canManageApiTokens = false, ?UserTheme $theme = null, ?UserInterfaceDensity $userInterfaceDensity = null, public ?string $defaultPage = null, public DashboardPermissionsResponseDto $dashboardPermissions = new DashboardPermissionsResponseDto(), ) { $this->theme = $theme ?? UserTheme::Light; $this->userInterfaceDensity = $userInterfaceDensity ?? UserInterfaceDensity::Compact; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/User/Application/UseCase/FindCurrentUserParameters/Response/DashboardPermissionsResponseDto.php
centreon/src/Core/User/Application/UseCase/FindCurrentUserParameters/Response/DashboardPermissionsResponseDto.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\User\Application\UseCase\FindCurrentUserParameters\Response; use Core\Dashboard\Domain\Model\Role\DashboardGlobalRole; final class DashboardPermissionsResponseDto { public function __construct( public ?DashboardGlobalRole $globalRole = null, public bool $hasViewerRole = false, public bool $hasCreatorRole = false, public bool $hasAdminRole = false, ) { } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/User/Application/UseCase/FindUsers/FindUsersPresenterInterface.php
centreon/src/Core/User/Application/UseCase/FindUsers/FindUsersPresenterInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\User\Application\UseCase\FindUsers; use Core\Application\Common\UseCase\ResponseStatusInterface; interface FindUsersPresenterInterface { public function presentResponse(FindUsersResponse|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/User/Application/UseCase/FindUsers/TinyUserDto.php
centreon/src/Core/User/Application/UseCase/FindUsers/TinyUserDto.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\User\Application\UseCase\FindUsers; final class TinyUserDto { public int $id = 0; public string $alias = ''; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/User/Application/UseCase/FindUsers/FindUsersResponse.php
centreon/src/Core/User/Application/UseCase/FindUsers/FindUsersResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\User\Application\UseCase\FindUsers; final class FindUsersResponse { /** @var TinyUserDto[]|UserDto[] */ public array $users = []; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/User/Application/UseCase/FindUsers/FindUsers.php
centreon/src/Core/User/Application/UseCase/FindUsers/FindUsers.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\User\Application\UseCase\FindUsers; use Centreon\Domain\Contact\Contact; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Log\LoggerTrait; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Centreon\Infrastructure\RequestParameters\RequestParametersTranslatorException; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\ForbiddenResponse; use Core\Contact\Domain\AdminResolver; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\Security\AccessGroup\Domain\Model\AccessGroup; use Core\User\Application\Exception\UserException; use Core\User\Application\Repository\ReadUserRepositoryInterface; use Core\User\Domain\Model\User; final class FindUsers { use LoggerTrait; public function __construct( private readonly ReadUserRepositoryInterface $readUserRepository, private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository, private readonly ContactInterface $user, private readonly RequestParametersInterface $requestParameters, private readonly bool $isCloudPlatform, private readonly AdminResolver $adminResolver, ) { } /** * @param FindUsersPresenterInterface $presenter */ public function __invoke(FindUsersPresenterInterface $presenter): void { try { $hasAccessToAllUsers = $this->adminResolver->isAdmin($this->user); if ($hasAccessToAllUsers) { $users = $this->readUserRepository->findAllByRequestParameters($this->requestParameters); } else { $accessGroups = $this->readAccessGroupRepository->findByContact($this->user); $accessGroupNames = array_map( fn (AccessGroup $accessGroup): string => $accessGroup->getName(), $accessGroups, ); if ( ! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_CONTACTS_READ) && ! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_CONTACTS_READ_WRITE) && ! ($this->isCloudPlatform && in_array('customer_editor_acl', $accessGroupNames, true)) ) { $this->error("User doesn't have sufficient rights to list users/contacts", [ 'status' => 'failure', 'initiator_user' => $this->user->getAlias(), ]); $presenter->presentResponse( new ForbiddenResponse(UserException::accessNotAllowed()) ); return; } $users = $this->readUserRepository->findByAccessGroupsUserAndRequestParameters( $accessGroups, $this->user, $this->requestParameters ); } if ($this->isCloudPlatform) { // Filter out service users in cloud platform $users = array_filter( $users, fn (User $user): bool => ! $user->isServiceAccount() ); } $this->info('Users listing succeeded', [ 'status' => 'success', 'initiator_user' => $this->user->getAlias(), ]); $presenter->presentResponse($this->createResponse($users, $hasAccessToAllUsers)); } catch (RequestParametersTranslatorException $ex) { $presenter->presentResponse(new ErrorResponse($ex->getMessage())); $this->error('User listing failed : ' . $ex->getMessage(), [ 'status' => 'failure', 'initiator_user' => $this->user->getAlias(), ]); } catch (\Throwable $ex) { $presenter->presentResponse( new ErrorResponse(UserException::errorWhileSearching($ex)) ); $this->error('User listing failed : ' . $ex->getMessage(), [ 'status' => 'failure', 'initiator_user' => $this->user->getAlias(), ]); } } /** * @param User[] $users * @param bool $hasAccessToAllUsers * * @return FindUsersResponse */ public function createResponse(array $users, bool $hasAccessToAllUsers): FindUsersResponse { $response = new FindUsersResponse(); foreach ($users as $user) { if (! $hasAccessToAllUsers) { $dto = new TinyUserDto(); $dto->id = $user->getId(); $dto->alias = $user->getAlias(); $response->users[] = $dto; continue; } $dto = new UserDto(); $dto->id = $user->getId(); $dto->alias = $user->getAlias(); $dto->name = $user->getName(); $dto->email = $user->getEmail(); $dto->isAdmin = $user->isAdmin(); $response->users[] = $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/User/Application/UseCase/FindUsers/UserDto.php
centreon/src/Core/User/Application/UseCase/FindUsers/UserDto.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\User\Application\UseCase\FindUsers; final class UserDto { public int $id = 0; public string $alias = ''; public string $name = ''; public string $email = ''; public bool $isAdmin = false; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/User/Application/UseCase/FindUserPermissions/FindUserPermissions.php
centreon/src/Core/User/Application/UseCase/FindUserPermissions/FindUserPermissions.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\User\Application\UseCase\FindUserPermissions; use Centreon\Domain\Contact\Contact; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\Common\Domain\NotEmptyString; use Core\User\Domain\Model\Permission; final class FindUserPermissions { /** @var array<string, string> */ private array $permissions = [ 'top_counter' => Contact::ROLE_DISPLAY_TOP_COUNTER, 'poller_statistics' => Contact::ROLE_DISPLAY_TOP_COUNTER_POLLERS_STATISTICS, 'configuration_host_group_write' => Contact::ROLE_CONFIGURATION_HOSTS_HOST_GROUPS_READ_WRITE, ]; public function __invoke(ContactInterface $user): FindUserPermissionsResponse|ResponseStatusInterface { return new FindUserPermissionsResponse($this->createPermissionsToReturn($user)); } /** * @param ContactInterface $user * * @return Permission[] */ private function createPermissionsToReturn(ContactInterface $user): array { $permissions = []; foreach ($this->permissions as $permissionName => $role) { if ($user->isAdmin() || $user->hasRole($role) || $user->hasTopologyRole($role)) { $permissions[] = new Permission(new NotEmptyString($permissionName), true); } } return $permissions; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/User/Application/UseCase/FindUserPermissions/FindUserPermissionsResponse.php
centreon/src/Core/User/Application/UseCase/FindUserPermissions/FindUserPermissionsResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\User\Application\UseCase\FindUserPermissions; use Core\Application\Common\UseCase\StandardResponseInterface; use Core\User\Domain\Model\Permission; final readonly class FindUserPermissionsResponse implements StandardResponseInterface { /** * @param Permission[] $permissions */ public function __construct(public readonly array $permissions) { } public function getData(): self { 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/User/Application/Exception/UserException.php
centreon/src/Core/User/Application/Exception/UserException.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\User\Application\Exception; class UserException extends \Exception { /** * @param \Throwable $ex * * @return self */ public static function errorWhileSearchingForUser(\Throwable $ex): self { return new self( _('Error while searching for the user'), 0, $ex ); } /** * @return self */ public static function accessNotAllowed(): self { return new self(_('You are not allowed to access users')); } /** * @param \Throwable $ex * * @return self */ public static function errorWhileSearching(\Throwable $ex): self { return new self(_('Error while searching for users'), 0, $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/User/Application/Repository/ReadUserRepositoryInterface.php
centreon/src/Core/User/Application/Repository/ReadUserRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\User\Application\Repository; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Core\Security\AccessGroup\Domain\Model\AccessGroup; use Core\User\Domain\Model\User; interface ReadUserRepositoryInterface { /** * Find configured users. * * @param RequestParametersInterface $requestParameters * * @throws \Throwable * * @return User[] */ public function findAllByRequestParameters(RequestParametersInterface $requestParameters): array; /** * Finds all users that the contact can see based on contacts and contact groups * defined in ACL groups filtered by access groups. * As well as all the users in the contact groups to which he belongs. * * @param AccessGroup[] $accessGroups * @param ContactInterface $user * @param RequestParametersInterface|null $requestParameters * * @throws \Throwable * * @return User[] */ public function findByAccessGroupsUserAndRequestParameters( array $accessGroups, ContactInterface $user, ?RequestParametersInterface $requestParameters, ): array; /** * Find a user by its ID. * * @param int $userId * * @throws \Throwable */ public function find(int $userId): ?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/User/Domain/Model/User.php
centreon/src/Core/User/Domain/Model/User.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\User\Domain\Model; use Centreon\Domain\Common\Assertion\Assertion; use Core\Contact\Domain\Model\ContactTemplate; class User { public const MIN_ALIAS_LENGTH = 1; public const MAX_ALIAS_LENGTH = 255; public const MIN_NAME_LENGTH = 1; public const MAX_NAME_LENGTH = 255; public const MIN_EMAIL_LENGTH = 1; public const MAX_EMAIL_LENGTH = 255; public const MIN_THEME_LENGTH = 1; public const MAX_THEME_LENGTH = 100; public const THEME_LIGHT = 'light'; public const THEME_DARK = 'dark'; public const USER_INTERFACE_DENSITY_EXTENDED = 'extended'; public const USER_INTERFACE_DENSITY_COMPACT = 'compact'; /** @var bool */ protected bool $isActivate = true; /** @var ContactTemplate|null */ protected ?ContactTemplate $contactTemplate = null; /** * @param int $id * @param string $alias * @param string $name * @param string $email * @param bool $isAdmin * @param string $theme * @param string $userInterfaceDensity * @param bool $canReachFrontend * @param bool $isServiceAccount * * @throws \Assert\AssertionFailedException */ public function __construct( private int $id, protected string $alias, protected string $name, protected string $email, protected bool $isAdmin, protected string $theme, protected string $userInterfaceDensity, protected bool $canReachFrontend, protected bool $isServiceAccount = false, ) { Assertion::positiveInt($this->id, 'User::id'); $this->setAlias($alias); $this->setName($name); $this->setEmail($email); $this->setTheme($theme); $this->setUserInterfaceDensity($userInterfaceDensity); $this->setCanReachFrontend($canReachFrontend); } /** * @return int */ public function getId(): int { return $this->id; } /** * @return string */ public function getAlias(): string { return $this->alias; } /** * @param string $alias * * @throws \Assert\AssertionFailedException * * @return self */ public function setAlias(string $alias): self { Assertion::minLength($alias, self::MIN_ALIAS_LENGTH, 'User::alias'); Assertion::maxLength($alias, self::MAX_ALIAS_LENGTH, 'User::alias'); $this->alias = $alias; return $this; } /** * @return string */ public function getName(): string { return $this->name; } /** * @param string $name * * @throws \Assert\AssertionFailedException * * @return self */ public function setName(string $name): self { Assertion::minLength($name, self::MIN_ALIAS_LENGTH, 'User::name'); Assertion::maxLength($name, self::MAX_ALIAS_LENGTH, 'User::name'); $this->name = $name; return $this; } /** * @return string */ public function getEmail(): string { return $this->email; } /** * @param string $email * * @throws \Assert\AssertionFailedException * * @return self */ public function setEmail(string $email): self { // Email format validation cannot be done here until legacy form does not check it Assertion::minLength($email, self::MIN_EMAIL_LENGTH, 'User::email'); Assertion::maxLength($email, self::MAX_EMAIL_LENGTH, 'User::email'); $this->email = $email; return $this; } /** * @return bool */ public function isAdmin(): bool { return $this->isAdmin; } /** * @param bool $isAdmin * * @return self */ public function setAdmin(bool $isAdmin): self { $this->isAdmin = $isAdmin; return $this; } /** * @return string */ public function getTheme(): string { return $this->theme; } /** * @param string $theme * * @throws \Assert\AssertionFailedException * * @return self */ public function setTheme(string $theme): self { Assertion::minLength($theme, self::MIN_THEME_LENGTH, 'User::theme'); Assertion::maxLength($theme, self::MAX_THEME_LENGTH, 'User::theme'); $this->theme = $theme; return $this; } /** * @return ContactTemplate|null */ public function getContactTemplate(): ?ContactTemplate { return $this->contactTemplate; } /** * @param ContactTemplate|null $contactTemplate * * @return self */ public function setContactTemplate(?ContactTemplate $contactTemplate): self { $this->contactTemplate = $contactTemplate; return $this; } /** * @return bool */ public function isActivate(): bool { return $this->isActivate; } /** * @param bool $isActivate * * @return self */ public function setActivate(bool $isActivate): self { $this->isActivate = $isActivate; return $this; } /** * @return string */ public function getUserInterfaceDensity(): string { return $this->userInterfaceDensity; } /** * @param string $userInterfaceDensity * * @throws \Assert\AssertionFailedException * @throws \InvalidArgumentException * * @return self */ public function setUserInterfaceDensity(string $userInterfaceDensity): self { if ( $userInterfaceDensity !== self::USER_INTERFACE_DENSITY_EXTENDED && $userInterfaceDensity !== self::USER_INTERFACE_DENSITY_COMPACT ) { throw new \InvalidArgumentException('User interface view mode provided not handled'); } $this->userInterfaceDensity = $userInterfaceDensity; return $this; } /** * @return bool */ public function canReachFrontend(): bool { return $this->canReachFrontend; } /** * @param bool $canReachFrontend * * @return self */ public function setCanReachFrontend(bool $canReachFrontend): self { $this->canReachFrontend = $canReachFrontend; return $this; } public function isServiceAccount(): bool { return $this->isServiceAccount; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/User/Domain/Model/UserInterfaceDensity.php
centreon/src/Core/User/Domain/Model/UserInterfaceDensity.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\User\Domain\Model; enum UserInterfaceDensity { case Compact; case Extended; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/User/Domain/Model/UserTheme.php
centreon/src/Core/User/Domain/Model/UserTheme.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\User\Domain\Model; enum UserTheme { case Light; case Dark; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/User/Domain/Model/Permission.php
centreon/src/Core/User/Domain/Model/Permission.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\User\Domain\Model; use Core\Common\Domain\NotEmptyString; readonly class Permission { public function __construct(private NotEmptyString $name, private bool $isActive) { } public function getName(): NotEmptyString { return $this->name; } public function isActive(): bool { return $this->isActive; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/User/Infrastructure/Model/UserInterfaceDensityConverter.php
centreon/src/Core/User/Infrastructure/Model/UserInterfaceDensityConverter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\User\Infrastructure\Model; use Core\User\Domain\Model\UserInterfaceDensity; final class UserInterfaceDensityConverter { public static function toString(UserInterfaceDensity $density): string { return match ($density) { UserInterfaceDensity::Compact => 'compact', UserInterfaceDensity::Extended => 'extended', }; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/User/Infrastructure/Model/UserThemeConverter.php
centreon/src/Core/User/Infrastructure/Model/UserThemeConverter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\User\Infrastructure\Model; use Core\User\Domain\Model\UserTheme; final class UserThemeConverter { public static function toString(UserTheme $theme): string { return match ($theme) { UserTheme::Light => 'light', UserTheme::Dark => 'dark', }; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/User/Infrastructure/Repository/DbReadUserRepository.php
centreon/src/Core/User/Infrastructure/Repository/DbReadUserRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\User\Infrastructure\Repository; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Log\LoggerTrait; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Centreon\Domain\RequestParameters\RequestParameters; use Centreon\Infrastructure\DatabaseConnection; use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator; use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB; use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait; use Core\Security\AccessGroup\Domain\Model\AccessGroup; use Core\User\Application\Repository\ReadUserRepositoryInterface; use Core\User\Domain\Model\User; use Utility\SqlConcatenator; /** * @phpstan-type _UserRecord array{ * contact_id: int|string, * contact_alias: string, * contact_name: string, * contact_email: string, * contact_admin: string, * contact_theme: string, * user_interface_density: string, * user_can_reach_frontend: string, * is_service_account: int, * } */ class DbReadUserRepository extends AbstractRepositoryRDB implements ReadUserRepositoryInterface { use LoggerTrait; use SqlMultipleBindTrait; public function __construct(DatabaseConnection $db) { $this->db = $db; } /** * @inheritDoc */ public function findAllByRequestParameters(RequestParametersInterface $requestParameters): array { $concatenator = new SqlConcatenator(); $concatenator->defineSelect( <<<'SQL_WRAP' SELECT DISTINCT SQL_CALC_FOUND_ROWS contact_id, contact_alias, contact_name, contact_email, contact_admin, contact_theme, user_interface_density, is_service_account, contact_oreon AS `user_can_reach_frontend` FROM `:db`.contact SQL_WRAP ); $concatenator->defineWhere( <<<'SQL' WHERE contact.contact_register = '1' SQL ); // Update the SQL string builder with the RequestParameters through SqlRequestParametersTranslator $sqlTranslator = new SqlRequestParametersTranslator($requestParameters); $sqlTranslator->setConcordanceArray([ 'id' => 'contact_id', 'alias' => 'contact_alias', 'name' => 'contact_name', 'email' => 'contact_email', 'provider_name' => 'contact_auth_type', 'is_admin' => 'contact_admin', ]); $sqlTranslator->translateForConcatenator($concatenator); // Prepare SQL + bind values $statement = $this->db->prepare($this->translateDbName($concatenator->concatAll())); $sqlTranslator->bindSearchValues($statement); $concatenator->bindValuesToStatement($statement); $statement->setFetchMode(\PDO::FETCH_ASSOC); $statement->execute(); // Calculate the number of rows for the pagination. $sqlTranslator->calculateNumberOfRows($this->db); $users = []; foreach ($statement as $result) { /** @var _UserRecord $result */ $users[] = $this->createFromRecord($result); } return $users; } /** * @inheritDoc */ public function findByAccessGroupsUserAndRequestParameters( array $accessGroups, ContactInterface $user, ?RequestParametersInterface $requestParameters = null, ): array { if ($accessGroups === []) { return []; } $accessGroupIds = array_map( static fn (AccessGroup $accessGroup): int => $accessGroup->getId(), $accessGroups ); [$binValues, $subRequest] = $this->createMultipleBindQuery($accessGroupIds, ':id_'); $request = <<<SQL SELECT SQL_CALC_FOUND_ROWS * FROM ( SELECT /* Finds associated users in ACL group rules */ contact.contact_id, contact.contact_alias, contact.contact_name, contact.contact_email, contact.contact_admin, contact.contact_theme, contact.user_interface_density, contact.contact_oreon AS `user_can_reach_frontend`, contact.is_service_account FROM `:db`.`contact` INNER JOIN `:db`.`acl_group_contacts_relations` acl_c_rel ON acl_c_rel.contact_contact_id = contact.contact_id WHERE contact.contact_register = '1' AND acl_c_rel.acl_group_id IN ({$subRequest}) UNION SELECT /* Finds users belonging to associated contact groups in ACL group rules */ contact.contact_id, contact.contact_alias, contact.contact_name, contact.contact_email, contact.contact_admin, contact.contact_theme, contact.user_interface_density, contact.contact_oreon AS `user_can_reach_frontend`, contact.is_service_account FROM `:db`.`contact` INNER JOIN `:db`.`contactgroup_contact_relation` c_cg_rel ON c_cg_rel.contact_contact_id = contact.contact_id INNER JOIN `:db`.`acl_group_contactgroups_relations` acl_cg_rel ON acl_cg_rel.cg_cg_id = c_cg_rel.contactgroup_cg_id WHERE contact.contact_register = '1' AND acl_cg_rel.acl_group_id IN ({$subRequest}) UNION SELECT /* Finds users belonging to the same contact groups as the user */ contact2.contact_id, contact2.contact_alias, contact2.contact_name, contact2.contact_email, contact2.contact_admin, contact2.contact_theme, contact2.user_interface_density, contact2.contact_oreon AS `user_can_reach_frontend`, contact.is_service_account FROM `:db`.`contact` INNER JOIN `:db`.`contactgroup_contact_relation` c_cg_rel ON c_cg_rel.contact_contact_id = contact.contact_id INNER JOIN `:db`.`contactgroup_contact_relation` c_cg_rel2 ON c_cg_rel2.contactgroup_cg_id = c_cg_rel.contactgroup_cg_id INNER JOIN `:db`.`contact` contact2 ON contact2.contact_id = c_cg_rel2.contact_contact_id WHERE c_cg_rel.contact_contact_id = :user_id AND contact.contact_register = '1' AND contact2.contact_register = '1' GROUP BY contact2.contact_id ) as contact SQL; // Update the SQL query with the RequestParameters through SqlRequestParametersTranslator $sqlTranslator = $requestParameters ? new SqlRequestParametersTranslator($requestParameters) : null; $sqlTranslator?->getRequestParameters()->setConcordanceStrictMode(RequestParameters::CONCORDANCE_MODE_STRICT); $sqlTranslator?->setConcordanceArray([ 'id' => 'contact_id', 'alias' => 'contact_alias', 'name' => 'contact_name', 'email' => 'contact_email', 'provider_name' => 'contact_auth_type', 'is_admin' => 'contact_admin', ]); // handle search $request .= $sqlTranslator?->translateSearchParameterToSql(); // handle sort $request .= $sqlTranslator?->translateSortParameterToSql() ?? ' ORDER BY contact_id ASC'; // handle pagination $request .= $sqlTranslator?->translatePaginationToSql(); $statement = $this->db->prepare($this->translateDbName($request)); $statement->bindValue(':user_id', $user->getId(), \PDO::PARAM_INT); foreach ($binValues as $key => $value) { $statement->bindValue($key, $value, \PDO::PARAM_INT); } if ($sqlTranslator !== null) { foreach ($sqlTranslator->getSearchValues() as $key => $data) { $type = (int) key($data); $value = $data[$type]; $statement->bindValue($key, $value, $type); } } $statement->execute(); $statement->setFetchMode(\PDO::FETCH_ASSOC); // Calculate the number of rows for the pagination. if ($total = $this->calculateNumberOfRows()) { $requestParameters?->setTotal($total); } $users = []; foreach ($statement as $result) { /** @var _UserRecord $result */ $users[] = $this->createFromRecord($result); } return $users; } /** * @inheritDoc */ public function find(int $userId): ?User { $statement = $this->db->prepare($this->translateDbName( <<<'SQL' SELECT contact_id, contact_alias, contact_name, contact_email, contact_admin, contact_theme, user_interface_density, contact_oreon AS `user_can_reach_frontend`, is_service_account FROM `:db`.contact WHERE contact.contact_register = '1' AND contact_id = :userId SQL )); $statement->bindValue(':userId', $userId, \PDO::PARAM_INT); $statement->execute(); /** @var false|_UserRecord $result */ $result = $statement->fetch(\PDO::FETCH_ASSOC); if ($result === false) { return null; } return $this->createFromRecord($result); } /** * @param _UserRecord $user * * @throws \Assert\AssertionFailedException * * @return User */ private function createFromRecord(array $user): User { return new User( id: (int) $user['contact_id'], alias: $user['contact_alias'], name: $user['contact_name'], email: $user['contact_email'], isAdmin: $user['contact_admin'] === '1', theme: $user['contact_theme'], userInterfaceDensity: $user['user_interface_density'], canReachFrontend: $user['user_can_reach_frontend'] === '1', isServiceAccount: (bool) $user['is_service_account'] ?: false ); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/User/Infrastructure/API/FindCurrentUserParameters/FindCurrentUserParametersPresenter.php
centreon/src/Core/User/Infrastructure/API/FindCurrentUserParameters/FindCurrentUserParametersPresenter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\User\Infrastructure\API\FindCurrentUserParameters; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\Dashboard\Infrastructure\Model\DashboardGlobalRoleConverter; use Core\Infrastructure\Common\Api\DefaultPresenter; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\User\Application\UseCase\FindCurrentUserParameters\FindCurrentUserParametersPresenterInterface; use Core\User\Application\UseCase\FindCurrentUserParameters\FindCurrentUserParametersResponse; use Core\User\Infrastructure\Model\UserInterfaceDensityConverter; use Core\User\Infrastructure\Model\UserThemeConverter; class FindCurrentUserParametersPresenter extends DefaultPresenter implements FindCurrentUserParametersPresenterInterface { public function __construct( PresenterFormatterInterface $presenterFormatter, ) { parent::__construct($presenterFormatter); } public function presentResponse(ResponseStatusInterface|FindCurrentUserParametersResponse $data): void { if ($data instanceof FindCurrentUserParametersResponse) { $array = [ 'id' => $data->id, 'name' => $data->name, 'alias' => $data->alias, 'email' => $data->email, 'timezone' => $data->timezone, 'locale' => $data->locale, 'is_admin' => $data->isAdmin, 'use_deprecated_pages' => $data->useDeprecatedPages, 'use_deprecated_custom_views' => $data->useDeprecatedCustomViews, 'is_export_button_enabled' => $data->isExportButtonEnabled, 'can_manage_api_tokens' => $data->canManageApiTokens, 'theme' => UserThemeConverter::toString($data->theme), 'user_interface_density' => UserInterfaceDensityConverter::toString($data->userInterfaceDensity), 'default_page' => $data->defaultPage, ]; $array['dashboard'] = $data->dashboardPermissions->globalRole ? [ 'global_user_role' => DashboardGlobalRoleConverter::toString( $data->dashboardPermissions->globalRole ), 'view_dashboards' => $data->dashboardPermissions->hasViewerRole, 'create_dashboards' => $data->dashboardPermissions->hasCreatorRole, 'administrate_dashboards' => $data->dashboardPermissions->hasAdminRole, ] : null; $this->present($array); } else { $this->setResponseStatus($data); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/User/Infrastructure/API/FindCurrentUserParameters/FindCurrentUserParametersController.php
centreon/src/Core/User/Infrastructure/API/FindCurrentUserParameters/FindCurrentUserParametersController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\User\Infrastructure\API\FindCurrentUserParameters; use Centreon\Application\Controller\AbstractController; use Core\User\Application\UseCase\FindCurrentUserParameters\FindCurrentUserParameters; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Exception\AccessDeniedException; final class FindCurrentUserParametersController extends AbstractController { /** * @param FindCurrentUserParameters $useCase * @param FindCurrentUserParametersPresenter $presenter * * @throws AccessDeniedException * * @return Response */ public function __invoke( FindCurrentUserParameters $useCase, FindCurrentUserParametersPresenter $presenter, ): Response { $this->denyAccessUnlessGrantedForApiConfiguration(); $useCase($presenter); return $presenter->show(); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/User/Infrastructure/API/FindUsers/FindUsersPresenter.php
centreon/src/Core/User/Infrastructure/API/FindUsers/FindUsersPresenter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\User\Infrastructure\API\FindUsers; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\User\Application\UseCase\FindUsers\FindUsersPresenterInterface; use Core\User\Application\UseCase\FindUsers\FindUsersResponse; use Core\User\Application\UseCase\FindUsers\TinyUserDto; class FindUsersPresenter extends AbstractPresenter implements FindUsersPresenterInterface { public function __construct( private readonly RequestParametersInterface $requestParameters, protected PresenterFormatterInterface $presenterFormatter, ) { parent::__construct($presenterFormatter); } /** * @inheritDoc */ public function presentResponse(ResponseStatusInterface|FindUsersResponse $response): void { if ($response instanceof ResponseStatusInterface) { $this->setResponseStatus($response); } else { $result = []; foreach ($response->users as $dto) { if ($dto instanceof TinyUserDto) { $result[] = [ 'id' => $dto->id, 'alias' => $dto->alias, ]; continue; } $result[] = [ 'id' => $dto->id, 'name' => $dto->name, 'alias' => $dto->alias, 'email' => $dto->email, 'is_admin' => $dto->isAdmin, ]; } $this->present([ 'result' => $result, 'meta' => $this->requestParameters->toArray(), ]); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/User/Infrastructure/API/FindUsers/FindUsersController.php
centreon/src/Core/User/Infrastructure/API/FindUsers/FindUsersController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\User\Infrastructure\API\FindUsers; use Centreon\Application\Controller\AbstractController; use Core\User\Application\UseCase\FindUsers\FindUsers; use Symfony\Component\HttpFoundation\Response; final class FindUsersController extends AbstractController { public function __invoke( FindUsers $useCase, FindUsersPresenter $presenter, ): Response { $this->denyAccessUnlessGrantedForApiConfiguration(); $useCase($presenter); return $presenter->show(); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/User/Infrastructure/API/FindUserPermissions/PermissionNormalizer.php
centreon/src/Core/User/Infrastructure/API/FindUserPermissions/PermissionNormalizer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\User\Infrastructure\API\FindUserPermissions; use Core\User\Domain\Model\Permission; use Symfony\Component\DependencyInjection\Attribute\Autowire; use Symfony\Component\Serializer\Exception\ExceptionInterface; use Symfony\Component\Serializer\Normalizer\NormalizerInterface; final readonly class PermissionNormalizer implements NormalizerInterface { public function __construct( #[Autowire(service: 'serializer.normalizer.object')] private readonly NormalizerInterface $normalizer, ) { } /** * @param mixed $object * @param string|null $format * @param array<string, mixed> $context * * @throws ExceptionInterface * @return array<string, mixed> */ public function normalize( mixed $object, ?string $format = null, array $context = [], ): array { $data = $this->normalizer->normalize($object, $format, $context); if (! isset($data['name'], $data['is_active'])) { throw new \InvalidArgumentException('Normalized data missing, required fields: name, is_active'); } return [$data['name'] => $data['is_active']]; } /** * @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 Permission; } /** * @param ?string $format * @return array<class-string|'*'|'object'|string, bool|null> */ public function getSupportedTypes(?string $format): array { return [ Permission::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/User/Infrastructure/API/FindUserPermissions/FindUserPermissionsResponseNormalizer.php
centreon/src/Core/User/Infrastructure/API/FindUserPermissions/FindUserPermissionsResponseNormalizer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\User\Infrastructure\API\FindUserPermissions; use Core\User\Application\UseCase\FindUserPermissions\FindUserPermissionsResponse; use Symfony\Component\DependencyInjection\Attribute\Autowire; use Symfony\Component\Serializer\Exception\ExceptionInterface; use Symfony\Component\Serializer\Normalizer\NormalizerInterface; final readonly class FindUserPermissionsResponseNormalizer implements NormalizerInterface { public function __construct( #[Autowire(service: 'serializer.normalizer.object')] private readonly NormalizerInterface $normalizer, ) { } /** * @param mixed $object * @param string|null $format * @param array<string, mixed> $context * * @throws ExceptionInterface * @return array<string, mixed> */ public function normalize( mixed $object, ?string $format = null, array $context = [], ): array { $data = $this->normalizer->normalize($object, $format, $context); $normalizedData = []; if (! isset($data['permissions'])) { throw new \InvalidArgumentException('Normalized data missing, required fields: permissions'); } if (is_iterable($data['permissions'])) { foreach ($data['permissions'] as $permission) { $name = key($permission); $normalizedData[$name] = $permission[$name]; } } return $normalizedData; } /** * @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 FindUserPermissionsResponse; } /** * @param ?string $format * @return array<class-string|'*'|'object'|string, bool|null> */ public function getSupportedTypes(?string $format): array { return [ FindUserPermissionsResponse::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/User/Infrastructure/API/FindUserPermissions/FindUserPermissionsController.php
centreon/src/Core/User/Infrastructure/API/FindUserPermissions/FindUserPermissionsController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\User\Infrastructure\API\FindUserPermissions; use Centreon\Application\Controller\AbstractController; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\Infrastructure\Common\Api\StandardPresenter; use Core\User\Application\UseCase\FindUserPermissions\FindUserPermissions; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Serializer\Exception\ExceptionInterface; final class FindUserPermissionsController extends AbstractController { /** * @param StandardPresenter $presenter * @param FindUserPermissions $useCase * @param ContactInterface $user * * @throws ExceptionInterface * @return Response */ public function __invoke( StandardPresenter $presenter, FindUserPermissions $useCase, ContactInterface $user, ): Response { $response = $useCase($user); if ($response instanceof ResponseStatusInterface) { return $this->createResponse($response); } return JsonResponse::fromJsonString( $presenter->present($response, ['groups' => ['FindUserPermissions:Read', 'NotEmptyString: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/Common/Application/FeatureFlagsInterface.php
centreon/src/Core/Common/Application/FeatureFlagsInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Application; /** * This class is a facade to the feature flag system which consists in a simple JSON file saved in this project. * * This feature flags system is static by purpose. * * Each value is a flags bitmask depending on the current platform (On-Prem / Cloud). */ interface FeatureFlagsInterface { /** * Simple public exposition of the internal flag. * * @return bool */ public function isCloudPlatform(): bool; /** * Return all configured flags with their value. * * @return array<string, bool> */ public function getAll(): 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/Common/Application/UseCase/VaultTrait.php
centreon/src/Core/Common/Application/UseCase/VaultTrait.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Application\UseCase; use Core\Security\Vault\Domain\Model\VaultConfiguration; trait VaultTrait { private ?string $uuid = null; /** * Parse the vault path and find the UUID. * * example: * Given $value = 'secret::vault_name::path/to/secret/xxxxxxx-xx-xxx-xxxxx::vault_key' * Then 'xxxxxxx-xx-xxx-xxxxx' will be extracted. * * @param string $value * * @return string|null */ private function getUuidFromPath(string $value): ?string { if ( preg_match( '/' . VaultConfiguration::UUID_EXTRACTION_REGEX . '/', $value, $matches ) ) { return $matches[2]; } return null; } private function isAVaultPath(string $value): bool { return str_starts_with($value, VaultConfiguration::VAULT_PATH_PATTERN); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Common/Application/Type/NoValue.php
centreon/src/Core/Common/Application/Type/NoValue.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Application\Type; /** * This class is used as a dedicated type for the meaning of "no value". * * You absolutely need it when the `null` type has a meaning from an application point of view. * * <pre> * // Example DTO * class MyDto { * public function __construct( * public NoValue|null|int $number = new NoValue() * ) * {} * } * * // Classical coalesce with null as we use to encounter * $value = $dto->number ?? $defaultValue; * * // Replaced with the NoValue behaviour * $value = NoValue::coalesce($dto->number, $defaultValue); * * </pre> */ final class NoValue { /** * This method is here to mimic the null coalescing operator of php `??` but with this object. * * @see https://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce * * @template T of int|bool|float|string|array|null * * @param self|T $value * @param T $default * * @return T */ public static function coalesce( self|null|int|bool|float|string|array $value, null|int|bool|float|string|array $default, ): null|int|bool|float|string|array { return $value instanceof self ? $default : $value; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Common/Application/Converter/YesNoDefaultConverter.php
centreon/src/Core/Common/Application/Converter/YesNoDefaultConverter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Application\Converter; use Core\Common\Domain\YesNoDefault; /** * This class purpose is to allow convertion from the legacy host event enum to a string. */ class YesNoDefaultConverter { private const CASE_NO = 0; private const CASE_YES = 1; private const CASE_DEFAULT = 2; /** * @param null|bool|int|string $value * * @return YesNoDefault */ public static function fromScalar(null|bool|int|string $value): YesNoDefault { return match ($value) { true, '1', self::CASE_YES, (string) self::CASE_YES => YesNoDefault::Yes, false, '0', self::CASE_NO, (string) self::CASE_NO => YesNoDefault::No, null, '2', self::CASE_DEFAULT, (string) self::CASE_DEFAULT => YesNoDefault::Default, default => throw new \ValueError("\"{$value}\" is not a valid backing value for enum YesNoDefault"), }; } /** * Convert a YesNoDefault into its corresponding integer * ex: YesNoDefault::Default => 2. * * @param YesNoDefault $enum * * @return int */ public static function toInt(YesNoDefault $enum): int { return match ($enum) { YesNoDefault::Yes => self::CASE_YES, YesNoDefault::No => self::CASE_NO, YesNoDefault::Default => self::CASE_DEFAULT, }; } /** * Convert a YesNoDefault into its corresponding string * ex: YesNoDefault::Default => '2'. * * @param YesNoDefault $enum * * @return string */ public static function toString(YesNoDefault $enum): string { return (string) self::toInt($enum); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Common/Application/Repository/ReadVaultRepositoryInterface.php
centreon/src/Core/Common/Application/Repository/ReadVaultRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Application\Repository; use Core\Security\Vault\Domain\Model\NewVaultConfiguration; use Core\Security\Vault\Domain\Model\VaultConfiguration; interface ReadVaultRepositoryInterface { public function isVaultConfigured(): bool; public function setCustomPath(string $customPath): void; /** * Get vault content from given path. * * @param string $path * * @throws \Throwable * * @return array<string,string> */ public function findFromPath(string $path): array; /** * Get Vault content from given paths. * * @param array<int, string> $paths list of paths to get indexed by resource ID * @return array<int, array<string,string>> vault content indexed by resource ID */ public function findFromPaths(array $paths): array; /** * Test a vault configuration validity. * * @param VaultConfiguration|NewVaultConfiguration $vaultConfiguration * * @return bool */ public function testVaultConnection(VaultConfiguration|NewVaultConfiguration $vaultConfiguration): 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/Common/Application/Repository/RepositoryManagerInterface.php
centreon/src/Core/Common/Application/Repository/RepositoryManagerInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Application\Repository; use Core\Common\Domain\Exception\RepositoryException; /** * Interface * * @class RepositoryManagerInterface * @package Core\Common\Application\Repository */ interface RepositoryManagerInterface { /** * Checks whether a transaction is currently active. * * @return bool TRUE if a transaction is currently active, FALSE otherwise */ public function isTransactionActive(): bool; /** * Opens a new transaction. This must be closed by calling one of the following methods: * {@see commitTransaction} or {@see rollBackTransaction} * * @throws RepositoryException * @return void */ public function startTransaction(): void; /** * To validate a transaction. * * @throws RepositoryException * @return bool */ public function commitTransaction(): bool; /** * To cancel a transaction. * * @throws RepositoryException * @return bool */ public function rollBackTransaction(): 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/Common/Application/Repository/ApiRepositoryInterface.php
centreon/src/Core/Common/Application/Repository/ApiRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Application\Repository; use Core\Proxy\Domain\Model\Proxy; interface ApiRepositoryInterface { /** * @param string $token */ public function setAuthenticationToken(string $token): void; /** * @param int $maxItemsByRequest Number of items that can be requested per call */ public function setMaxItemsByRequest(int $maxItemsByRequest): void; /** * @see Proxy::__toString() * * @param string $proxy String representation of proxy url */ public function setProxy(string $proxy): void; /** * Define API call timeout. * * @param int $timeout In seconds */ public function setTimeout(int $timeout): void; /** * @param string $url */ public function setUrl(string $url): 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/Common/Application/Repository/WriteVaultRepositoryInterface.php
centreon/src/Core/Common/Application/Repository/WriteVaultRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Application\Repository; interface WriteVaultRepositoryInterface { public function isVaultConfigured(): bool; public function setCustomPath(string $customPath): void; /** * Update or save secrets and return vault path. * * @param string|null $uuid * @param array<string, int|string> $inserts * @param array<string, int|string> $deletes * * @throws \Throwable * * @return array<string, string> array of paths */ public function upsert(?string $uuid = null, array $inserts = [], array $deletes = []): array; /** * Delete secrets. * * @param string $uuid * * @throws \Throwable */ public function delete(string $uuid): void; /** * Add a path to the list of available paths. * * @param string $path */ public function addAvailablePath(string $path): 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/Common/Domain/NotEmptyString.php
centreon/src/Core/Common/Domain/NotEmptyString.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Domain; class NotEmptyString { public readonly string $value; public function __construct(string|\Stringable $value) { $this->value = trim((string) $value); if ($this->value === '') { throw new \InvalidArgumentException('The string must not be empty'); } } public function __toString(): string { return $this->value; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Common/Domain/YesNoDefault.php
centreon/src/Core/Common/Domain/YesNoDefault.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Domain; /** * This enum is to be used to handle properties with only three accepted value : Yes, No and Default. */ enum YesNoDefault { case Yes; case No; case Default; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Common/Domain/Identifiable.php
centreon/src/Core/Common/Domain/Identifiable.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Domain; interface Identifiable { public function getId(): 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/Common/Domain/PlatformType.php
centreon/src/Core/Common/Domain/PlatformType.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Domain; final class PlatformType { public const CLOUD = 'cloud'; public const ON_PREM = 'on-premise'; public const AVAILABLE_TYPES = [self::CLOUD, self::ON_PREM]; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Common/Domain/PositiveInteger.php
centreon/src/Core/Common/Domain/PositiveInteger.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Domain; class PositiveInteger { /** * @param int $value Integer value >= 0 */ public function __construct(readonly private int $value) { if ($this->value <= 0) { throw new \InvalidArgumentException('The integer must be positive'); } } public function getValue(): int { return $this->value; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Common/Domain/Comparable.php
centreon/src/Core/Common/Domain/Comparable.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Domain; interface Comparable { /** * This method returns true if two objects are considered equal. * * @param object $object * * @return bool */ public function isEqual(object $object): bool; /** * Calculates a hash with the list of values used to validate equality between two objects. * * @return string */ public function getEqualityHash(): string; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Common/Domain/HostType.php
centreon/src/Core/Common/Domain/HostType.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Domain; /** * This enum is to be used to handle the different types of host. */ enum HostType: string { case Template = '0'; case Host = '1'; case Virtual = '2'; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Common/Domain/TrimmedString.php
centreon/src/Core/Common/Domain/TrimmedString.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Domain; /** * This object is *by purpose* a very simple ValueObject. * It forces the carried string to be explicitly trimmed. */ final class TrimmedString implements \Stringable { public readonly string $value; public function __construct(string|\Stringable $value) { $this->value = trim((string) $value); } public function __toString(): string { return $this->value; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Common/Domain/ResponseCodeEnum.php
centreon/src/Core/Common/Domain/ResponseCodeEnum.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Domain; enum ResponseCodeEnum { case OK; case NotFound; case Error; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Common/Domain/SimpleEntity.php
centreon/src/Core/Common/Domain/SimpleEntity.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Domain; use Assert\AssertionFailedException; use Centreon\Domain\Common\Assertion\Assertion; /** * This class contain the id and name of any object regardles of their other attributes. * It can be used as property of another object. */ class SimpleEntity { /** * @param int $id * @param TrimmedString|null $name * @param string $objectName * * @throws AssertionFailedException */ public function __construct( private readonly int $id, private readonly ?TrimmedString $name, string $objectName, ) { Assertion::positiveInt($id, "{$objectName}::id"); if ($name !== null) { Assertion::notEmptyString($name->value, "{$objectName}::name"); } } public function getId(): int { return $this->id; } public function getName(): ?string { return $this->name?->value; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Common/Domain/Collection/Collection.php
centreon/src/Core/Common/Domain/Collection/Collection.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Domain\Collection; use Core\Common\Domain\Exception\CollectionException; /** * Class * * @class Collection * @package Core\Common\Domain\Collection * @template TItem * @implements CollectionInterface<TItem> * @phpstan-consistent-constructor */ abstract class Collection implements CollectionInterface { /** @var array<string|int,TItem> */ protected array $items; /** * Collection constructor * * @param array<string|int,TItem> $items * * @throws CollectionException * * @example $collection = new Collection(['key1' => new Item(), 'key2' => new Item()]); * $collection = new Collection([0 => new Item(), 1 => new Item()]); * $collection = new Collection([0 => 'bar', 1 => 'foo']); * $collection = new Collection([0 => 4555, 1 => 9999]); */ final public function __construct(array $items = []) { foreach ($items as $item) { $this->validateItem($item); } $this->items = $items; } /** * @param array<string|int,TItem> $items * * @throws CollectionException * @return static * * @example $collection = Collection::create(['key1' => new Item(), 'key2' => new Item()]); * $collection = Collection::create([0 => new Item(), 1 => new Item()]); * $collection = Collection::create([0 => 'foo', 1 => 'bar']); * $collection = Collection::create([0 => 4555, 1 => 9999]); */ final public static function create(array $items): static { return new static($items); } /** * @return static */ public function clear(): static { $this->items = []; return $this; } /** * @param TItem $item * * @return bool */ public function contains($item): bool { return in_array($item, $this->items, true); } /** * @param int|string $key * * @throws CollectionException * @return TItem */ public function get(int|string $key): mixed { if (isset($this->items[$key])) { return $this->items[$key]; } throw new CollectionException("Key {$key} not found in the collection"); } /** * @param int|string $key * * @return bool */ public function has(int|string $key): bool { return isset($this->items[$key]); } /** * @return array<int|string> */ public function keys(): array { return array_keys($this->items); } /** * @return bool */ public function isEmpty(): bool { return $this->items === []; } /** * @return int */ public function length(): int { return count($this->items); } /** * @param TItem $item * * @throws CollectionException * @return int|string */ public function indexOf(mixed $item): int|string { $items = array_values($this->items); $position = array_search($item, $items, true); if ($position === false) { throw new CollectionException('Item not found in the collection'); } return $position; } /** * @param callable $callable * * @return true */ public function sortByValues(callable $callable): bool { return usort($this->items, $callable); } /** * @param callable $callable * * @return true */ public function sortByKeys(callable $callable): bool { return uksort($this->items, $callable); } /** * Filter the collection by a callable using the item as parameter * * @param callable $callable * * @throws CollectionException * @return static * * @example $collection = new Collection([1, 2, 3, 4, 5]); * $filteredCollection = $collection->filterValues(fn($item) => $item > 2); * // $filteredCollection = [3, 4, 5] */ public function filterOnValue(callable $callable): static { return new static(array_filter($this->items, $callable)); } /** * Filter the collection by a callable using the key as parameter * * @param callable $callable * * @throws CollectionException * @return static * * @example $collection = new Collection(['key1' => 'foo', 'key2' => 'bar']); * $filteredCollection = $collection->filterKeys(fn($key) => $key === 'key1'); * // $filteredCollection = ['key1' => 'foo'] */ public function filterOnKey(callable $callable): static { return new static(array_filter($this->items, $callable, ARRAY_FILTER_USE_KEY)); } /** * Filter the collection by a callable using the item and key as parameters * * @param callable $callable * * @throws CollectionException * @return static * * @example $collection = new Collection(['key1' => 'foo', 'key2' => 'bar']); * $filteredCollection = $collection->filterValueKey(fn($item, $key) => $key === 'key1' && $item === 'foo'); * // $filteredCollection = ['key1' => 'foo'] */ public function filterOnValueKey(callable $callable): static { return new static(array_filter($this->items, $callable, ARRAY_FILTER_USE_BOTH)); } /** * Merge collections with actual collection. Collections have to be of the same type as actual. * * @param CollectionInterface<TItem> ...$collections * * @throws CollectionException * @return static */ public function mergeWith(CollectionInterface ...$collections): static { $itemsBackup = $this->items; foreach ($collections as $collection) { if ($collection::class === static::class) { foreach ($collection->toArray() as $key => $item) { $this->put($key, $item); } } else { // if failure put the collection back in its original state $this->items = $itemsBackup; throw new CollectionException( sprintf('Collections to merge must be instances of %s, %s given', static::class, $collection::class) ); } } return $this; } /** * @return TItem[] */ public function toArray(): array { return $this->items; } /** * Add new item at the collection, if key exists then adding aborted * * @param int|string $key * @param TItem $item * * @throws CollectionException * @return static */ public function add(int|string $key, $item): static { if (isset($this->items[$key])) { throw new CollectionException("Key {$key} already used in this collection"); } $this->validateItem($item); $this->items[$key] = $item; return $this; } /** * @param int|string $key * @param TItem $item * * @throws CollectionException * @return static */ public function put(int|string $key, $item): static { $this->validateItem($item); $this->items[$key] = $item; return $this; } /** * @param int|string $key * * @return bool */ public function remove(int|string $key): bool { if ($this->has($key)) { unset($this->items[$key]); return true; } return false; } /** * @return TItem[] */ public function values(): array { return array_values($this->items); } /** * @return \Traversable<string|int,TItem> */ public function getIterator(): \Traversable { foreach ($this->items as $key => $item) { yield $key => $item; } } /** * @throws CollectionException * @return string */ public function toJson(): string { try { $json = json_encode($this->jsonSerialize(), JSON_THROW_ON_ERROR); } catch (\JsonException $exception) { throw new CollectionException( "Stringify the collection to json failed : {$exception->getMessage()}", [ 'serializedCollection' => $this->jsonSerialize(), 'json_last_error_message' => json_last_error_msg(), ], $exception ); } return $json; } /** * @return array<string,mixed> */ abstract public function jsonSerialize(): array; /** * @param TItem $item * * @throws CollectionException * @return void */ abstract protected function validateItem($item): 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/Common/Domain/Collection/CollectionInterface.php
centreon/src/Core/Common/Domain/Collection/CollectionInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Domain\Collection; use Core\Common\Domain\Exception\CollectionException; /** * Interface * * @class CollectionInterface * @package Core\Common\Domain\Collection * @template TItem * @extends \IteratorAggregate<string|int,TItem> */ interface CollectionInterface extends \IteratorAggregate, \JsonSerializable { /** * Return all items of collection * * @return TItem[] */ public function toArray(): array; /** * Delete all items of collection * * @return CollectionInterface<TItem> */ public function clear(): self; /** * @param TItem $item * * @return bool */ public function contains($item): bool; /** * @param int|string $key * * @throws CollectionException * @return TItem */ public function get(int|string $key): mixed; /** * @param int|string $key * * @return bool */ public function has(int|string $key): bool; /** * Return an array with the keys of collection * * @return array<int|string> */ public function keys(): array; /** * @return bool */ public function isEmpty(): bool; /** * Return the number of items of collection * * @return int */ public function length(): int; /** * @param TItem $item * * @throws CollectionException * @return int|string */ public function indexOf(mixed $item): int|string; /** * @param callable $callable * * @return true */ public function sortByValues(callable $callable): bool; /** * @param callable $callable * * @return true */ public function sortByKeys(callable $callable): bool; /** * Filter the collection by a callable using the item as parameter * * @param callable $callable * * @throws CollectionException * @return CollectionInterface<TItem> * * @example $collection = new Collection([1, 2, 3, 4, 5]); * $filteredCollection = $collection->filterValues(fn($item) => $item > 2); * // $filteredCollection = [3, 4, 5] */ public function filterOnValue(callable $callable): self; /** * Filter the collection by a callable using the key as parameter * * @param callable $callable * * @throws CollectionException * @return CollectionInterface<TItem> * * @example $collection = new Collection(['key1' => 'foo', 'key2' => 'bar']); * $filteredCollection = $collection->filterKeys(fn($key) => $key === 'key1'); * // $filteredCollection = ['key1' => 'foo'] */ public function filterOnKey(callable $callable): self; /** * Filter the collection by a callable using the item and key as parameters * * @param callable $callable * * @throws CollectionException * @return CollectionInterface<TItem> * * @example $collection = new Collection(['key1' => 'foo', 'key2' => 'bar']); * $filteredCollection = $collection->filterValueKey(fn($item, $key) => $key === 'key1' && $item === 'foo'); * // $filteredCollection = ['key1' => 'foo'] */ public function filterOnValueKey(callable $callable): self; /** * Merge collections with actual collection. Collections must to be the same of actual. * * @param CollectionInterface<TItem> ...$collections * * @throws CollectionException * @return CollectionInterface<TItem> */ public function mergeWith(self ...$collections): self; /** * @param int|string $key * @param TItem $item * * @throws CollectionException * @return CollectionInterface<TItem> */ public function add(int|string $key, mixed $item): self; /** * @param int|string $key * @param TItem $item * * @throws CollectionException * @return CollectionInterface<TItem> */ public function put(int|string $key, mixed $item): self; /** * @param int|string $key * * @return bool */ public function remove(int|string $key): bool; /** * Return an array of items of collection * * @return TItem[] */ public function values(): array; /** * @throws CollectionException * @return string */ public function toJson(): string; /** * @return \Traversable<string|int,TItem> */ public function getIterator(): \Traversable; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Common/Domain/Collection/LiteralStringCollection.php
centreon/src/Core/Common/Domain/Collection/LiteralStringCollection.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Domain\Collection; use Core\Common\Domain\ValueObject\LiteralString; /** * Class * * @class LiteralStringCollection * @package Core\Common\Domain\Collection * @extends ObjectCollection<LiteralString> */ class LiteralStringCollection extends ObjectCollection { /** * @return array<int|string,string> */ public function jsonSerialize(): array { return array_map(fn ($item) => $item->jsonSerialize(), $this->items); } /** * @return class-string<LiteralString> */ protected function itemClass(): string { return LiteralString::class; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Common/Domain/Collection/StringCollection.php
centreon/src/Core/Common/Domain/Collection/StringCollection.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Domain\Collection; use Core\Common\Domain\Exception\CollectionException; /** * Class * * @class StringCollection * @package Core\Common\Domain\Collection * @extends Collection<string> */ class StringCollection extends Collection { /** * @return array<int|string,string> */ public function jsonSerialize(): array { return $this->items; } /** * @param string $item * * @throws CollectionException * @return void */ protected function validateItem($item): void { if (! is_string($item)) { throw new CollectionException( sprintf('Item must be a string, %s given', gettype($item)) ); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Common/Domain/Collection/ObjectCollection.php
centreon/src/Core/Common/Domain/Collection/ObjectCollection.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Domain\Collection; use Core\Common\Domain\Exception\CollectionException; /** * Class * * @class ObjectCollection * @package Core\Common\Domain\Collection * @template TItem * @extends Collection<TItem> * @phpstan-consistent-constructor */ abstract class ObjectCollection extends Collection { /** * @throws CollectionException * @return array<int|string,mixed> */ public function jsonSerialize(): array { $serializedItems = []; foreach ($this->items as $key => $item) { $serializedItems[$key] = method_exists($item, 'jsonSerialize') ? $item->jsonSerialize() : get_object_vars($item); } return $serializedItems; } /** * @param TItem $item * * @throws CollectionException * @return void */ protected function validateItem($item): void { $class = $this->itemClass(); if (! $item instanceof $class) { throw new CollectionException( sprintf('Item must be an instance of %s, %s given', $class, $item::class) ); } } /** * Return the name of item class in the collection * * @return class-string<TItem> */ abstract protected function itemClass(): string; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Common/Domain/ValueObject/LiteralString.php
centreon/src/Core/Common/Domain/ValueObject/LiteralString.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Domain\ValueObject; use Core\Common\Domain\Exception\ValueObjectException; /** * Class * * @class LiteralString * @package Core\Common\Domain\ValueObject */ readonly class LiteralString implements ValueObjectInterface { /** * LiteralString constructor * * @param string $value */ public function __construct(protected string $value) { } /** * @return string */ public function __toString(): string { return $this->value; } /** * @return string */ public function getValue(): string { return $this->value; } /** * @return bool */ public function isEmpty(): bool { return empty($this->value); } /** * @return int */ public function length(): int { return mb_strlen($this->value); } /** * @return LiteralString */ public function toUpperCase(): self { return new static(mb_strtoupper($this->value)); } /** * @return LiteralString */ public function toLowerCase(): self { return new static(mb_strtolower($this->value)); } /** * @param string $needle * * @return bool */ public function contains(string $needle): bool { return str_contains($this->value, $needle); } /** * @param string $needle * * @return bool */ public function startsWith(string $needle): bool { return str_starts_with($this->value, $needle); } /** * @param string $needle * * @return bool */ public function endsWith(string $needle): bool { return str_ends_with($this->value, $needle); } /** * @param string $search * @param string $replace * * @return LiteralString */ public function replace(string $search, string $replace): self { return new static(str_replace($search, $replace, $this->value)); } /** * @return LiteralString */ public function trim(): self { return new static(trim($this->value)); } /** * @param string $value * * @return LiteralString */ public function append(string $value): self { return new static($this->value . $value); } /** * @param ValueObjectInterface $object * * @throws ValueObjectException * @return bool */ public function equals(ValueObjectInterface $object): bool { if (! $object instanceof static) { throw new ValueObjectException( 'Equal checking failed because not a ' . static::class . ', ' . $object::class . ' given', ); } return $this->value === $object->getValue(); } /** * @return string */ public function jsonSerialize(): string { return $this->value; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Common/Domain/ValueObject/ValueObjectInterface.php
centreon/src/Core/Common/Domain/ValueObject/ValueObjectInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Domain\ValueObject; use Core\Common\Domain\Exception\ValueObjectException; /** * Interface * * @class ValueObjectInterface * @package Core\Common\Domain\ValueObject */ interface ValueObjectInterface extends \JsonSerializable, \Stringable { /** * @param ValueObjectInterface $object * * @throws ValueObjectException * @return bool */ public function equals(self $object): 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/Common/Domain/ValueObject/Web/IpAddress.php
centreon/src/Core/Common/Domain/ValueObject/Web/IpAddress.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Domain\ValueObject\Web; use Core\Common\Domain\Exception\ValueObjectException; use Core\Common\Domain\ValueObject\LiteralString; /** * Class * * @class IpAddress * @package Core\Common\Domain\ValueObject\Web */ final readonly class IpAddress extends LiteralString { /** * IpAddress constructor * * @param string $ip_address * * @throws ValueObjectException */ public function __construct(string $ip_address) { if (! filter_var($ip_address, FILTER_VALIDATE_IP)) { throw new ValueObjectException("{$ip_address} is an invalid IP Address"); } parent::__construct($ip_address); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Common/Domain/ValueObject/Identity/Email.php
centreon/src/Core/Common/Domain/ValueObject/Identity/Email.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Domain\ValueObject\Identity; use Core\Common\Domain\Exception\ValueObjectException; use Core\Common\Domain\ValueObject\LiteralString; /** * Class * * @class Email * @package Core\Common\Domain\ValueObject\Identity */ final readonly class Email extends LiteralString { /** * Email constructor * * @param string $email * * @throws ValueObjectException */ public function __construct(string $email) { if (empty($email) || ! filter_var($email, FILTER_VALIDATE_EMAIL)) { throw new ValueObjectException('Invalid email', ['email' => $email]); } parent::__construct($email); } /** * Returns the local part of the email address. * * @return LiteralString */ public function getLocalPart(): LiteralString { $parts = explode('@', $this->value); return new LiteralString($parts[0]); } /** * Returns the domain part of the email address. * * @return LiteralString */ public function getDomainPart(): LiteralString { $parts = explode('@', $this->value); return new LiteralString($parts[1]); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Common/Domain/Exception/ValueObjectException.php
centreon/src/Core/Common/Domain/Exception/ValueObjectException.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Domain\Exception; /** * Class * * @class ValueObjectException * @package Core\Common\Domain\Exception */ class ValueObjectException extends BusinessLogicException { /** * ValueObjectException constructor * * @param string $message * @param array<string,mixed> $context * @param \Throwable|null $previous */ public function __construct(string $message, array $context = [], ?\Throwable $previous = null) { parent::__construct($message, self::ERROR_CODE_BAD_USAGE, $context, $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/Common/Domain/Exception/TransformerException.php
centreon/src/Core/Common/Domain/Exception/TransformerException.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Domain\Exception; /** * Class * * @class TransformerException * @package Core\Common\Domain\Exception */ class TransformerException extends BusinessLogicException { /** * TransformerException constructor * * @param string $message * @param array<string,mixed> $context * @param \Throwable|null $previous */ public function __construct(string $message, array $context = [], ?\Throwable $previous = null) { parent::__construct($message, self::ERROR_CODE_INTERNAL, $context, $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/Common/Domain/Exception/ExceptionFormatter.php
centreon/src/Core/Common/Domain/Exception/ExceptionFormatter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Domain\Exception; /** * Class * * @class ExceptionFormatter * @package Core\Common\Domain\Exception */ abstract readonly class ExceptionFormatter { /** * @param \Throwable $throwable * @return array<string,mixed> */ public static function format(\Throwable $throwable): array { return self::getExceptionInfos($throwable); } /** * @param \Throwable $throwable * * @return array<string,mixed> */ private static function getExceptionInfos(\Throwable $throwable): array { return [ 'type' => $throwable::class, 'message' => $throwable->getMessage(), 'file' => $throwable->getFile(), 'line' => $throwable->getLine(), 'code' => $throwable->getCode(), 'class' => $throwable->getTrace()[0]['class'] ?? null, 'method' => $throwable->getTrace()[0]['function'] ?? null, 'previous' => self::getPreviousInfos($throwable), ]; } /** * @param \Throwable $throwable * @return array<string,mixed>|null */ private static function getPreviousInfos(\Throwable $throwable): ?array { $previousContext = null; if ($throwable->getPrevious() !== null) { $previousContext = self::getExceptionInfos($throwable->getPrevious()); } return $previousContext; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Common/Domain/Exception/CollectionException.php
centreon/src/Core/Common/Domain/Exception/CollectionException.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Domain\Exception; /** * Class * * @class CollectionException * @package Core\Common\Domain\Exception */ class CollectionException extends BusinessLogicException { /** * CollectionException constructor * * @param string $message * @param array<string,mixed> $context * @param \Throwable|null $previous */ public function __construct(string $message, array $context = [], ?\Throwable $previous = null) { parent::__construct($message, self::ERROR_CODE_INTERNAL, $context, $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/Common/Domain/Exception/RepositoryException.php
centreon/src/Core/Common/Domain/Exception/RepositoryException.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Domain\Exception; /** * Class * * @class RepositoryException * @package Core\Common\Domain\Exception */ class RepositoryException extends BusinessLogicException { /** * RepositoryException constructor * * @param string $message * @param array<string,mixed> $context * @param \Throwable|null $previous */ public function __construct(string $message, array $context = [], ?\Throwable $previous = null) { parent::__construct($message, self::ERROR_CODE_REPOSITORY, $context, $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/Common/Domain/Exception/UnexpectedValueException.php
centreon/src/Core/Common/Domain/Exception/UnexpectedValueException.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Domain\Exception; /** * Class * * @class UnexpectedValueException * @package Core\Common\Domain\Exception */ class UnexpectedValueException extends BusinessLogicException { /** * UnexpectedValueException constructor * * @param string $message * @param array<string,mixed> $context * @param \Throwable|null $previous */ public function __construct(string $message, array $context = [], ?\Throwable $previous = null) { parent::__construct($message, self::ERROR_CODE_BAD_USAGE, $context, $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/Common/Domain/Exception/JsonException.php
centreon/src/Core/Common/Domain/Exception/JsonException.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Domain\Exception; /** * Class * * @class JsonException * @package Core\Common\Domain\Exception */ class JsonException extends BusinessLogicException { /** * JsonException constructor * * @param string $message * @param array<string,mixed> $context * @param \Throwable|null $previous */ public function __construct(string $message, array $context = [], ?\Throwable $previous = null) { parent::__construct($message, self::ERROR_CODE_INTERNAL, $context, $previous); $this->addContextItem('json_last_error', json_last_error()); $this->addContextItem('json_last_error_message', json_last_error_msg()); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Common/Domain/Exception/BusinessLogicException.php
centreon/src/Core/Common/Domain/Exception/BusinessLogicException.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Domain\Exception; /** * Class * * @class BusinessLogicException * @package Core\Common\Domain\Exception */ abstract class BusinessLogicException extends \Exception { public const ERROR_CODE_INTERNAL = 0; public const ERROR_CODE_REPOSITORY = 1; public const ERROR_CODE_BAD_USAGE = 4; /** @var array<string,mixed> */ private array $context = []; /** @var array<string,mixed> */ private array $businessContext; /** @var array<string,mixed> */ private array $exceptionContext; /** * BusinessLogicException constructor * * @param string $message * @param int $code * @param array<string,mixed> $context * @param \Throwable|null $previous */ public function __construct(string $message, int $code, array $context = [], ?\Throwable $previous = null) { parent::__construct($message, $code, $previous); $this->setBusinessContext($context); $this->setExceptionContext(); $this->setGlobalContext(); } /** * @return array<string,mixed> */ public function getContext(): array { return $this->context; } /** * @param array<string,mixed> $context * * @return void */ public function setContext(array $context): void { $this->context = $context; } /** * @param string $name * @param mixed $value * * @return void */ public function addContextItem(string $name, mixed $value): void { $this->context[$name] = $value; } /** * @param array<string,mixed> $newContext * * @return void */ public function addContext(array $newContext): void { $this->context = array_merge($this->getContext(), $newContext); } /** * @return array<string,mixed> */ public function getBusinessContext(): array { return $this->businessContext; } /** * @return array<string,mixed> */ public function getExceptionContext(): array { return $this->exceptionContext; } // ----------------------------------------- PRIVATE METHODS ----------------------------------------- /** * @return void */ private function setGlobalContext(): void { $this->context = array_merge( $this->getExceptionContext(), ['context' => $this->getBusinessContext()] ); } /** * @param array<string,mixed> $context * * @return void */ private function setBusinessContext(array $context): void { $previousContext = null; if ($this->getPrevious() instanceof self) { $previousContext = $this->getPrevious()->getBusinessContext(); } $this->businessContext = array_merge( $context, ['previous' => $previousContext] ); } /** * @return void */ private function setExceptionContext(): void { $this->exceptionContext = ExceptionFormatter::format($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/Common/Infrastructure/FeatureFlags.php
centreon/src/Core/Common/Infrastructure/FeatureFlags.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Infrastructure; use Centreon\Domain\Log\LoggerTrait; use Core\Common\Application\FeatureFlagsInterface; use function is_int; use function is_string; /** * {@see FeatureFlagsInterface}. * * Example of the file structure. * <pre>{ * "feature-1": 0, * "feature-2": 3 * }</pre> */ final class FeatureFlags implements FeatureFlagsInterface { use LoggerTrait; private const BIT_ON_PREM = 0b0001; private const BIT_CLOUD = 0b0010; /** @var array<string, bool> */ private readonly array $flags; /** @var array<string> */ private readonly array $enabledFlags; private readonly bool $isCloudPlatform; /** * @param bool $isCloudPlatform * @param string $json */ public function __construct(bool $isCloudPlatform, string $json) { [$flags, $enabledFlags] = $this->prepare($isCloudPlatform, $json); $this->flags = $flags; $this->enabledFlags = $enabledFlags; $this->isCloudPlatform = $isCloudPlatform; } /** * {@inheritDoc} */ public function isCloudPlatform(): bool { return $this->isCloudPlatform; } /** * {@inheritDoc} */ public function getAll(): array { return $this->flags; } /** * Return an array of flag names which are enabled (active). * * @return array<string> */ public function getEnabled(): array { return $this->enabledFlags; } /** * {@inheritDoc} */ public function isEnabled(string $feature): bool { if (isset($this->flags[$feature])) { return $this->flags[$feature]; } $this->info("The feature flag '{$feature}' does not exists."); return false; } /** * This build the flags for the current platform. * * @param bool $isCloudPlatform * @param string $json * * @return array{ * array<string, bool>, * array<string> * } */ private function prepare(bool $isCloudPlatform, string $json): array { $bit = $isCloudPlatform ? self::BIT_CLOUD : self::BIT_ON_PREM; $flags = []; $enabledFlags = []; foreach ($this->safeJsonDecode($json) as $feature => $bitmask) { if (! is_string($feature) || ! is_int($bitmask)) { continue; } $isEnabled = (bool) ($bitmask & $bit); if ($isEnabled) { $enabledFlags[] = $feature; } $flags[$feature] = $isEnabled; } return [$flags, $enabledFlags]; } /** * This safely decodes the JSON to an array. * * @param string $json * * @return array<mixed> */ private function safeJsonDecode(string $json): array { try { if (is_array($array = json_decode($json, true, 10, JSON_THROW_ON_ERROR))) { return $array; } } catch (\JsonException $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); } return []; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Common/Infrastructure/CommandInitializer.php
centreon/src/Core/Common/Infrastructure/CommandInitializer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Infrastructure; use Symfony\Component\Console\Application; use Symfony\Component\Console\Command\Command; class CommandInitializer extends Application { /** * @param iterable<Command> $commands * * @throws \Symfony\Component\Console\Exception\LogicException */ public function __construct(iterable $commands) { $commands = $commands instanceof \Traversable ? iterator_to_array($commands) : $commands; foreach ($commands as $command) { $this->add($command); } parent::__construct(); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Common/Infrastructure/Routing/ModuleRouteLoader.php
centreon/src/Core/Common/Infrastructure/Routing/ModuleRouteLoader.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Infrastructure\Routing; use Core\Common\Infrastructure\ExceptionLogger\ExceptionLogger; use Core\Module\Infrastructure\ModuleInstallationVerifier; use Core\Platform\Domain\InstallationVerifierInterface; use Symfony\Bundle\FrameworkBundle\Routing\RouteLoaderInterface; use Symfony\Component\DependencyInjection\Attribute\Autowire; use Symfony\Component\Routing\Loader\AttributeFileLoader; use Symfony\Component\Routing\RouteCollection; abstract readonly class ModuleRouteLoader implements RouteLoaderInterface { public function __construct( #[Autowire(service: 'routing.loader.attribute.file')] private AttributeFileLoader $loader, #[Autowire(param: 'kernel.project_dir')] private string $projectDir, private ModuleInstallationVerifier $moduleInstallationVerifier, private InstallationVerifierInterface $centreonInstallationVerifier, ) { } final public function __invoke(): RouteCollection { $routes = new RouteCollection(); /** * Dont populate RouteCollection during install / upgrade process to avoid DI of services that could need * some configurations that don't exists at this moment of the lifecycle of the software. */ if ($this->centreonInstallationVerifier->isCentreonWebInstallableOrUpgradable()) { return $routes; } try { if (! $this->moduleInstallationVerifier->isInstallComplete($this->getModuleName())) { return $routes; } } catch (\Throwable $ex) { ExceptionLogger::create()->log($ex, ['module_name' => $this->getModuleName()]); return $routes; } $controllerFilePattern = $this->projectDir . '/src/' . $this->getModuleDirectory() . '/**/*Controller.php'; $routeCollections = $this->loader->import($controllerFilePattern, 'attribute'); if (! is_iterable($routeCollections)) { return $routes; } // Modules with only one route will return directly a route collection if ($routeCollections instanceof RouteCollection) { $routeCollections->addPrefix('/{base_uri}api/{version}'); $routeCollections->addDefaults(['base_uri' => 'centreon/', 'version' => 'latest']); $routeCollections->addRequirements(['base_uri' => '(.+/)|.{0}']); return $routeCollections; } foreach ($routeCollections as $routeCollection) { $routes->addCollection($routeCollection); } $routes->addPrefix('/{base_uri}api/{version}'); $routes->addDefaults(['base_uri' => 'centreon/', 'version' => 'latest']); $routes->addRequirements(['base_uri' => '(.+/)|.{0}']); return $routes; } abstract protected function getModuleName(): string; abstract protected function getModuleDirectory(): string; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Common/Infrastructure/ExceptionLogger/ExceptionLogFormatter.php
centreon/src/Core/Common/Infrastructure/ExceptionLogger/ExceptionLogFormatter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Infrastructure\ExceptionLogger; use Core\Common\Domain\Exception\BusinessLogicException; use Core\Common\Domain\Exception\ExceptionFormatter; /** * Class * * @class ExceptionLogFormatter * @package Core\Common\Infrastructure\ExceptionLogger\ExceptionLogger */ abstract class ExceptionLogFormatter { /** * @param array<string,mixed> $customContext * @param \Throwable $throwable * * @return array<string,mixed> */ public static function format(array $customContext, \Throwable $throwable): array { $customContext = self::formatCustomContext($throwable, $customContext); $exceptionContext = self::formatExceptionContext($throwable); $context = $customContext !== [] ? $customContext : null; $context['exception'] = $exceptionContext !== [] ? $exceptionContext : null; return $context; } /** * @param \Throwable $throwable * * @return array<string,mixed> */ private static function formatExceptionContext(\Throwable $throwable): array { $exceptionContext = []; if ($throwable instanceof BusinessLogicException) { $firstThrowable = $throwable->getExceptionContext(); } else { $firstThrowable = ExceptionFormatter::format($throwable); } $previousList = self::cleanPreviousCollection(self::getPreviousCollection($firstThrowable)); if (array_key_exists('previous', $firstThrowable)) { unset($firstThrowable['previous']); } $exceptionContext['exceptions'] = array_merge([$firstThrowable], $previousList); $exceptionContext['traces'] = $throwable->getTrace(); return $exceptionContext; } /** * @param \Throwable $throwable * @param array<string,mixed> $customContext * * @return array<string,mixed> */ private static function formatCustomContext(\Throwable $throwable, array $customContext): array { if ($throwable instanceof BusinessLogicException) { $firstThrowableContext = $throwable->getBusinessContext(); $previousListContext = self::cleanPreviousCollection(self::getPreviousCollection($firstThrowableContext)); if (array_key_exists('previous', $firstThrowableContext)) { unset($firstThrowableContext['previous']); } $firstThrowableContext = $firstThrowableContext !== [] ? [$firstThrowableContext] : []; $contextExceptions = array_merge($firstThrowableContext, $previousListContext); $customContext['from_exception'] = $contextExceptions; } return $customContext; } /** * @param array<string,mixed> $context * * @return array<int,array<string,mixed>> */ private static function getPreviousCollection(array $context): array { $previousList = []; if (isset($context['previous'])) { $previousList[] = $context['previous']; $previousList = array_merge($previousList, self::getPreviousCollection($context['previous'])); } return $previousList; } /** * @param array<int,array<string,mixed>> $previousList * * @return array<int,array<string,mixed>> */ private static function cleanPreviousCollection(array $previousList): array { $previousListCleaned = []; foreach ($previousList as $previous) { if (array_key_exists('previous', $previous)) { unset($previous['previous']); } if (! empty($previous)) { $previousListCleaned[] = $previous; } } return $previousListCleaned; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Common/Infrastructure/ExceptionLogger/ExceptionLogger.php
centreon/src/Core/Common/Infrastructure/ExceptionLogger/ExceptionLogger.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Infrastructure\ExceptionLogger; use Centreon\Domain\Log\Logger; use Psr\Log\LoggerInterface; use Psr\Log\LogLevel; /** * Class * * @class ExceptionLogger * @package Core\Common\Infrastructure\ExceptionLogger */ final readonly class ExceptionLogger { /** * ExceptionLogger constructor * * @param LoggerInterface $logger */ public function __construct( private LoggerInterface $logger, ) { } /** * Factory * * @return ExceptionLogger */ public static function create(): self { return new self(new Logger()); } /** * @param \Throwable $throwable * @param array<string,mixed> $context * @param string $level {@see LogLevel} * * @return void */ public function log(\Throwable $throwable, array $context = [], string $level = LogLevel::ERROR): void { $context = ExceptionLogFormatter::format($context, $throwable); $this->logger->log($level, $throwable->getMessage(), $context); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Common/Infrastructure/Upload/FileCollection.php
centreon/src/Core/Common/Infrastructure/Upload/FileCollection.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Infrastructure\Upload; use Symfony\Component\HttpFoundation\File\UploadedFile; class FileCollection { private \AppendIterator $appendIterator; /** * @throws \Exception */ public function __construct() { $this->appendIterator = new \AppendIterator(); $this->appendIterator->append(new CommonFileIterator()); } /** * @param UploadedFile $file * * @throws \Exception */ public function addFile(UploadedFile $file): void { if ($file->getMimeType() === ZipFileIterator::MIME_TYPE) { $this->appendIterator->append(new ZipFileIterator($file)); } else { foreach ($this->appendIterator->getArrayIterator() as $iterator) { if ($iterator instanceof CommonFileIterator) { $iterator->addFile($file); break; } } } } /** * @return \AppendIterator<string, string, FileIteratorInterface> */ public function getFiles(): \AppendIterator { return $this->appendIterator; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Common/Infrastructure/Upload/ZipFileIterator.php
centreon/src/Core/Common/Infrastructure/Upload/ZipFileIterator.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Infrastructure\Upload; use Symfony\Component\HttpFoundation\File\File; class ZipFileIterator implements FileIteratorInterface { public const MIME_TYPE = 'application/zip'; private \ZipArchive $zipArchive; private int $filePosition = 0; /** * @param File $file * * @throws \Exception */ public function __construct(readonly private File $file) { if ($this->file->getMimeType() !== self::MIME_TYPE) { throw new \Exception( sprintf('Incompatible file type: %s != %s', $this->file->getMimeType(), self::MIME_TYPE) ); } $this->zipArchive = new \ZipArchive(); $openStatus = $this->zipArchive->open($file->getRealPath()); if ($openStatus !== true) { throw new \Exception($this->getErrorMessage($openStatus)); } } public function count(): int { return $this->zipArchive->count(); } /** * @inheritDoc */ public function current(): string { $fileContent = $this->zipArchive->getFromIndex($this->filePosition); if ($fileContent === false) { throw new \Exception(); } return $fileContent; } /** * @throws \Exception */ public function next(): void { $this->filePosition++; } /** * @throws \Exception */ public function key(): string { $currentFilename = $this->zipArchive->getNameIndex($this->filePosition); if ($currentFilename === false) { throw new \Exception(); } return $currentFilename; } public function valid(): bool { return $this->filePosition < $this->zipArchive->count(); } /** * @throws \Exception */ public function rewind(): void { $this->filePosition = 0; } /** * Retrieve the error message according to the open status error code. * * @param int $openStatus * * @return string */ private function getErrorMessage(int $openStatus): string { return match ($openStatus) { \ZipArchive::ER_EXISTS => 'The file already exists', \ZipArchive::ER_INCONS => 'The ZIP archive is inconsistent', \ZipArchive::ER_INVAL => 'Invalid argument', \ZipArchive::ER_MEMORY => 'Memory allocation failure', \ZipArchive::ER_NOENT => 'The file does not exist', \ZipArchive::ER_NOZIP => 'This is not a ZIP archive', \ZipArchive::ER_OPEN => 'Unable to open file', \ZipArchive::ER_READ => 'Reading error', \ZipArchive::ER_SEEK => 'Position error', default => 'Unknown 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/Common/Infrastructure/Upload/CommonFileIterator.php
centreon/src/Core/Common/Infrastructure/Upload/CommonFileIterator.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Infrastructure\Upload; use Symfony\Component\HttpFoundation\File\UploadedFile; class CommonFileIterator implements FileIteratorInterface { private int $fileIndex = 0; private int $fileNumber = 0; /** @var list<UploadedFile> */ private array $files = []; /** * @param UploadedFile $file */ public function addFile(UploadedFile $file): void { $this->files[] = $file; $this->fileNumber++; } public function count(): int { return $this->fileNumber; } /** * @return string */ public function current(): string { return $this->files[$this->fileIndex]->getContent(); } public function next(): void { $this->fileIndex++; } /** * @return string */ public function key(): string { return $this->files[$this->fileIndex]->getClientOriginalName(); } public function valid(): bool { return $this->fileIndex < $this->fileNumber; } public function rewind(): void { $this->fileIndex = 0; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Common/Infrastructure/Upload/FileIteratorInterface.php
centreon/src/Core/Common/Infrastructure/Upload/FileIteratorInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Infrastructure\Upload; /** * @extends \Iterator<string, string> */ interface FileIteratorInterface extends \Iterator, \Countable { /** * @return int Returns the number of files */ public function count(): int; /** * @throws \Exception * * @return string Returns the file content */ public function current(): string; public function next(): void; /** * @return string Returns the filename */ public function key(): string; public function valid(): bool; public function rewind(): 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/Common/Infrastructure/RequestParameters/Transformer/SearchRequestParametersTransformer.php
centreon/src/Core/Common/Infrastructure/RequestParameters/Transformer/SearchRequestParametersTransformer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Infrastructure\RequestParameters\Transformer; use Adaptation\Database\Connection\Adapter\Pdo\Transformer\PdoParameterTypeTransformer; use Adaptation\Database\Connection\Collection\QueryParameters; use Adaptation\Database\Connection\Enum\QueryParameterTypeEnum; use Adaptation\Database\Connection\ValueObject\QueryParameter; use Core\Common\Domain\Exception\CollectionException; use Core\Common\Domain\Exception\TransformerException; use Core\Common\Domain\Exception\ValueObjectException; /** * Class * * @class SearchRequestParametersTransformer * @package Centreon\Infrastructure\RequestParameters\Transformer */ abstract readonly class SearchRequestParametersTransformer { /** * @param QueryParameters $queryParameters * * @return array<string,array<int,mixed>> */ public static function transformFromQueryParameters(QueryParameters $queryParameters): array { $requestParameters = []; /** @var QueryParameter $queryParameter */ foreach ($queryParameters->getIterator() as $queryParameter) { $pdoType = PdoParameterTypeTransformer::transformFromQueryParameterType( $queryParameter->getType() ?? QueryParameterTypeEnum::STRING ); $requestParameters[$queryParameter->getName()] = [$pdoType => $queryParameter->getValue()]; } return $requestParameters; } /** * @param array<string,array<int,mixed>> $requestParameters * * @throws TransformerException * @return QueryParameters */ public static function reverseToQueryParameters(array $requestParameters): QueryParameters { try { $queryParameters = new QueryParameters(); foreach ($requestParameters as $name => $parameter) { $pdoType = key($parameter); if (is_null($pdoType)) { throw new TransformerException( 'Error while transforming request parameters to query parameters with pdo type', ['requestParameters' => $requestParameters] ); } $queryParameterTypeEnum = PdoParameterTypeTransformer::reverseToQueryParameterType($pdoType); $queryParameters->add($name, QueryParameter::create($name, $parameter[$pdoType], $queryParameterTypeEnum)); } return $queryParameters; } catch (CollectionException|ValueObjectException $exception) { throw new TransformerException( 'Error while transforming request parameters to query parameters', ['requestParameters' => $requestParameters], $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/Common/Infrastructure/RequestParameters/Normalizer/BoolToEnumNormalizer.php
centreon/src/Core/Common/Infrastructure/RequestParameters/Normalizer/BoolToEnumNormalizer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Infrastructure\RequestParameters\Normalizer; use Centreon\Infrastructure\RequestParameters\Interfaces\NormalizerInterface; /** * This simple normalizer translate a value to a valid string (for mysql enum). */ final class BoolToEnumNormalizer implements NormalizerInterface { public function __construct( private readonly string $falseEnum = '0', private readonly string $trueEnum = '1', private readonly bool $nullable = false, ) { } /** * {@inheritDoc} * * @throws \TypeError */ public function normalize($valueToNormalize): ?string { return match ($valueToNormalize) { true, 1, '1', 'true', 'TRUE', $this->trueEnum => $this->trueEnum, false, 0, '0', 'false', 'FALSE', $this->falseEnum => $this->falseEnum, null => $this->nullable ? null : throw $this->newTypeError($valueToNormalize), default => throw $this->newTypeError($valueToNormalize), }; } private function newTypeError(string|int|null $value): \TypeError { return new \TypeError( sprintf( 'The value %s is not supported.', '<' . get_debug_type($value) . '>' . $value ) ); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Common/Infrastructure/RequestParameters/Normalizer/BoolToIntegerNormalizer.php
centreon/src/Core/Common/Infrastructure/RequestParameters/Normalizer/BoolToIntegerNormalizer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Infrastructure\RequestParameters\Normalizer; use Centreon\Infrastructure\RequestParameters\Interfaces\NormalizerInterface; /** * This simple normalizer translate a value to a valid integer. */ final class BoolToIntegerNormalizer implements NormalizerInterface { public function __construct( private readonly int $falseEnum = 0, private readonly int $trueEnum = 1, private readonly bool $nullable = false, ) { } /** * {@inheritDoc} * * @throws \TypeError */ public function normalize($valueToNormalize): ?int { return match ($valueToNormalize) { true, 1, '1', 'true', 'TRUE', $this->trueEnum => $this->trueEnum, false, 0, '0', 'false', 'FALSE', $this->falseEnum => $this->falseEnum, null => $this->nullable ? null : throw $this->newTypeError($valueToNormalize), default => throw $this->newTypeError($valueToNormalize), }; } private function newTypeError(string|int|null $value): \TypeError { return new \TypeError( sprintf( 'The value "%s" is not supported.', '<' . get_debug_type($value) . '>' . $value ) ); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Common/Infrastructure/Validator/DateFormat.php
centreon/src/Core/Common/Infrastructure/Validator/DateFormat.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Common\Infrastructure\Validator; final class DateFormat { /** * This is not the DateTime:ISO8601 PHP format. This represents the format sent by the frontend to Centreon APIs */ public const ISO8601 = 'Y-m-d\TH:i:s.u\Z'; public const INVALID_DATE_MESSAGE = 'this field does not match expected date format. Expected : 2024-09-10T12:45:00.000Z'; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false