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/Common/Infrastructure/Validator/Constraints/WhenPlatformValidator.php | centreon/src/Core/Common/Infrastructure/Validator/Constraints/WhenPlatformValidator.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the 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\Constraints;
use Core\Common\Domain\PlatformType;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
final class WhenPlatformValidator extends ConstraintValidator
{
public function __construct(private readonly bool $isCloudPlatform)
{
}
public function validate(mixed $value, Constraint $constraint): void
{
if (! $constraint instanceof WhenPlatform) {
throw new UnexpectedTypeException($constraint, WhenPlatform::class);
}
$context = $this->context;
if ($this->platformMatch($constraint->platform)) {
$context->getValidator()->inContext($context)
->validate($value, $constraint->constraints);
}
}
private function platformMatch(string $platform): bool
{
return ($this->isCloudPlatform === true && $platform === PlatformType::CLOUD)
|| ($this->isCloudPlatform === false && $platform === PlatformType::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/Infrastructure/Validator/Constraints/WhenPlatform.php | centreon/src/Core/Common/Infrastructure/Validator/Constraints/WhenPlatform.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the 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\Constraints;
use Core\Common\Domain\PlatformType;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\Composite;
use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
use Symfony\Component\Validator\Exception\InvalidOptionsException;
use Symfony\Component\Validator\Exception\LogicException;
use Symfony\Component\Validator\Exception\MissingOptionsException;
/**
* Strongly Inspired by Symfony\Component\Validator\Constraints\When
*
* Dedicated to handle by ourselves the context of the platform.
*
* @Annotation
* @Target({"CLASS", "PROPERTY", "METHOD", "ANNOTATION"})
*/
#[\Attribute(
\Attribute::TARGET_CLASS
| \Attribute::TARGET_PROPERTY
| \Attribute::TARGET_METHOD
| \Attribute::IS_REPEATABLE
)]
final class WhenPlatform extends Composite
{
/**
* @param string $platform
* @param Constraint[]|Constraint|null $constraints
* @param null|string[] $groups
* @param mixed $payload
* @param array<mixed> $options
*
* @throws LogicException
* @throws ConstraintDefinitionException
* @throws InvalidOptionsException
* @throws MissingOptionsException
*/
public function __construct(
public string $platform,
public array|Constraint|null $constraints = null,
?array $groups = null,
$payload = null,
array $options = [],
) {
if (! \in_array($platform, PlatformType::AVAILABLE_TYPES, true)) {
throw new LogicException(\sprintf('The platform "%s" is not valid.', $platform));
}
$options['platform'] = $platform;
$options['constraints'] = $constraints;
if (isset($options['constraints']) && ! \is_array($options['constraints'])) {
$options['constraints'] = [$options['constraints']];
}
if ($groups !== null) {
$options['groups'] = $groups;
}
if ($payload !== null) {
$options['payload'] = $payload;
}
parent::__construct($options);
}
public function getRequiredOptions(): array
{
return ['platform', 'constraints'];
}
/**
* @return string[]
*/
public function getTargets(): array
{
return [self::CLASS_CONSTRAINT, self::PROPERTY_CONSTRAINT];
}
protected function getCompositeOption(): string
{
return 'constraints';
}
}
| 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/Normalizer/GeoCoordsNormalizer.php | centreon/src/Core/Common/Infrastructure/Normalizer/GeoCoordsNormalizer.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the 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\Normalizer;
use Core\Domain\Common\GeoCoords;
use Symfony\Component\Serializer\Exception\ExceptionInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
final readonly class GeoCoordsNormalizer implements NormalizerInterface
{
/**
* @param mixed $object
* @param string|null $format
* @param array<string, mixed> $context
*
* @throws ExceptionInterface
*/
public function normalize(
mixed $object,
?string $format = null,
array $context = [],
): string {
/** @var GeoCoords $object */
return $object->__toString();
}
/**
* @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 GeoCoords;
}
/**
* @param ?string $format
* @return array<class-string|'*'|'object'|string, bool|null>
*/
public function getSupportedTypes(?string $format): array
{
return [
GeoCoords::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/Common/Infrastructure/Normalizer/NotEmptyStringNormalizer.php | centreon/src/Core/Common/Infrastructure/Normalizer/NotEmptyStringNormalizer.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the 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\Normalizer;
use Core\Common\Domain\NotEmptyString;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Serializer\Exception\ExceptionInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
final readonly class NotEmptyStringNormalizer 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
*/
public function normalize(
mixed $object,
?string $format = null,
array $context = [],
): string {
/** @var array{value: string} $data */
$data = $this->normalizer->normalize($object, $format, $context);
return $data['value'];
}
/**
* @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 NotEmptyString;
}
/**
* @param ?string $format
* @return array<class-string|'*'|'object'|string, bool|null>
*/
public function getSupportedTypes(?string $format): array
{
return [
NotEmptyString::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/Common/Infrastructure/Repository/DataStorageObserver.php | centreon/src/Core/Common/Infrastructure/Repository/DataStorageObserver.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the 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\Repository;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
class DataStorageObserver implements DataStorageEngineInterface
{
use LoggerTrait;
/** @var list<DataStorageEngineInterface> */
private array $engines = [];
/**
* @param DataStorageEngineInterface ...$dataStorageEngines
*/
public function __construct(DataStorageEngineInterface ...$dataStorageEngines)
{
$this->engines = array_values($dataStorageEngines);
}
/**
* @inheritDoc
*/
public function rollbackTransaction(): bool
{
$status = true;
foreach ($this->engines as $engine) {
$status = $engine->rollbackTransaction() && $status;
}
return $status;
}
/**
* @inheritDoc
*/
public function startTransaction(): bool
{
$this->debug(
'Starting the data storage engine transaction',
['engines' => array_map(fn (DataStorageEngineInterface $engine) => $engine::class, $this->engines)]
);
$status = true;
foreach ($this->engines as $engine) {
$status = $engine->startTransaction() && $status;
}
return $status;
}
/**
* @inheritDoc
*/
public function commitTransaction(): bool
{
$status = true;
foreach ($this->engines as $engine) {
$status = $engine->commitTransaction() && $status;
}
return $status;
}
/**
* @inheritDoc
*/
public function isAlreadyinTransaction(): bool
{
$status = true;
foreach ($this->engines as $engine) {
$status = $engine->isAlreadyinTransaction() && $status;
}
return $status;
}
}
| 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/Repository/DatabaseRepositoryManager.php | centreon/src/Core/Common/Infrastructure/Repository/DatabaseRepositoryManager.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the 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\Repository;
use Adaptation\Database\Connection\ConnectionInterface;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Core\Common\Application\Repository\RepositoryManagerInterface;
use Core\Common\Domain\Exception\RepositoryException;
/**
* Class
*
* @class DatabaseRepositoryManager
* @package Core\Common\Application\Repository
*/
final readonly class DatabaseRepositoryManager implements RepositoryManagerInterface
{
/**
* DatabaseRepositoryManager constructor
*
* @param ConnectionInterface $connection
*/
public function __construct(private ConnectionInterface $connection)
{
}
/**
* @inheritDoc
*/
public function isTransactionActive(): bool
{
return $this->connection->isTransactionActive();
}
/**
* @inheritDoc
*/
public function startTransaction(): void
{
try {
$this->connection->startTransaction();
} catch (ConnectionException $exception) {
throw new RepositoryException(
message : 'Unable to start transaction from database repository manager',
previous : $exception,
);
}
}
/**
* @inheritDoc
*/
public function commitTransaction(): bool
{
try {
return $this->connection->commitTransaction();
} catch (ConnectionException $exception) {
throw new RepositoryException(
message : 'Unable to commit transaction from database repository manager',
previous : $exception,
);
}
}
/**
* @inheritDoc
*/
public function rollBackTransaction(): bool
{
try {
return $this->connection->rollBackTransaction();
} catch (ConnectionException $exception) {
throw new RepositoryException(
message : 'Unable to rollback transaction from database repository manager',
previous : $exception,
);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Common/Infrastructure/Repository/ApiResponseTrait.php | centreon/src/Core/Common/Infrastructure/Repository/ApiResponseTrait.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the 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\Repository;
use Centreon\Domain\Repository\RepositoryException;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
trait ApiResponseTrait
{
/**
* @param ResponseInterface $response
*
* @throws ClientExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ServerExceptionInterface
* @throws TransportExceptionInterface
* @throws RepositoryException
*
* @return array<mixed>
*/
public function getResponseOrFail(ResponseInterface $response): array
{
$httpStatusCode = $response->getStatusCode();
$responseBody = json_decode($response->getContent(false), true);
if ($httpStatusCode !== Response::HTTP_OK) {
if (is_array($responseBody) && array_key_exists('message', $responseBody)) {
$errorMessage = sprintf('%s (%d)', $responseBody['message'], $httpStatusCode);
} else {
$errorMessage = $httpStatusCode;
}
if (isset($this->logger) && $this->logger instanceof LoggerInterface) {
$this->logger->debug('API error', [
'http_code' => $httpStatusCode,
'message' => $errorMessage,
]);
}
throw new RepositoryException('Request error: ' . $errorMessage, $httpStatusCode);
}
if (! is_array($responseBody)) {
throw new RepositoryException('No body response');
}
return $responseBody;
}
}
| 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/Repository/WriteVaultRepository.php | centreon/src/Core/Common/Infrastructure/Repository/WriteVaultRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the 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\Repository;
use Core\Common\Application\Repository\WriteVaultRepositoryInterface;
use Core\Security\Vault\Application\Repository\ReadVaultConfigurationRepositoryInterface;
use Symfony\Component\HttpClient\AmpHttpClient;
use Utility\Interfaces\UUIDGeneratorInterface;
class WriteVaultRepository extends AbstractVaultRepository implements WriteVaultRepositoryInterface
{
public function __construct(
private readonly UUIDGeneratorInterface $uuidGenerator,
protected ReadVaultConfigurationRepositoryInterface $configurationRepository,
protected AmpHttpClient $httpClient,
) {
parent::__construct($configurationRepository, $httpClient);
}
/**
* @inheritDoc
*/
public function upsert(?string $uuid = null, array $inserts = [], array $deletes = []): array
{
if ($this->vaultConfiguration === null) {
throw new \LogicException('Vault not configured');
}
$payload = [];
if ($uuid === null) {
$uuid = $this->uuidGenerator->generateV4();
$url = $this->buildUrl($uuid);
} else {
$url = $this->buildUrl($uuid);
// Retrieve current vault data
$responseContent = $this->sendRequest('GET', $url);
if (is_array($responseContent) && isset($responseContent['data']['data'])) {
$payload = $responseContent['data']['data'];
}
}
// Delete unwanted data
foreach (array_keys($deletes) as $deleteKey) {
unset($payload[$deleteKey]);
}
// Add new data
foreach ($inserts as $insertKey => $insertValue) {
$payload[$insertKey] = $insertValue;
}
$this->sendRequest('POST', $url, $payload);
$paths = [];
/** @var string $credentialName */
foreach (array_keys($payload) as $credentialName) {
$paths[$credentialName] = $this->buildPath($uuid, $credentialName);
}
return $paths;
}
/**
* @inheritDoc
*/
public function delete(string $uuid): void
{
if ($this->vaultConfiguration === null) {
throw new \LogicException('Vault not configured');
}
$url = $this->vaultConfiguration->getAddress() . ':' . $this->vaultConfiguration->getPort()
. '/v1/' . $this->vaultConfiguration->getRootPath() . '/metadata/' . $this->customPath . '/' . $uuid;
$url = sprintf('%s://%s', parent::DEFAULT_SCHEME, $url);
$this->sendRequest('DELETE', $url);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Common/Infrastructure/Repository/SqlMultipleBindTrait.php | centreon/src/Core/Common/Infrastructure/Repository/SqlMultipleBindTrait.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the 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\Repository;
use Adaptation\Database\Connection\Enum\QueryParameterTypeEnum;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Core\Common\Domain\Exception\ValueObjectException;
trait SqlMultipleBindTrait
{
/**
* @param array<int|string, int|string> $list
* @param string $prefix
* @param int|null $bindType (optional)
*
* @return array{
* 0: array<string, int|string|array{0: int|string, 1: int}>,
* 1: string
* }
*/
protected function createMultipleBindQuery(array $list, string $prefix, ?int $bindType = null): array
{
$bindValues = [];
$list = array_values($list); // Reset index to avoid SQL injection
foreach ($list as $index => $id) {
$bindValues[$prefix . $index] = ($bindType === null) ? $id : [$id, $bindType];
}
return [$bindValues, implode(', ', array_keys($bindValues))];
}
/**
* Create multiple bind parameters compatible with QueryParameterTypeEnum
*
* @param array<int|string, int|string|null> $values Scalar values to bind
* @param string $prefix Placeholder prefix (no colon)
* @param QueryParameterTypeEnum $paramType Type of binding (INTEGER|STRING)
*
* @throws ValueObjectException
* @return array{parameters: QueryParameter[], placeholderList: string}
*/
protected function createMultipleBindParameters(
array $values,
string $prefix,
QueryParameterTypeEnum $paramType,
): array {
$placeholders = [];
$parameters = [];
foreach (array_values($values) as $idx => $val) {
$name = "{$prefix}_{$idx}";
$placeholders[] = ':' . $name;
$parameters[] = match ($paramType) {
QueryParameterTypeEnum::INTEGER => ($val === null)
? QueryParameter::null($name)
: QueryParameter::int($name, (int) $val),
default => ($val === null)
? QueryParameter::null($name)
: QueryParameter::string($name, (string) $val),
};
}
return [
'parameters' => $parameters,
'placeholderList' => implode(', ', $placeholders),
];
}
}
| 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/Repository/ApiCallIterator.php | centreon/src/Core/Common/Infrastructure/Repository/ApiCallIterator.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the 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\Repository;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Centreon\Domain\Repository\RepositoryException;
use Psr\Log\LoggerInterface;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
/**
* @template T
*
* @implements \IteratorAggregate<int, T>&\Countable
*/
class ApiCallIterator implements \IteratorAggregate, \Countable
{
use ApiResponseTrait;
private int $nbrElements = -1;
/**
* @param HttpClientInterface $httpClient
* @param string $url
* @param array<string, mixed> $options
* @param positive-int $maxItemsByRequest
* @param \Closure $entityFactory
* @param LoggerInterface $logger
*
* @throws AssertionFailedException
*/
public function __construct(
private readonly HttpClientInterface $httpClient,
private readonly string $url,
private readonly array $options,
private readonly int $maxItemsByRequest,
private readonly \Closure $entityFactory,
private readonly LoggerInterface $logger,
) {
Assertion::positiveInt($this->maxItemsByRequest, 'maxItemsByRequest');
}
/**
* @throws TransportExceptionInterface
* @throws ServerExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ClientExceptionInterface
* @throws RepositoryException
*/
public function getIterator(): \Traversable
{
$fromPage = 1;
$totalPage = 0;
do {
$separator = parse_url($this->url, PHP_URL_QUERY) ? '&' : '?';
$url = $this->url . $separator . sprintf('limit=%d&page=%d', $this->maxItemsByRequest, $fromPage);
$this->logger->debug('Call API', ['url' => $url]);
/** @var array{meta: array{total: int}, result: array<string, mixed>} $response */
$response = $this->getResponseOrFail($this->httpClient->request('GET', $url, $this->options));
if ($this->nbrElements === -1) {
$this->nbrElements = (int) $response['meta']['total'];
$totalPage = (int) ceil($this->nbrElements / $this->maxItemsByRequest);
$this->logger->debug(
'API call status',
['url' => $url, 'nbr_elements' => $this->nbrElements, 'nbr_page' => $totalPage]
);
}
foreach ($response['result'] as $result) {
$entity = ($this->entityFactory)($result);
if ($entity instanceof \Traversable) {
foreach ($entity as $oneEntity) {
yield $oneEntity;
}
} else {
yield $entity;
}
}
$fromPage++;
} while ($fromPage <= $totalPage);
}
/**
* @throws TransportExceptionInterface
* @throws ServerExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ClientExceptionInterface
* @throws RepositoryException
*/
public function count(): int
{
if ($this->nbrElements === -1) {
$this->logger->debug('Counting elements before recovery', ['url' => $this->url]);
$separator = parse_url($this->url, PHP_URL_QUERY) ? '&' : '?';
$url = $this->url . $separator . 'limit=1&page=1';
/** @var array{meta: array{total: int}, result: array<string, mixed>} $response */
$response = $this->getResponseOrFail($this->httpClient->request('GET', $url, $this->options));
$this->nbrElements = (int) $response['meta']['total'];
$this->logger->debug('API call status', ['url' => $this->url, 'nbr_elements' => $this->nbrElements]);
}
return $this->nbrElements;
}
}
| 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/Repository/AbstractRepositoryRDB.php | centreon/src/Core/Common/Infrastructure/Repository/AbstractRepositoryRDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the 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\Repository;
use Adaptation\Database\Connection\ConnectionInterface;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Infrastructure\DatabaseConnection;
/**
* Class
*
* @class AbstractRepositoryRDB
* @package Core\Common\Infrastructure\Repository
*
* @deprecated use {@see DatabaseRepository} instead
*/
class AbstractRepositoryRDB
{
use LoggerTrait;
/** @var positive-int Maximum number of elements an SQL query can return */
protected int $maxItemsByRequest = 5000;
/** @var DatabaseConnection */
protected ConnectionInterface $db;
/**
* Replace all instances of :dbstg and :db by the real db names.
* The table names of the database are defined in the services.yaml
* configuration file.
*
* @param string $request Request to translate
*
* @return string Request translated
*/
protected function translateDbName(string $request): string
{
return str_replace(
[':dbstg', ':db'],
[$this->getDbNameRealTime(), $this->getDbNameConfiguration()],
$request
);
}
/**
* Calculate the number of rows returned by a SELECT FOUND_ROWS() query.
* Don't forget to call this method just after the query that you want to
* count the number of rows.
* The previous query must be a SELECT SQL_CALC_FOUND_ROWS query.
*
* @return int|null
*/
protected function calculateNumberOfRows(): ?int
{
try {
return (int) $this->db->fetchOne('SELECT FOUND_ROWS()');
} catch (ConnectionException $exception) {
$this->error(
'Error while calculating the number of rows',
['exception' => $exception->getContext()]
);
return null;
}
}
/**
* @return string
*/
protected function getDbNameConfiguration(): string
{
return $this->db->getConnectionConfig()->getDatabaseNameConfiguration();
}
/**
* @return string
*/
protected function getDbNameRealTime(): string
{
return $this->db->getConnectionConfig()->getDatabaseNameRealTime();
}
}
| 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/Repository/DatabaseRepository.php | centreon/src/Core/Common/Infrastructure/Repository/DatabaseRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the 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\Repository;
use Adaptation\Database\Connection\ConnectionInterface;
/**
* Class
*
* @class DatabaseRepository
* @package Core\Common\Infrastructure\Repository
*/
abstract class DatabaseRepository
{
/**
* DatabaseRepository constructor
*
* @param ConnectionInterface $connection
*/
public function __construct(
protected ConnectionInterface $connection,
) {
}
/**
* Replace all instances of :dbstg and :db by the real db names.
*
* @param string $query
*
* @return string
*/
protected function translateDbName(string $query): string
{
return str_replace(
[':dbstg', ':db'],
[
$this->getDbNameRealTime(),
$this->getDbNameConfiguration(),
],
$query
);
}
/**
* @return string
*/
protected function getDbNameConfiguration(): string
{
return $this->connection->getConnectionConfig()->getDatabaseNameConfiguration();
}
/**
* @return string
*/
protected function getDbNameRealTime(): string
{
return $this->connection->getConnectionConfig()->getDatabaseNameRealTime();
}
}
| 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/Repository/ValuesByPackets.php | centreon/src/Core/Common/Infrastructure/Repository/ValuesByPackets.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the 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\Repository;
/**
* This class is used to split a 'GET' API call into multiple calls, due to URL size limitations.
* The main cause of this division is the size of parameter lengths.
*
* @template T of int|string
*
* @implements \IteratorAggregate<int, list<T>>
*/
class ValuesByPackets implements \IteratorAggregate
{
/**
* @param list<T> $values
* @param int $maxItemsByRequest
* @param int $maxQueryStringLength
* @param int $separatorLength
*/
public function __construct(
private readonly array $values,
private readonly int $maxItemsByRequest,
private readonly int $maxQueryStringLength,
private readonly int $separatorLength = 1,
) {
}
/**
* Returns the list of parameters that can be used for an API call, according to the limitations defined in the
* $maxItemsByRequest and $maxQueryStringLength properties.
*
* @return \Traversable<int, list<T>>
*/
public function getIterator(): \Traversable
{
$valuesToAnalyze = $this->values;
do {
$valuesLength = 0;
$valuesToReturn = [];
foreach ($valuesToAnalyze as $value) {
$currentValueLength = mb_strlen((string) $value);
if ($valuesLength !== 0) {
$currentValueLength += $this->separatorLength;
}
if (
count($valuesToReturn) >= $this->maxItemsByRequest
|| ($currentValueLength + $valuesLength) > $this->maxQueryStringLength
) {
break;
}
$valuesLength += $currentValueLength;
$firstValue = array_shift($valuesToAnalyze);
if ($firstValue !== null) {
$valuesToReturn[] = $firstValue;
}
}
yield $valuesToReturn;
} while ($valuesToAnalyze !== []);
}
}
| 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/Repository/FileDataStoreEngine.php | centreon/src/Core/Common/Infrastructure/Repository/FileDataStoreEngine.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the 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\Repository;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Security\Encryption;
class FileDataStoreEngine implements DataStorageEngineInterface
{
private bool $inTransaction = false;
private string $workingDirectory = '';
private string $lastError = '';
/**
* @param string $absoluteMediaPath Absolute destination path for the media
* @param bool $throwsException Indicates whether an exception should be thrown in the event of an error,
* false by default
*
* @throws \Exception
*/
public function __construct(private string $absoluteMediaPath, private bool $throwsException = false)
{
$this->absoluteMediaPath = realpath($absoluteMediaPath)
?: throw new \Exception(sprintf('Path invalid \'%s\'', $absoluteMediaPath));
}
/**
* Defines whether an exception should be thrown in the event of an error.
*
* @param bool $throwsException
*/
public function throwsException(bool $throwsException): void
{
$this->throwsException = $throwsException;
}
/**
* @inheritDoc
*/
public function rollbackTransaction(): bool
{
try {
$rollbackStatus = $this->rollbackFileSystem();
$this->inTransaction = false;
return $rollbackStatus;
} catch (\Throwable $ex) {
$this->lastError = $ex->getMessage();
if ($this->throwsException) {
throw $ex;
}
return false;
}
}
/**
* @inheritDoc
*/
public function startTransaction(): bool
{
if ($this->inTransaction) {
return false;
}
$tempDirectory = str_replace('/', '-', Encryption::generateRandomString(32));
$this->workingDirectory = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $tempDirectory;
if (! mkdir($this->workingDirectory)) {
throw new \Exception(
sprintf('Unable to create a directory \'%s\'', $this->workingDirectory)
);
}
$this->inTransaction = true;
return true;
}
/**
* @inheritDoc
*/
public function commitTransaction(): bool
{
$this->inTransaction = false;
return $this->commitFileSystem();
}
/**
* @inheritDoc
*/
public function isAlreadyinTransaction(): bool
{
return $this->inTransaction;
}
/**
* @param string $pathname
* @param string $data
* @param int $flags
*
* @throws \Exception
*
* @return int|false
*/
public function addFile(string $pathname, string $data, int $flags = 0): int|false
{
$absolutePathName = $this->workingDirectory . DIRECTORY_SEPARATOR . $pathname;
$filePath = pathinfo($absolutePathName);
if (empty($filePath['dirname'])) {
throw new \Exception('The destination directory cannot be the root');
}
if (! is_dir($filePath['dirname'])) {
$this->createDirectory($filePath['dirname']);
}
return file_put_contents($absolutePathName, $data, $flags);
}
/**
* @param string $filePath
*
* @throws \Exception
*/
public function deleteFromFileSystem(string $filePath): void
{
$this->deleteFile($this->absoluteMediaPath . DIRECTORY_SEPARATOR . $filePath);
}
public function getLastError(): string
{
return $this->lastError;
}
/**
* Copies files from the temporary working folder to the destination folder.
*
* @throws \Exception
*
* @return bool
*/
private function commitFileSystem(): bool
{
try {
$fromDirIterator = new \RecursiveDirectoryIterator($this->workingDirectory, \FilesystemIterator::SKIP_DOTS);
/** @var iterable<\SplFileInfo> $files */
$files = new \RecursiveIteratorIterator($fromDirIterator, \RecursiveIteratorIterator::CHILD_FIRST);
foreach ($files as $file) {
$destDirectory = $this->absoluteMediaPath . DIRECTORY_SEPARATOR . $fromDirIterator->getFilename();
if (! is_dir($destDirectory)) {
$this->createDirectory($destDirectory);
}
if (! $file->isDir()) {
$destFile = $destDirectory . DIRECTORY_SEPARATOR . $file->getFilename();
$this->copyFile($file->getPathname(), $destFile);
}
}
$this->recursivelyDeleteDirectory($this->workingDirectory);
return true;
} catch (\Exception $ex) {
$this->lastError = $ex->getMessage();
if ($this->throwsException) {
throw $ex;
}
return false;
}
}
/**
* @param string $from
* @param string $destination
*
* @throws \Exception
*/
private function copyFile(string $from, string $destination): void
{
if (! copy($from, $destination)) {
throw new \Exception(
sprintf('Unable to copy file from \'%s\' to \'%s\'', $from, $destination)
);
}
}
/**
* @param string $path
*
* @throws \Exception
*/
private function createDirectory(string $path): void
{
if (! mkdir($path)) {
throw new \Exception(sprintf('Unable to create a directory \'%s\'', $path));
}
}
/**
* @param string $path
*
* @throws \Exception
*/
private function deleteDirectory(string $path): void
{
if (! rmdir($path)) {
throw new \Exception(sprintf('Unable to delete the directory \'%s\'', $path));
}
}
/**
* @param string $filepath
*
* @throws \Exception
*/
private function deleteFile(string $filepath): void
{
if (! unlink($filepath)) {
throw new \Exception(sprintf('Unable to delete the file \'%s\'', $filepath));
}
}
/**
* Deletes all files in the temporary working folder.
*
* @throws \Exception Indicates whether an exception should be thrown in the event of an error, false by default
*
* @return bool
*/
private function rollbackFileSystem(): bool
{
try {
$this->recursivelyDeleteDirectory($this->workingDirectory);
return true;
} catch (\Throwable $ex) {
$this->lastError = $ex->getMessage();
if ($this->throwsException) {
throw $ex;
}
return false;
}
}
/**
* Recursively delete the directory and its contents.
*
* @param string $path
*
* @throws \Exception
*/
private function recursivelyDeleteDirectory(string $path): void
{
$dirIterator = new \RecursiveDirectoryIterator($path, \FilesystemIterator::SKIP_DOTS);
/** @var iterable<\SplFileInfo> $files */
$files = new \RecursiveIteratorIterator($dirIterator, \RecursiveIteratorIterator::CHILD_FIRST);
foreach ($files as $file) {
if ($file->isDir()) {
$this->deleteDirectory($file->getRealPath());
} else {
$this->deleteFile($file->getRealPath());
}
}
$this->deleteDirectory($this->workingDirectory);
}
}
| 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/Repository/AbstractVaultRepository.php | centreon/src/Core/Common/Infrastructure/Repository/AbstractVaultRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the 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\Repository;
use Centreon\Domain\Log\LoggerTrait;
use Core\Security\Vault\Application\Repository\ReadVaultConfigurationRepositoryInterface;
use Core\Security\Vault\Domain\Model\VaultConfiguration;
use Symfony\Component\HttpClient\AmpHttpClient;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\HttpClient\Exception\{
TransportExceptionInterface
};
abstract class AbstractVaultRepository
{
use LoggerTrait;
public const HOST_VAULT_PATH = 'monitoring/hosts';
public const SERVICE_VAULT_PATH = 'monitoring/services';
public const KNOWLEDGE_BASE_PATH = 'configuration/knowledge_base';
public const POLLER_MACRO_VAULT_PATH = 'monitoring/pollerMacros';
public const OPEN_ID_CREDENTIALS_VAULT_PATH = 'configuration/openid';
public const GORGONE_VAULT_PATH = 'configuration/gorgone';
public const DATABASE_VAULT_PATH = 'database';
public const BROKER_VAULT_PATH = 'configuration/broker';
public const ACC_VAULT_PATH = 'configuration/additionalConnectorConfigurations';
protected const DEFAULT_SCHEME = 'https';
/** @var string[] */
protected array $availablePaths = [
self::HOST_VAULT_PATH,
self::SERVICE_VAULT_PATH,
self::KNOWLEDGE_BASE_PATH,
self::POLLER_MACRO_VAULT_PATH,
self::OPEN_ID_CREDENTIALS_VAULT_PATH,
self::DATABASE_VAULT_PATH,
self::BROKER_VAULT_PATH,
self::ACC_VAULT_PATH,
self::GORGONE_VAULT_PATH,
];
protected ?VaultConfiguration $vaultConfiguration;
protected string $customPath = '';
public function __construct(
protected ReadVaultConfigurationRepositoryInterface $configurationRepository,
protected AmpHttpClient $httpClient,
) {
$this->vaultConfiguration = $configurationRepository->find();
}
public function isVaultConfigured(): bool
{
return $this->vaultConfiguration !== null;
}
public function setCustomPath(string $customPath): void
{
if (! in_array($customPath, $this->availablePaths, true)) {
$this->error("Invalid custom vault path '{$customPath}'");
throw new \LogicException("Invalid custom vault path '{$customPath}'");
}
$this->customPath = $customPath;
}
public function addAvailablePath(string $path): void
{
$this->availablePaths[] = $path;
}
/**
* Connect to vault to get an authenticationToken.
*
* @throws \Exception
*
* @return string
*/
public function getAuthenticationToken(): string
{
try {
$vaultConfiguration = $this->vaultConfiguration ?? throw new \LogicException();
} catch (\LogicException $exception) {
$this->error('There is a technical problem in ' . static::class . ' about the vaultConfiguration');
throw $exception;
}
try {
$url = $vaultConfiguration->getAddress() . ':'
. $vaultConfiguration->getPort() . '/v1/auth/approle/login';
$url = sprintf('%s://%s', self::DEFAULT_SCHEME, $url);
$body = [
'role_id' => $vaultConfiguration->getRoleId(),
'secret_id' => $vaultConfiguration->getSecretId(),
];
$this->info('Authenticating to Vault: ' . $url);
$loginResponse = $this->httpClient->request('POST', $url, ['json' => $body]);
$content = json_decode($loginResponse->getContent(), true);
} catch (\Exception $ex) {
$this->error($url . ' did not respond with a 2XX status');
throw $ex;
}
/** @var array{auth?:array{client_token?:string}} $content */
if (! isset($content['auth']['client_token'])) {
$this->error($url . ' Unable to retrieve client token from Vault');
throw new \Exception('Unable to authenticate to Vault');
}
return $content['auth']['client_token'];
}
protected function buildUrl(string $uuid): string
{
if (! $this->vaultConfiguration) {
$this->error('VaultConfiguration is not defined');
throw new \LogicException();
}
$url = $this->vaultConfiguration->getAddress() . ':' . $this->vaultConfiguration->getPort()
. '/v1/' . $this->vaultConfiguration->getRootPath() . '/data/' . $this->customPath . '/' . $uuid;
return sprintf('%s://%s', self::DEFAULT_SCHEME, $url);
}
protected function buildPath(string $uuid, string $credentialName): string
{
if (! $this->vaultConfiguration) {
$this->error('VaultConfiguration is not defined');
throw new \LogicException();
}
return 'secret::' . $this->vaultConfiguration->getName() . '::' . $this->vaultConfiguration->getRootPath()
. '/data/' . $this->customPath . '/' . $uuid . '::' . $credentialName;
}
/**
* @param string $method
* @param string $url
* @param array<mixed> $data
*
* @throws \Exception
*
* @return array<mixed>
*/
protected function sendRequest(string $method, string $url, ?array $data = null): array
{
$clientToken = $this->getAuthenticationToken();
$this->info(
'Sending request to vault',
[
'method' => $method,
'url' => $url,
'data' => $data,
]
);
$options = [
'headers' => ['X-Vault-Token' => $clientToken],
];
if ($method === 'POST') {
$options['json'] = ['data' => $data];
}
$response = $this->httpClient->request(
$method,
$url,
$options
);
$this->info(
'Request succesfully send to vault',
[
'method' => $method,
'url' => $url,
'data' => $data,
]
);
if (
$response->getStatusCode() !== Response::HTTP_NO_CONTENT
&& $response->getStatusCode() !== Response::HTTP_OK
) {
throw new \Exception('Error ' . $response->getStatusCode());
}
if ($method === 'DELETE') {
return [];
}
return $response->toArray();
}
/**
* Send a multiplexed request to vault.
*
* @param string $method
* @param array<string,string> $urls indexed by their uuid
* @param null|array<mixed> $data
*
* @return array<string, mixed> $response data indexed by their uuid
*/
protected function sendMultiplexedRequest(string $method, array $urls, ?array $data = null): array
{
$clientToken = $this->getAuthenticationToken();
$options = [
'headers' => ['X-Vault-Token' => $clientToken],
];
if ($method === 'POST') {
$options['json'] = ['data' => $data];
}
$responses = [];
$responseData = [];
foreach ($urls as $uuid => $url) {
$responseData[$uuid] = [];
try {
$responses[] = $this->httpClient->request($method, $url, $options);
} catch (TransportExceptionInterface $ex) {
$this->error(
'Error while sending multiplexed request to vault, process continue',
['url' => $url, 'exception' => $ex]
);
continue;
}
}
foreach ($this->httpClient->stream($responses) as $response => $chunk) {
try {
if ($chunk->isFirst()) {
if ($response->getStatusCode() !== Response::HTTP_OK) {
$this->error(
message: 'Error HTTP CODE:' . $response->getStatusCode(),
context: ['url' => $response->getInfo('url'), 'expected_status_code' => Response::HTTP_OK]
);
continue;
}
}
if ($chunk->isLast()) {
foreach (array_keys($responseData) as $uuid) {
if (str_contains($response->getInfo('url'), $uuid)) {
$responseData[$uuid] = $response->toArray();
}
}
}
} catch (\Exception $ex) {
$this->error(
message: 'Error while processing multiplexed request to vault, process continue',
context: [
'url' => $response->getInfo('url'),
'exception' => $ex,
]
);
continue;
}
}
return $responseData;
}
}
| 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/Repository/ApiRepositoryTrait.php | centreon/src/Core/Common/Infrastructure/Repository/ApiRepositoryTrait.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the 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\Repository;
trait ApiRepositoryTrait
{
protected ?string $proxy = null;
protected ?string $url = null;
protected string $authenticationToken = '';
/** @var positive-int */
protected int $timeout = 60; // Default timeout
/** @var positive-int */
protected int $maxItemsByRequest = 100;
/** @var positive-int */
protected int $maxQueryStringLength = 2048;
public function setProxy(string $proxy): void
{
$this->proxy = $proxy;
}
public function setUrl(string $url): void
{
$this->url = rtrim($url, '/');
if (! str_starts_with($this->url, 'http')) {
$this->url = 'https://' . $this->url;
}
}
public function setAuthenticationToken(string $token): void
{
$this->authenticationToken = $token;
}
public function setTimeout(int $timeout): void
{
if ($timeout > 1) {
$this->timeout = $timeout;
}
}
public function setMaxItemsByRequest(int $maxItemsByRequest): void
{
if ($maxItemsByRequest > 1) {
$this->maxItemsByRequest = $maxItemsByRequest;
}
}
public function setMaxQueryStringLength(int $maxQueryStringLength): void
{
if ($maxQueryStringLength > 1) {
$this->maxQueryStringLength = $maxQueryStringLength;
}
}
}
| 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/Repository/ReadVaultRepository.php | centreon/src/Core/Common/Infrastructure/Repository/ReadVaultRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the 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\Repository;
use Centreon\Domain\Log\LoggerTrait;
use Core\Common\Application\Repository\ReadVaultRepositoryInterface;
use Core\Common\Application\UseCase\VaultTrait;
use Core\Security\Vault\Domain\Model\NewVaultConfiguration;
use Core\Security\Vault\Domain\Model\VaultConfiguration;
class ReadVaultRepository extends AbstractVaultRepository implements ReadVaultRepositoryInterface
{
use LoggerTrait;
use VaultTrait;
/**
* @inheritDoc
*/
public function findFromPath(string $path): array
{
if ($this->vaultConfiguration === null) {
throw new \LogicException('Vault not configured');
}
$customPathElements = explode('::', $path);
// remove vault key from path
array_pop($customPathElements);
// Keep only the uri from the path
$customPath = end($customPathElements);
$url = $this->vaultConfiguration->getAddress() . ':' . $this->vaultConfiguration->getPort()
. '/v1/' . $customPath;
$url = sprintf('%s://%s', parent::DEFAULT_SCHEME, $url);
$responseContent = $this->sendRequest('GET', $url);
if (is_array($responseContent) && isset($responseContent['data']['data'])) {
return $responseContent['data']['data'];
}
return [];
}
/**
* {@inheritDoc}
*
* This method will use multiplexing to get the content of multiple paths at once. and enhance performance for the
* case of thousands of paths.
*/
public function findFromPaths(array $paths): array
{
if ($this->vaultConfiguration === null) {
throw new \LogicException('Vault not configured');
}
$urls = [];
foreach ($paths as $resourceId => $path) {
$customPathElements = explode('::', $path);
$uuid = $this->getUuidFromPath($path);
// remove vault key from path
array_pop($customPathElements);
// Keep only the uri from the path
$customPath = end($customPathElements);
$url = $this->vaultConfiguration->getAddress() . ':' . $this->vaultConfiguration->getPort()
. '/v1/' . $customPath;
$url = sprintf('%s://%s', parent::DEFAULT_SCHEME, $url);
$urls[$uuid] = $url;
}
$responses = $this->sendMultiplexedRequest('GET', $urls);
$vaultData = [];
foreach ($responses as $uuid => $response) {
foreach ($paths as $resourceId => $path) {
if (str_contains($path, $uuid)) {
$data = $response['data']['data'];
$vaultData[$resourceId] = $data;
}
}
}
return $vaultData;
}
public function testVaultConnection(VaultConfiguration|NewVaultConfiguration $vaultConfiguration): bool
{
try {
$url = $vaultConfiguration->getAddress() . ':'
. $vaultConfiguration->getPort() . '/v1/auth/approle/login';
$url = sprintf('%s://%s', parent::DEFAULT_SCHEME, $url);
$body = [
'role_id' => $vaultConfiguration->getRoleId(),
'secret_id' => $vaultConfiguration->getSecretId(),
];
$loginResponse = $this->httpClient->request('POST', $url, ['json' => $body]);
$content = json_decode($loginResponse->getContent(), true);
} catch (\Exception $ex) {
$this->error('Could not login to vault');
return false;
}
/** @var array{auth?:array{client_token?:string}} $content */
return (bool) (isset($content['auth']['client_token']));
}
}
| 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/Repository/RepositoryTrait.php | centreon/src/Core/Common/Infrastructure/Repository/RepositoryTrait.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the 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\Repository;
/**
* This trait is here only to expose utility methods **only** to avoid duplicate code.
* The methods SHOULD be "Pure" functions.
*/
trait RepositoryTrait
{
/**
* Transform an empty string `''` in `null` value, otherwise keep the same string.
*
* @phpstan-pure
*
* @param string $string
*
* @return string|null
*/
public function emptyStringAsNull(string $string): ?string
{
return $string === '' ? null : $string;
}
/**
* Transform a timestamp integer into a valid \DateTimeImmutable.
*
* @param int $timestamp
*
* @throws \ValueError
*
* @return \DateTimeImmutable
*/
public function timestampToDateTimeImmutable(int $timestamp): \DateTimeImmutable
{
return \DateTimeImmutable::createFromFormat('U', (string) $timestamp)
?: throw new \ValueError('Unable to create a DateTimeImmutable from an integer.');
}
}
| 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/Command/AbstractMigrationCommand.php | centreon/src/Core/Common/Infrastructure/Command/AbstractMigrationCommand.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the 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\Command;
use Assert\AssertionFailedException;
use Core\Common\Infrastructure\Command\Exception\MigrationCommandException;
use Core\Proxy\Application\Repository\ReadProxyRepositoryInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\Question;
abstract class AbstractMigrationCommand extends Command
{
public const LOCAL_PLATFORM = 0;
public const TARGET_PLATFORM = 1;
private static ?string $proxy = null;
private static bool $isProxyAlreadyLoaded = false;
public function __construct(readonly private ReadProxyRepositoryInterface $readProxyRepository)
{
parent::__construct();
}
protected function setStyle(OutputInterface $output): void
{
$output->getFormatter()->setStyle(
'error',
new OutputFormatterStyle('red', '', ['bold'])
);
}
/**
* @param int $platform self::LOCAL_PLATFORM|self::TARGET_PLATFORM
* @param InputInterface $input
* @param OutputInterface $output
*
* @throws MigrationCommandException
*
* @return string
*/
protected function askAuthenticationToken(int $platform, InputInterface $input, OutputInterface $output): string
{
$question = match ($platform) {
self::LOCAL_PLATFORM => 'Local authentication token? ',
self::TARGET_PLATFORM => 'Target authentication token? ',
default => throw new \InvalidArgumentException('Please choose an available platform type'),
};
return $this->askQuestion($question, $input, $output);
}
protected function writeError(string $message, OutputInterface $output): void
{
$output->writeln("<error>{$message}</error>");
}
/**
* **Available formats:**.
*
* <<procotol>>://<<user>>:<<password>>@<<url>>:<<port>>
*
* <<procotol>>://<<user>>:<<password>>@<<url>>
*
* <<procotol>>://<<url>>:<<port>>
*
* <<procotol>>://<<url>>
*
* @throws AssertionFailedException
*
* @return string|null
*/
protected function getProxy(): ?string
{
if (! self::$isProxyAlreadyLoaded) {
$proxy = $this->readProxyRepository->getProxy();
self::$proxy = $proxy ? (string) $proxy : null;
}
self::$isProxyAlreadyLoaded = true;
return self::$proxy;
}
/**
* @param string $message Question to display
* @param InputInterface $input
* @param OutputInterface $output
*
* @throws MigrationCommandException
* @throws \Exception
*
* @return string Response
*/
protected function askQuestion(string $message, InputInterface $input, OutputInterface $output): string
{
/** @var QuestionHelper $helper */
$helper = $this->getHelper('question');
$tokenQuestion = new Question($message, '');
$tokenQuestion->setHidden(true);
/** @var string $response */
$response = $helper->ask($input, $output, $tokenQuestion);
if ($response === '') {
throw MigrationCommandException::tokenCannotBeEmpty();
}
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/Common/Infrastructure/Command/Exception/MigrationCommandException.php | centreon/src/Core/Common/Infrastructure/Command/Exception/MigrationCommandException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the 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\Command\Exception;
class MigrationCommandException extends \Exception
{
/**
* @return self
*/
public static function tokenCannotBeEmpty(): self
{
return new self(_('The token cannot be empty'));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceSeverity/Application/UseCase/UpdateServiceSeverity/UpdateServiceSeverity.php | centreon/src/Core/ServiceSeverity/Application/UseCase/UpdateServiceSeverity/UpdateServiceSeverity.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceSeverity\Application\UseCase\UpdateServiceSeverity;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ConflictResponse;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Application\Common\UseCase\PresenterInterface;
use Core\Common\Domain\TrimmedString;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\ServiceSeverity\Application\Exception\ServiceSeverityException;
use Core\ServiceSeverity\Application\Repository\ReadServiceSeverityRepositoryInterface;
use Core\ServiceSeverity\Application\Repository\WriteServiceSeverityRepositoryInterface;
use Core\ServiceSeverity\Domain\Model\ServiceSeverity;
use Core\ViewImg\Application\Repository\ReadViewImgRepositoryInterface;
final class UpdateServiceSeverity
{
use LoggerTrait;
public function __construct(
private readonly WriteServiceSeverityRepositoryInterface $writeServiceSeverityRepository,
private readonly ReadServiceSeverityRepositoryInterface $readServiceSeverityRepository,
private readonly ReadViewImgRepositoryInterface $readViewImgRepository,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepositoryInterface,
private readonly ContactInterface $user,
) {
}
/**
* @param UpdateServiceSeverityRequest $dto
* @param DefaultPresenter $presenter
* @param int $severityId
*/
public function __invoke(
UpdateServiceSeverityRequest $dto,
PresenterInterface $presenter,
int $severityId,
): void {
try {
if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_SERVICES_CATEGORIES_READ_WRITE)) {
$this->error(
"User doesn't have sufficient rights to edit service severities",
['user_id' => $this->user->getId()]
);
$presenter->setResponseStatus(
new ForbiddenResponse(ServiceSeverityException::editNotAllowed()->getMessage())
);
return;
}
if (! $this->user->isAdmin()
&& ! $this->readServiceSeverityRepository->existsByAccessGroups(
$severityId,
$this->readAccessGroupRepositoryInterface->findByContact($this->user)
)
) {
$this->error(
'Service severity not found',
['severity_id' => $severityId]
);
$presenter->setResponseStatus(new NotFoundResponse('Service severity'));
return;
}
if (null === ($severity = $this->readServiceSeverityRepository->findById($severityId))) {
$this->error(
'Service severity not found',
['severity_id' => $severityId]
);
$presenter->setResponseStatus(new NotFoundResponse('Service severity'));
return;
}
$this->validateNameOrFail($dto->name, $severity);
$this->validateIconOrFail($dto->iconId);
$severity->setName($dto->name);
$severity->setAlias($dto->alias);
$severity->setLevel($dto->level);
$severity->setIconId($dto->iconId);
$severity->setActivated($dto->isActivated);
$this->writeServiceSeverityRepository->update($severity);
$presenter->setResponseStatus(new NoContentResponse());
} catch (ServiceSeverityException $ex) {
$presenter->setResponseStatus(
match ($ex->getCode()) {
ServiceSeverityException::CODE_CONFLICT => new ConflictResponse($ex),
default => new ErrorResponse($ex),
}
);
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (AssertionFailedException $ex) {
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (\Throwable $ex) {
$presenter->setResponseStatus(
new ErrorResponse(ServiceSeverityException::editServiceSeverity($ex))
);
$this->error((string) $ex);
}
}
/**
* @param string $name
* @param ServiceSeverity $severity
*
* @throws ServiceSeverityException
*/
private function validateNameOrFail(string $name, ServiceSeverity $severity): void
{
if (
$name !== $severity->getName()
&& $this->readServiceSeverityRepository->existsByName(new TrimmedString($name))
) {
$this->error(
'Service severity name already exists',
['severity_name' => $name]
);
throw ServiceSeverityException::serviceNameAlreadyExists();
}
}
/**
* @param int $iconId
*
* @throws ServiceSeverityException
*/
private function validateIconOrFail(int $iconId): void
{
if (! $this->readViewImgRepository->existsOne($iconId)) {
$this->error(
'Service severity icon does not exist',
['icon_id' => $iconId]
);
throw ServiceSeverityException::iconDoesNotExist($iconId);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceSeverity/Application/UseCase/UpdateServiceSeverity/UpdateServiceSeverityRequest.php | centreon/src/Core/ServiceSeverity/Application/UseCase/UpdateServiceSeverity/UpdateServiceSeverityRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceSeverity\Application\UseCase\UpdateServiceSeverity;
final class UpdateServiceSeverityRequest
{
public string $name = '';
public string $alias = '';
public int $level = 0;
public int $iconId = 0;
public bool $isActivated = true;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceSeverity/Application/UseCase/AddServiceSeverity/AddServiceSeverityResponse.php | centreon/src/Core/ServiceSeverity/Application/UseCase/AddServiceSeverity/AddServiceSeverityResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceSeverity\Application\UseCase\AddServiceSeverity;
final class AddServiceSeverityResponse
{
public int $id = 0;
public string $name = '';
public string $alias = '';
public int $level = 0;
public int $iconId = 0;
public bool $isActivated = true;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceSeverity/Application/UseCase/AddServiceSeverity/AddServiceSeverityRequest.php | centreon/src/Core/ServiceSeverity/Application/UseCase/AddServiceSeverity/AddServiceSeverityRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceSeverity\Application\UseCase\AddServiceSeverity;
final class AddServiceSeverityRequest
{
public string $name = '';
public string $alias = '';
public int $level = 0;
public int $iconId = 0;
public bool $isActivated = true;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceSeverity/Application/UseCase/AddServiceSeverity/AddServiceSeverity.php | centreon/src/Core/ServiceSeverity/Application/UseCase/AddServiceSeverity/AddServiceSeverity.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceSeverity\Application\UseCase\AddServiceSeverity;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ConflictResponse;
use Core\Application\Common\UseCase\CreatedResponse;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Application\Common\UseCase\PresenterInterface;
use Core\Common\Domain\TrimmedString;
use Core\ServiceSeverity\Application\Exception\ServiceSeverityException;
use Core\ServiceSeverity\Application\Repository\ReadServiceSeverityRepositoryInterface;
use Core\ServiceSeverity\Application\Repository\WriteServiceSeverityRepositoryInterface;
use Core\ServiceSeverity\Domain\Model\NewServiceSeverity;
use Core\ServiceSeverity\Domain\Model\ServiceSeverity;
use Core\ServiceSeverity\Infrastructure\API\AddServiceSeverity\AddServiceSeverityPresenter;
use Core\ViewImg\Application\Repository\ReadViewImgRepositoryInterface;
final class AddServiceSeverity
{
use LoggerTrait;
public function __construct(
private readonly WriteServiceSeverityRepositoryInterface $writeServiceSeverityRepository,
private readonly ReadServiceSeverityRepositoryInterface $readServiceSeverityRepository,
private readonly ReadViewImgRepositoryInterface $readViewImgRepository,
private readonly ContactInterface $user,
) {
}
/**
* @param AddServiceSeverityRequest $request
* @param AddServiceSeverityPresenter $presenter
*/
public function __invoke(AddServiceSeverityRequest $request, PresenterInterface $presenter): void
{
try {
if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_SERVICES_CATEGORIES_READ_WRITE)) {
$this->error(
"User doesn't have sufficient rights to add service severities",
['user_id' => $this->user->getId()]
);
$presenter->setResponseStatus(
new ForbiddenResponse(ServiceSeverityException::addNotAllowed()->getMessage())
);
} elseif ($this->readServiceSeverityRepository->existsByName(new TrimmedString($request->name))) {
$this->error(
'Service severity name already exists',
['serviceseverity_name' => $request->name]
);
$presenter->setResponseStatus(
new ConflictResponse(ServiceSeverityException::serviceNameAlreadyExists())
);
} elseif (
$request->iconId === 0
|| ! $this->readViewImgRepository->existsOne($request->iconId)
) {
$this->error(
'Service severity icon does not exist',
['serviceseverity_name' => $request->name]
);
$presenter->setResponseStatus(
new ConflictResponse(ServiceSeverityException::iconDoesNotExist($request->iconId))
);
} else {
$newServiceSeverity = new NewServiceSeverity(
$request->name,
$request->alias,
$request->level,
$request->iconId,
);
$newServiceSeverity->setActivated($request->isActivated);
$serviceSeverityId = $this->writeServiceSeverityRepository->add($newServiceSeverity);
$serviceSeverity = $this->readServiceSeverityRepository->findById($serviceSeverityId);
$this->info('Add a new service severity', ['serviceseverity_id' => $serviceSeverityId]);
if (! $serviceSeverity) {
$presenter->setResponseStatus(
new ErrorResponse(ServiceSeverityException::errorWhileRetrievingJustCreated())
);
return;
}
$presenter->present(
new CreatedResponse($serviceSeverityId, $this->createResponse($serviceSeverity))
);
}
} catch (AssertionFailedException $ex) {
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (\Throwable $ex) {
$presenter->setResponseStatus(
new ErrorResponse(ServiceSeverityException::addServiceSeverity($ex))
);
$this->error((string) $ex);
}
}
/**
* @param ServiceSeverity|null $serviceSeverity
*
* @return AddServiceSeverityResponse
*/
private function createResponse(?ServiceSeverity $serviceSeverity): AddServiceSeverityResponse
{
$response = new AddServiceSeverityResponse();
if ($serviceSeverity !== null) {
$response->id = $serviceSeverity->getId();
$response->name = $serviceSeverity->getName();
$response->alias = $serviceSeverity->getAlias();
$response->level = $serviceSeverity->getLevel();
$response->iconId = $serviceSeverity->getIconId();
$response->isActivated = $serviceSeverity->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/ServiceSeverity/Application/UseCase/DeleteServiceSeverity/DeleteServiceSeverity.php | centreon/src/Core/ServiceSeverity/Application/UseCase/DeleteServiceSeverity/DeleteServiceSeverity.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceSeverity\Application\UseCase\DeleteServiceSeverity;
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\ServiceSeverity\Application\Exception\ServiceSeverityException;
use Core\ServiceSeverity\Application\Repository\ReadServiceSeverityRepositoryInterface;
use Core\ServiceSeverity\Application\Repository\WriteServiceSeverityRepositoryInterface;
final class DeleteServiceSeverity
{
use LoggerTrait;
public function __construct(
private readonly WriteServiceSeverityRepositoryInterface $writeServiceSeverityRepository,
private readonly ReadServiceSeverityRepositoryInterface $readServiceSeverityRepository,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepositoryInterface,
private ContactInterface $user,
) {
}
/**
* @param int $serviceSeverityId
* @param PresenterInterface $presenter
*/
public function __invoke(int $serviceSeverityId, PresenterInterface $presenter): void
{
try {
if ($this->user->isAdmin()) {
if ($this->readServiceSeverityRepository->exists($serviceSeverityId)) {
$this->writeServiceSeverityRepository->deleteById($serviceSeverityId);
$presenter->setResponseStatus(new NoContentResponse());
} else {
$this->error(
'Service severity not found',
['serviceseverity_id' => $serviceSeverityId]
);
$presenter->setResponseStatus(new NotFoundResponse('Service severity'));
}
} elseif ($this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_SERVICES_CATEGORIES_READ_WRITE)) {
$accessGroups = $this->readAccessGroupRepositoryInterface->findByContact($this->user);
if ($this->readServiceSeverityRepository->existsByAccessGroups($serviceSeverityId, $accessGroups)) {
$this->writeServiceSeverityRepository->deleteById($serviceSeverityId);
$presenter->setResponseStatus(new NoContentResponse());
$this->info('Delete a service severity', ['serviceseverity_id' => $serviceSeverityId]);
} else {
$this->error(
'Service severity not found',
['serviceseverity_id' => $serviceSeverityId, 'accessgroups' => $accessGroups]
);
$presenter->setResponseStatus(new NotFoundResponse('Service severity'));
}
} else {
$this->error(
"User doesn't have sufficient rights to delete service severities",
['user_id' => $this->user->getId()]
);
$presenter->setResponseStatus(
new ForbiddenResponse(ServiceSeverityException::deleteNotAllowed())
);
}
} catch (\Throwable $ex) {
$presenter->setResponseStatus(
new ErrorResponse(ServiceSeverityException::deleteServiceSeverity($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/ServiceSeverity/Application/UseCase/FindServiceSeverities/FindServiceSeveritiesResponse.php | centreon/src/Core/ServiceSeverity/Application/UseCase/FindServiceSeverities/FindServiceSeveritiesResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceSeverity\Application\UseCase\FindServiceSeverities;
final class FindServiceSeveritiesResponse
{
/**
* @var array<array{
* id: int,
* name: string,
* alias: string,
* level: int,
* iconId: int,
* isActivated: bool
* }>
*/
public array $serviceSeverities = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceSeverity/Application/UseCase/FindServiceSeverities/FindServiceSeverities.php | centreon/src/Core/ServiceSeverity/Application/UseCase/FindServiceSeverities/FindServiceSeverities.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceSeverity\Application\UseCase\FindServiceSeverities;
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\ServiceSeverity\Application\Exception\ServiceSeverityException;
use Core\ServiceSeverity\Application\Repository\ReadServiceSeverityRepositoryInterface;
use Core\ServiceSeverity\Domain\Model\ServiceSeverity;
final class FindServiceSeverities
{
use LoggerTrait;
/**
* @param ReadServiceSeverityRepositoryInterface $readServiceSeverityRepository
* @param ReadAccessGroupRepositoryInterface $readAccessGroupRepositoryInterface
* @param RequestParametersInterface $requestParameters
* @param ContactInterface $user
*/
public function __construct(
private ReadServiceSeverityRepositoryInterface $readServiceSeverityRepository,
private ReadAccessGroupRepositoryInterface $readAccessGroupRepositoryInterface,
private RequestParametersInterface $requestParameters,
private ContactInterface $user,
) {
}
/**
* @param PresenterInterface $presenter
*/
public function __invoke(PresenterInterface $presenter): void
{
try {
if ($this->user->isAdmin()) {
$serviceSeverities = $this->readServiceSeverityRepository->findByRequestParameter($this->requestParameters);
$presenter->present($this->createResponse($serviceSeverities));
} 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 severities',
['user' => $this->user->getName()]
);
$accessGroups = $this->readAccessGroupRepositoryInterface->findByContact($this->user);
$serviceSeverities = $this->readServiceSeverityRepository->findByRequestParameterAndAccessGroups(
$accessGroups,
$this->requestParameters
);
$presenter->present($this->createResponse($serviceSeverities));
} else {
$this->error(
"User doesn't have sufficient rights to see service severities",
['user_id' => $this->user->getId()]
);
$presenter->setResponseStatus(
new ForbiddenResponse(ServiceSeverityException::accessNotAllowed())
);
}
} catch (\Throwable $ex) {
$presenter->setResponseStatus(
new ErrorResponse(ServiceSeverityException::findServiceSeverities($ex))
);
$this->error((string) $ex);
}
}
/**
* @param ServiceSeverity[] $serviceSeverities
*
* @return FindServiceSeveritiesResponse
*/
private function createResponse(
array $serviceSeverities,
): FindServiceSeveritiesResponse {
$response = new FindServiceSeveritiesResponse();
foreach ($serviceSeverities as $serviceSeverity) {
$response->serviceSeverities[] = [
'id' => $serviceSeverity->getId(),
'name' => $serviceSeverity->getName(),
'alias' => $serviceSeverity->getAlias(),
'level' => $serviceSeverity->getLevel(),
'iconId' => $serviceSeverity->getIconId(),
'isActivated' => $serviceSeverity->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/ServiceSeverity/Application/Exception/ServiceSeverityException.php | centreon/src/Core/ServiceSeverity/Application/Exception/ServiceSeverityException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceSeverity\Application\Exception;
class ServiceSeverityException extends \Exception
{
public const CODE_CONFLICT = 1;
/**
* @return self
*/
public static function accessNotAllowed(): self
{
return new self(_('You are not allowed to access service severities'));
}
/**
* @return self
*/
public static function editNotAllowed(): self
{
return new self(_('You are not allowed to edit service severities'));
}
/**
* @param \Throwable $ex
*
* @return self
*/
public static function findServiceSeverities(\Throwable $ex): self
{
return new self(_('Error while searching for service severities'), 0, $ex);
}
/**
* @return self
*/
public static function deleteNotAllowed(): self
{
return new self(_('You are not allowed to delete service severities'));
}
/**
* @param \Throwable $ex
*
* @return self
*/
public static function deleteServiceSeverity(\Throwable $ex): self
{
return new self(_('Error while deleting service severity'), 0, $ex);
}
/**
* @param \Throwable $ex
*
* @return self
*/
public static function editServiceSeverity(\Throwable $ex): self
{
return new self(_('Error while editing service severity'), 0, $ex);
}
/**
* @param \Throwable $ex
*
* @return self
*/
public static function addServiceSeverity(\Throwable $ex): self
{
return new self(_('Error while creating service severity'), 0, $ex);
}
/**
* @return self
*/
public static function addNotAllowed(): self
{
return new self(_('You are not allowed to create service severities'));
}
/**
* @return self
*/
public static function errorWhileRetrievingJustCreated(): self
{
return new self(_('Error while retrieving recently created service severity'));
}
/**
* @return self
*/
public static function serviceNameAlreadyExists(): self
{
return new self(_('Service severity name already exists'), self::CODE_CONFLICT);
}
/**
* @param int $iconId
*
* @return self
*/
public static function iconDoesNotExist(int $iconId): self
{
return new self(
sprintf(_("The service severity icon with id '%d' does not exist"), $iconId),
self::CODE_CONFLICT
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceSeverity/Application/Repository/ReadServiceSeverityRepositoryInterface.php | centreon/src/Core/ServiceSeverity/Application/Repository/ReadServiceSeverityRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceSeverity\Application\Repository;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Common\Domain\TrimmedString;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Core\ServiceSeverity\Domain\Model\ServiceSeverity;
interface ReadServiceSeverityRepositoryInterface
{
/**
* Find all service severities.
*
* @param RequestParametersInterface $requestParameters
*
* @throws \Throwable
*
* @return ServiceSeverity[]
*/
public function findByRequestParameter(RequestParametersInterface $requestParameters): array;
/**
* Find all service severities by access groups.
*
* @param AccessGroup[] $accessGroups
* @param RequestParametersInterface $requestParameters
*
* @throws \Throwable
*
* @return ServiceSeverity[]
*/
public function findByRequestParameterAndAccessGroups(array $accessGroups, RequestParametersInterface $requestParameters): array;
/**
* Check existence of a service severity.
*
* @param int $serviceSeverityId
*
* @throws \Throwable
*
* @return bool
*/
public function exists(int $serviceSeverityId): bool;
/**
* Check existence of a service severity by access groups.
*
* @param int $serviceSeverityId
* @param AccessGroup[] $accessGroups
*
* @throws \Throwable
*
* @return bool
*/
public function existsByAccessGroups(int $serviceSeverityId, array $accessGroups): bool;
/**
* Check existence of a service severity by name.
*
* @param TrimmedString $serviceSeverityName
*
* @throws \Throwable
*
* @return bool
*/
public function existsByName(TrimmedString $serviceSeverityName): bool;
/**
* Find one service severity.
*
* @param int $serviceSeverityId
*
* @return ServiceSeverity|null
*/
public function findById(int $serviceSeverityId): ?ServiceSeverity;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceSeverity/Application/Repository/WriteServiceSeverityRepositoryInterface.php | centreon/src/Core/ServiceSeverity/Application/Repository/WriteServiceSeverityRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceSeverity\Application\Repository;
use Core\ServiceSeverity\Domain\Model\NewServiceSeverity;
use Core\ServiceSeverity\Domain\Model\ServiceSeverity;
interface WriteServiceSeverityRepositoryInterface
{
/**
* Delete service severity by id.
*
* @param int $serviceSeverityId
*/
public function deleteById(int $serviceSeverityId): void;
/**
* Add a service severity
* Return the id of the service severity.
*
* @param NewServiceSeverity $serviceSeverity
*
* @throws \Throwable
*
* @return int
*/
public function add(NewServiceSeverity $serviceSeverity): int;
/**
* Update a service severity.
*
* @param ServiceSeverity $severity
*
* @throws \Throwable
*/
public function update(ServiceSeverity $severity): 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/ServiceSeverity/Domain/Model/ServiceSeverity.php | centreon/src/Core/ServiceSeverity/Domain/Model/ServiceSeverity.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceSeverity\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
class ServiceSeverity
{
public const MAX_NAME_LENGTH = 200;
public const MAX_ALIAS_LENGTH = 200;
public const MIN_LEVEL_VALUE = -128;
public const MAX_LEVEL_VALUE = 127;
private string $shortName = '';
private bool $isActivated = true;
/**
* @param int $id
* @param string $name
* @param string $alias
* @param int $level
* @param int $iconId
*
* @throws AssertionFailedException
*/
public function __construct(
private readonly int $id,
private string $name,
private string $alias,
private int $level,
private int $iconId,
) {
$this->shortName = (new \ReflectionClass($this))->getShortName();
$this->setName($name);
$this->setAlias($alias);
$this->setIconId($iconId);
$this->setLevel($level);
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
public function getName(): string
{
return $this->name;
}
/**
* @param string $name
*
* @throws \Throwable
*/
public function setName(string $name): void
{
$name = trim($name);
Assertion::notEmptyString($name, $this->shortName . '::name');
Assertion::maxLength($name, self::MAX_NAME_LENGTH, $this->shortName . '::name');
$this->name = $name;
}
public function getAlias(): string
{
return $this->alias;
}
/**
* @param string $alias
*
* @throws \Throwable
*/
public function setAlias(string $alias): void
{
$alias = trim($alias);
Assertion::notEmptyString($alias, $this->shortName . '::alias');
Assertion::maxLength($alias, self::MAX_ALIAS_LENGTH, $this->shortName . '::alias');
$this->alias = $alias;
}
public function getLevel(): int
{
return $this->level;
}
/**
* @param int $level
*
* @throws \Throwable
*/
public function setLevel(int $level): void
{
Assertion::min($level, self::MIN_LEVEL_VALUE, $this->shortName . '::level');
Assertion::max($level, self::MAX_LEVEL_VALUE, $this->shortName . '::level');
$this->level = $level;
}
public function getIconId(): int
{
return $this->iconId;
}
/**
* @param int $iconId
*
* @throws \Throwable
*/
public function setIconId(int $iconId): void
{
Assertion::positiveInt($iconId, $this->shortName . '::iconId');
$this->iconId = $iconId;
}
public function isActivated(): bool
{
return $this->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/ServiceSeverity/Domain/Model/NewServiceSeverity.php | centreon/src/Core/ServiceSeverity/Domain/Model/NewServiceSeverity.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceSeverity\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
class NewServiceSeverity
{
public const MAX_NAME_LENGTH = 200;
public const MIN_NAME_LENGTH = 1;
public const MAX_ALIAS_LENGTH = 200;
public const MIN_ALIAS_LENGTH = 1;
public const MIN_LEVEL_VALUE = -128;
public const MAX_LEVEL_VALUE = 127;
protected bool $isActivated = true;
protected ?string $comment = null;
/**
* @param string $name
* @param string $alias
* @param int $level
* @param int $iconId FK
*
* @throws AssertionFailedException
*/
public function __construct(
protected string $name,
protected string $alias,
protected int $level,
protected int $iconId,
) {
$this->name = trim($name);
$this->alias = trim($alias);
$shortName = (new \ReflectionClass($this))->getShortName();
Assertion::maxLength($name, self::MAX_NAME_LENGTH, $shortName . '::name');
Assertion::minLength($name, self::MIN_NAME_LENGTH, $shortName . '::name');
Assertion::maxLength($alias, self::MAX_ALIAS_LENGTH, $shortName . '::alias');
Assertion::minLength($alias, self::MIN_ALIAS_LENGTH, $shortName . '::alias');
Assertion::min($level, self::MIN_LEVEL_VALUE, $shortName . '::level');
Assertion::max($level, self::MAX_LEVEL_VALUE, $shortName . '::level');
Assertion::positiveInt($iconId, "{$shortName}::iconId");
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @return string
*/
public function getAlias(): string
{
return $this->alias;
}
/**
* @return int
*/
public function getLevel(): int
{
return $this->level;
}
/**
* @return int
*/
public function getIconId(): int
{
return $this->iconId;
}
/**
* @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/ServiceSeverity/Infrastructure/Repository/DbReadServiceSeverityRepository.php | centreon/src/Core/ServiceSeverity/Infrastructure/Repository/DbReadServiceSeverityRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceSeverity\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\RequestParameters\Normalizer\BoolToEnumNormalizer;
use Core\ServiceSeverity\Application\Repository\ReadServiceSeverityRepositoryInterface;
use Core\ServiceSeverity\Domain\Model\ServiceSeverity;
use Utility\SqlConcatenator;
class DbReadServiceSeverityRepository extends AbstractRepositoryRDB implements ReadServiceSeverityRepositoryInterface
{
use LoggerTrait;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function findByRequestParameter(RequestParametersInterface $requestParameters): array
{
$this->info('Getting all service severities');
$concatenator = new SqlConcatenator();
$concatenator->withCalcFoundRows(true);
$concatenator->defineSelect(
<<<'SQL'
SELECT sc.sc_id, sc.sc_name, sc.sc_description, sc.sc_activate, sc.level, sc.icon_id
FROM `:db`.service_categories sc
SQL
);
return $this->retrieveServiceSeverities($concatenator, $requestParameters);
}
/**
* @inheritDoc
*/
public function findByRequestParameterAndAccessGroups(array $accessGroups, RequestParametersInterface $requestParameters): array
{
$this->info('Getting all service severities 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 severities are not filtered in ACLs, then user has access to ALL service severities
if (! $this->hasRestrictedAccessToServiceSeverities($accessGroupIds)) {
$this->info('Service severities access not filtered');
return $this->findByRequestParameter($requestParameters);
}
$concatenator = new SqlConcatenator();
$concatenator->withCalcFoundRows(true);
$concatenator->defineSelect(
<<<'SQL'
SELECT sc.sc_id, sc.sc_name, sc.sc_description, sc.sc_activate, sc.level, sc.icon_id
FROM `:db`.service_categories sc
INNER JOIN `:db`.acl_resources_sc_relations arsr
ON sc.sc_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
);
$concatenator->storeBindValueMultiple(':access_group_ids', $accessGroupIds, \PDO::PARAM_INT)
->appendWhere('ag.acl_group_id IN (:access_group_ids)');
return $this->retrieveServiceSeverities($concatenator, $requestParameters);
}
/**
* @inheritDoc
*/
public function exists(int $serviceSeverityId): bool
{
$this->info('Check existence of service severity with id #' . $serviceSeverityId);
$request = $this->translateDbName(
<<<'SQL'
SELECT 1
FROM `:db`.service_categories sc
WHERE sc.sc_id = :serviceSeverityId
AND sc.level IS NOT NULL
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':serviceSeverityId', $serviceSeverityId, \PDO::PARAM_INT);
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* @inheritDoc
*/
public function existsByAccessGroups(int $serviceSeverityId, array $accessGroups): bool
{
$this->info(
'Check existence of service severity by access groups',
['id' => $serviceSeverityId, 'accessgroups' => $accessGroups]
);
if ($accessGroups === []) {
$this->debug('Access groups array empty');
return false;
}
$concat = new SqlConcatenator();
$accessGroupIds = array_map(
fn ($accessGroup) => $accessGroup->getId(),
$accessGroups
);
// if service severities are not filtered in ACLs, then user has access to ALL service severities
if (! $this->hasRestrictedAccessToServiceSeverities($accessGroupIds)) {
$this->info('Service severities access not filtered');
return $this->exists($serviceSeverityId);
}
$request = $this->translateDbName(
<<<'SQL'
SELECT 1
FROM `:db`.service_categories sc
INNER JOIN `:db`.acl_resources_sc_relations arsr
ON sc.sc_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
);
$concat->appendWhere(
<<<'SQL'
WHERE sc.sc_id = :serviceSeverityId
AND sc.level IS NOT NULL
SQL
);
$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(':serviceSeverityId', $serviceSeverityId, \PDO::PARAM_INT);
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* @inheritDoc
*/
public function existsByName(TrimmedString $serviceSeverityName): bool
{
$this->info('Check existence of service severity with name ' . $serviceSeverityName);
$request = $this->translateDbName(
'SELECT 1 FROM `:db`.service_categories sc WHERE sc.sc_name = :serviceSeverityName'
);
$statement = $this->db->prepare($request);
$statement->bindValue(':serviceSeverityName', $serviceSeverityName->value, \PDO::PARAM_STR);
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* @inheritDoc
*/
public function findById(int $serviceSeverityId): ?ServiceSeverity
{
$this->info('Get a service severity with ID #' . $serviceSeverityId);
$request = $this->translateDbName(
<<<'SQL'
SELECT sc.sc_id, sc.sc_name, sc.sc_description, sc.sc_activate, sc.level, sc.icon_id
FROM `:db`.service_categories sc
WHERE sc.sc_id = :serviceSeverityId
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':serviceSeverityId', $serviceSeverityId, \PDO::PARAM_INT);
$statement->execute();
$result = $statement->fetch(\PDO::FETCH_ASSOC);
if ($result === false) {
return null;
}
/** @var array{
* sc_id: int,
* sc_name: string,
* sc_description: string,
* sc_activate: '0'|'1',
* level: int,
* icon_id: int
* } $result
*/
return $this->createServiceSeverityFromArray($result);
}
/**
* @param SqlConcatenator $concatenator
* @param RequestParametersInterface $requestParameters
*
* @return ServiceSeverity[]
*/
private function retrieveServiceSeverities(
SqlConcatenator $concatenator,
RequestParametersInterface $requestParameters,
): array {
// Exclude severities from the results
$concatenator->appendWhere('sc.level IS NOT NULL');
// Settup for search, pagination, order
$sqlTranslator = new SqlRequestParametersTranslator($requestParameters);
$sqlTranslator->setConcordanceArray([
'id' => 'sc.sc_id',
'name' => 'sc.sc_name',
'alias' => 'sc.sc_description',
'level' => 'sc.level',
'is_activated' => 'sc.sc_activate',
]);
$sqlTranslator->addNormalizer('is_activated', new BoolToEnumNormalizer());
$sqlTranslator->translateForConcatenator($concatenator);
$statement = $this->db->prepare($this->translateDbName($concatenator->__toString()));
$sqlTranslator->bindSearchValues($statement);
$concatenator->bindValuesToStatement($statement);
$statement->execute();
$sqlTranslator->calculateNumberOfRows($this->db);
$serviceSeverities = [];
while (is_array($result = $statement->fetch(\PDO::FETCH_ASSOC))) {
/** @var array{
* sc_id: int,
* sc_name: string,
* sc_description: string,
* sc_activate: '0'|'1',
* level: int,
* icon_id: int
* } $result */
$serviceSeverities[] = $this->createServiceSeverityFromArray($result);
}
return $serviceSeverities;
}
/**
* @param array{
* sc_id: int,
* sc_name: string,
* sc_description: string,
* sc_activate: '0'|'1',
* level: int,
* icon_id: int
* } $result
*
* @return ServiceSeverity
*/
private function createServiceSeverityFromArray(array $result): ServiceSeverity
{
$serviceSeverity = new ServiceSeverity(
$result['sc_id'],
$result['sc_name'],
$result['sc_description'],
$result['level'],
$result['icon_id'],
);
$serviceSeverity->setActivated((bool) $result['sc_activate']);
return $serviceSeverity;
}
/**
* Determine if service severities are filtered for given access group ids:
* - true: accessible service severities are filtered
* - false: accessible service severities are not filtered.
*
* @param int[] $accessGroupIds
*
* @phpstan-param non-empty-array<int> $accessGroupIds
*
* @return bool
*/
private function hasRestrictedAccessToServiceSeverities(array $accessGroupIds): bool
{
$concatenator = new SqlConcatenator();
$concatenator->defineSelect(
<<<'SQL'
SELECT 1
FROM `:db`.acl_resources_sc_relations arsr
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
);
$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();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceSeverity/Infrastructure/Repository/DbWriteServiceSeverityRepository.php | centreon/src/Core/ServiceSeverity/Infrastructure/Repository/DbWriteServiceSeverityRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceSeverity\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\ServiceSeverity\Application\Repository\WriteServiceSeverityRepositoryInterface;
use Core\ServiceSeverity\Domain\Model\NewServiceSeverity;
use Core\ServiceSeverity\Domain\Model\ServiceSeverity;
class DbWriteServiceSeverityRepository extends AbstractRepositoryRDB implements WriteServiceSeverityRepositoryInterface
{
use LoggerTrait;
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function deleteById(int $serviceSeverityId): void
{
$this->debug('Delete service severity', ['serviceSeverityId' => $serviceSeverityId]);
$request = $this->translateDbName(
<<<'SQL'
DELETE sc FROM `:db`.service_categories sc
WHERE sc.sc_id = :serviceSeverityId
AND sc.level IS NOT NULL
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':serviceSeverityId', $serviceSeverityId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @inheritDoc
*/
public function add(NewServiceSeverity $serviceSeverity): int
{
$this->debug('Add service severity', ['serviceSeverity' => $serviceSeverity]);
$request = $this->translateDbName(
<<<'SQL'
INSERT INTO `:db`.service_categories
(sc_name, sc_description, level, icon_id, sc_activate) VALUES
(:name, :alias, :level, :icon_id, :activate)
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':name', $serviceSeverity->getName(), \PDO::PARAM_STR);
$statement->bindValue(':alias', $serviceSeverity->getAlias(), \PDO::PARAM_STR);
$statement->bindValue(':level', $serviceSeverity->getLevel(), \PDO::PARAM_INT);
$statement->bindValue(':icon_id', $serviceSeverity->getIconId(), \PDO::PARAM_INT);
$statement->bindValue(':activate', (new BoolToEnumNormalizer())->normalize($serviceSeverity->isActivated()));
$statement->execute();
return (int) $this->db->lastInsertId();
}
/**
* @inheritDoc
*/
public function update(ServiceSeverity $severity): void
{
$request = $this->translateDbName(
<<<'SQL'
UPDATE `:db`.service_categories
SET
`sc_name` = :name,
`sc_description` = :alias,
`level` = :level,
`icon_id` = :icon_id,
`sc_activate` = :activate
WHERE sc_id = :severity_id
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':name', $severity->getName(), \PDO::PARAM_STR);
$statement->bindValue(':alias', $severity->getAlias(), \PDO::PARAM_STR);
$statement->bindValue(':level', $severity->getLevel(), \PDO::PARAM_INT);
$statement->bindValue(':icon_id', $severity->getIconId(), \PDO::PARAM_INT);
$statement->bindValue(':activate', (new BoolToEnumNormalizer())->normalize($severity->isActivated()));
$statement->bindValue(':severity_id', $severity->getId(), \PDO::PARAM_INT);
$statement->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceSeverity/Infrastructure/Repository/DbWriteServiceSeverityActionLogRepository.php | centreon/src/Core/ServiceSeverity/Infrastructure/Repository/DbWriteServiceSeverityActionLogRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceSeverity\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\ServiceSeverity\Application\Repository\ReadServiceSeverityRepositoryInterface;
use Core\ServiceSeverity\Application\Repository\WriteServiceSeverityRepositoryInterface;
use Core\ServiceSeverity\Domain\Model\NewServiceSeverity;
use Core\ServiceSeverity\Domain\Model\ServiceSeverity;
class DbWriteServiceSeverityActionLogRepository extends AbstractRepositoryRDB implements WriteServiceSeverityRepositoryInterface
{
use LoggerTrait;
private const SERVICE_SEVERITY_PROPERTIES_MAP = [
'name' => 'sc_name',
'alias' => 'sc_description',
'level' => 'sc_severity_level',
'iconId' => 'sc_severity_icon',
'isActivated' => 'sc_activate',
];
public function __construct(
private readonly WriteServiceSeverityRepositoryInterface $writeServiceSeverityRepository,
private readonly ReadServiceSeverityRepositoryInterface $readServiceSeverityRepository,
private readonly WriteActionLogRepositoryInterface $writeActionLogRepository,
private readonly ContactInterface $contact,
DatabaseConnection $db,
) {
$this->db = $db;
}
/**
* @inheritDoc
*/
public function deleteById(int $serviceSeverityId): void
{
$serviceSeverity = null;
try {
$serviceSeverity = $this->readServiceSeverityRepository->findById($serviceSeverityId);
if ($serviceSeverity === null) {
throw new RepositoryException('Service severity not found');
}
$this->writeServiceSeverityRepository->deleteById($serviceSeverityId);
$actionLog = new ActionLog(
ActionLog::OBJECT_TYPE_SERVICE_SEVERITY,
$serviceSeverity->getId(),
$serviceSeverity->getName(),
ActionLog::ACTION_TYPE_DELETE,
$this->contact->getId()
);
$this->writeActionLogRepository->addAction($actionLog);
} catch (\Throwable $ex) {
$this->error(
"Error while deleting service severity : {$ex->getMessage()}",
['serviceSeverity' => $serviceSeverity, 'trace' => $ex->getTraceAsString()]
);
throw $ex;
}
}
/**
* @inheritDoc
*/
public function add(NewServiceSeverity $serviceSeverity): int
{
try {
$serviceSeverityId = $this->writeServiceSeverityRepository->add($serviceSeverity);
$actionLog = new ActionLog(
ActionLog::OBJECT_TYPE_SERVICE_SEVERITY,
$serviceSeverityId,
$serviceSeverity->getName(),
ActionLog::ACTION_TYPE_ADD,
$this->contact->getId()
);
$actionLogId = $this->writeActionLogRepository->addAction($actionLog);
$actionLog->setId($actionLogId);
$details = $this->getServiceSeverityPropertiesAsArray($serviceSeverity);
$this->writeActionLogRepository->addActionDetails($actionLog, $details);
return $serviceSeverityId;
} catch (\Throwable $ex) {
$this->error(
"Error while adding service severity : {$ex->getMessage()}",
['serviceSeverity' => $serviceSeverity, 'trace' => $ex->getTraceAsString()]
);
throw $ex;
}
}
/**
* @inheritDoc
*/
public function update(ServiceSeverity $serviceSeverity): void
{
try {
$initialSeverity = $this->readServiceSeverityRepository->findById($serviceSeverity->getId());
if ($initialSeverity === null) {
throw new RepositoryException('Service severity not found');
}
$this->writeServiceSeverityRepository->update($serviceSeverity);
$diff = $this->getServiceSeverityDiff($initialSeverity, $serviceSeverity);
// If enable/disable has been changed
if (array_key_exists('sc_activate', $diff)) {
// If only the activation has been changed
if (count($diff) === 1) {
$actionLog = new ActionLog(
ActionLog::OBJECT_TYPE_SERVICE_SEVERITY,
$serviceSeverity->getId(),
$serviceSeverity->getName(),
(bool) $diff['sc_activate'] ? ActionLog::ACTION_TYPE_ENABLE : ActionLog::ACTION_TYPE_DISABLE,
$this->contact->getId()
);
$this->writeActionLogRepository->addAction($actionLog);
return;
}
// If other properties have been changed as well
$actionLog = new ActionLog(
ActionLog::OBJECT_TYPE_SERVICE_SEVERITY,
$serviceSeverity->getId(),
$serviceSeverity->getName(),
(bool) $diff['sc_activate'] ? ActionLog::ACTION_TYPE_ENABLE : ActionLog::ACTION_TYPE_DISABLE,
$this->contact->getId()
);
$this->writeActionLogRepository->addAction($actionLog);
// Log change action
unset($diff['sc_activate']);
$actionLog = new ActionLog(
ActionLog::OBJECT_TYPE_SERVICE_SEVERITY,
$serviceSeverity->getId(),
$serviceSeverity->getName(),
ActionLog::ACTION_TYPE_CHANGE,
$this->contact->getId()
);
$actionLogId = $this->writeActionLogRepository->addAction($actionLog);
$actionLog->setId($actionLogId);
$this->writeActionLogRepository->addActionDetails($actionLog, $diff);
return;
}
// Log change action if other properties have been changed without activation
$actionLog = new ActionLog(
ActionLog::OBJECT_TYPE_SERVICE_SEVERITY,
$serviceSeverity->getId(),
$serviceSeverity->getName(),
ActionLog::ACTION_TYPE_CHANGE,
$this->contact->getId()
);
$actionLogId = $this->writeActionLogRepository->addAction($actionLog);
$actionLog->setId($actionLogId);
$this->writeActionLogRepository->addActionDetails($actionLog, $diff);
} catch (\Throwable $ex) {
$this->error(
"Error while updating service severity : {$ex->getMessage()}",
['serviceSeverity' => $serviceSeverity, 'trace' => $ex->getTraceAsString()]
);
throw $ex;
}
}
/**
* @param NewServiceSeverity $serviceSeverity
*
* @return array<string,int|bool|string>
*/
private function getServiceSeverityPropertiesAsArray(NewServiceSeverity $serviceSeverity): array
{
$serviceSeverityPropertiesArray = [];
$reflection = new \ReflectionClass($serviceSeverity);
foreach ($reflection->getProperties() as $property) {
$value = $property->getValue($serviceSeverity);
if ($value === null) {
$value = '';
}
if ($value === false) {
$value = 0;
}
if (array_key_exists($property->getName(), self::SERVICE_SEVERITY_PROPERTIES_MAP)) {
$serviceSeverityPropertiesArray[self::SERVICE_SEVERITY_PROPERTIES_MAP[$property->getName()]] = $value;
}
}
return $serviceSeverityPropertiesArray;
}
/**
* @param ServiceSeverity $initialSeverity
* @param ServiceSeverity $updatedServiceSeverity
*
* @return array<string, string|int|bool>
*/
private function getServiceSeverityDiff(
ServiceSeverity $initialSeverity,
ServiceSeverity $updatedServiceSeverity,
): array {
$diff = [];
$reflection = new \ReflectionClass($initialSeverity);
foreach ($reflection->getProperties() as $property) {
$initialValue = $property->getValue($initialSeverity);
$updatedValue = $property->getValue($updatedServiceSeverity);
if ($initialValue !== $updatedValue) {
if (array_key_exists($property->getName(), self::SERVICE_SEVERITY_PROPERTIES_MAP)) {
$diff[self::SERVICE_SEVERITY_PROPERTIES_MAP[$property->getName()]] = $updatedValue;
}
}
}
return $diff;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceSeverity/Infrastructure/API/UpdateServiceSeverity/UpdateServiceSeverityController.php | centreon/src/Core/ServiceSeverity/Infrastructure/API/UpdateServiceSeverity/UpdateServiceSeverityController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceSeverity\Infrastructure\API\UpdateServiceSeverity;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\ServiceSeverity\Application\UseCase\UpdateServiceSeverity\UpdateServiceSeverity;
use Core\ServiceSeverity\Application\UseCase\UpdateServiceSeverity\UpdateServiceSeverityRequest;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class UpdateServiceSeverityController extends AbstractController
{
use LoggerTrait;
/**
* @param Request $request
* @param UpdateServiceSeverity $useCase
* @param DefaultPresenter $presenter
* @param int $serviceSeverityId
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
Request $request,
UpdateServiceSeverity $useCase,
DefaultPresenter $presenter,
int $serviceSeverityId,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
try {
/** @var array{
* name: string,
* alias: string,
* level: int,
* icon_id: int,
* is_activated?: bool
* } $data
*/
$data = $this->validateAndRetrieveDataSent($request, __DIR__ . '/UpdateServiceSeveritySchema.json');
} catch (\InvalidArgumentException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
return $presenter->show();
}
$serviceSeverityRequest = $this->createRequestDto($data);
$useCase($serviceSeverityRequest, $presenter, $serviceSeverityId);
return $presenter->show();
}
/**
* @param array{
* name: string,
* alias: string,
* level: int,
* icon_id: int,
* is_activated?: bool
* } $data
*
* @return UpdateServiceSeverityRequest
*/
private function createRequestDto(array $data): UpdateServiceSeverityRequest
{
$serviceSeverityRequest = new UpdateServiceSeverityRequest();
$serviceSeverityRequest->name = $data['name'];
$serviceSeverityRequest->alias = $data['alias'];
$serviceSeverityRequest->level = $data['level'];
$serviceSeverityRequest->iconId = $data['icon_id'];
$serviceSeverityRequest->isActivated = $data['is_activated'] ?? true;
return $serviceSeverityRequest;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceSeverity/Infrastructure/API/AddServiceSeverity/AddServiceSeverityController.php | centreon/src/Core/ServiceSeverity/Infrastructure/API/AddServiceSeverity/AddServiceSeverityController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceSeverity\Infrastructure\API\AddServiceSeverity;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\ServiceSeverity\Application\UseCase\AddServiceSeverity\AddServiceSeverity;
use Core\ServiceSeverity\Application\UseCase\AddServiceSeverity\AddServiceSeverityRequest;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class AddServiceSeverityController extends AbstractController
{
use LoggerTrait;
/**
* @param Request $request
* @param AddServiceSeverity $useCase
* @param AddServiceSeverityPresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
Request $request,
AddServiceSeverity $useCase,
AddServiceSeverityPresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
try {
/** @var array{
* name: string,
* alias: string,
* level: int,
* icon_id: int,
* is_activated?: bool
* } $data
*/
$data = $this->validateAndRetrieveDataSent($request, __DIR__ . '/AddServiceSeveritySchema.json');
} catch (\InvalidArgumentException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
return $presenter->show();
}
$serviceSeverityRequest = $this->createRequestDto($data);
$useCase($serviceSeverityRequest, $presenter);
return $presenter->show();
}
/**
* @param array{
* name: string,
* alias: string,
* level: int,
* icon_id: int,
* is_activated?: bool
* } $data
*
* @return AddServiceSeverityRequest
*/
private function createRequestDto(array $data): AddServiceSeverityRequest
{
$serviceSeverityRequest = new AddServiceSeverityRequest();
$serviceSeverityRequest->name = $data['name'];
$serviceSeverityRequest->alias = $data['alias'];
$serviceSeverityRequest->level = $data['level'];
$serviceSeverityRequest->iconId = $data['icon_id'];
$serviceSeverityRequest->isActivated = $data['is_activated'] ?? true;
return $serviceSeverityRequest;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceSeverity/Infrastructure/API/AddServiceSeverity/AddServiceSeverityPresenter.php | centreon/src/Core/ServiceSeverity/Infrastructure/API/AddServiceSeverity/AddServiceSeverityPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceSeverity\Infrastructure\API\AddServiceSeverity;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\CreatedResponse;
use Core\ServiceSeverity\Application\UseCase\AddServiceSeverity\AddServiceSeverityResponse;
class AddServiceSeverityPresenter extends AbstractPresenter
{
use LoggerTrait;
/**
* @inheritDoc
*/
public function present(mixed $data): void
{
if (
$data instanceof CreatedResponse
&& $data->getPayload() instanceof AddServiceSeverityResponse
) {
$payload = $data->getPayload();
$data->setPayload([
'id' => $payload->id,
'name' => $payload->name,
'alias' => $payload->alias,
'level' => $payload->level,
'icon_id' => $payload->iconId,
'is_activated' => $payload->isActivated,
]);
// NOT setting location as required route does not currently exist
}
parent::present($data);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceSeverity/Infrastructure/API/DeleteServiceSeverity/DeleteServiceSeverityController.php | centreon/src/Core/ServiceSeverity/Infrastructure/API/DeleteServiceSeverity/DeleteServiceSeverityController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceSeverity\Infrastructure\API\DeleteServiceSeverity;
use Centreon\Application\Controller\AbstractController;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\ServiceSeverity\Application\UseCase\DeleteServiceSeverity\DeleteServiceSeverity;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class DeleteServiceSeverityController extends AbstractController
{
/**
* @param int $serviceSeverityId
* @param DeleteServiceSeverity $useCase
* @param DefaultPresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
int $serviceSeverityId,
DeleteServiceSeverity $useCase,
DefaultPresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($serviceSeverityId, $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/ServiceSeverity/Infrastructure/API/FindServiceSeverities/FindServiceSeveritiesController.php | centreon/src/Core/ServiceSeverity/Infrastructure/API/FindServiceSeverities/FindServiceSeveritiesController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceSeverity\Infrastructure\API\FindServiceSeverities;
use Centreon\Application\Controller\AbstractController;
use Core\ServiceSeverity\Application\UseCase\FindServiceSeverities\FindServiceSeverities;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class FindServiceSeveritiesController extends AbstractController
{
/**
* @param FindServiceSeverities $useCase
* @param FindServiceSeveritiesPresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(FindServiceSeverities $useCase, FindServiceSeveritiesPresenter $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/ServiceSeverity/Infrastructure/API/FindServiceSeverities/FindServiceSeveritiesPresenter.php | centreon/src/Core/ServiceSeverity/Infrastructure/API/FindServiceSeverities/FindServiceSeveritiesPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceSeverity\Infrastructure\API\FindServiceSeverities;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\ServiceSeverity\Application\UseCase\FindServiceSeverities\FindServiceSeveritiesResponse;
class FindServiceSeveritiesPresenter extends AbstractPresenter
{
/**
* @param RequestParametersInterface $requestParameters
* @param PresenterFormatterInterface $presenterFormatter
*/
public function __construct(
private readonly RequestParametersInterface $requestParameters,
protected PresenterFormatterInterface $presenterFormatter,
) {
parent::__construct($presenterFormatter);
}
/**
* @param FindServiceSeveritiesResponse $data
*/
public function present(mixed $data): void
{
$result = [];
foreach ($data->serviceSeverities as $serviceSeverity) {
$result[] = [
'id' => $serviceSeverity['id'],
'name' => $serviceSeverity['name'],
'alias' => $serviceSeverity['alias'],
'level' => $serviceSeverity['level'],
'icon_id' => $serviceSeverity['iconId'],
'is_activated' => $serviceSeverity['isActivated'],
];
}
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/MonitoringServer/Model/MonitoringServer.php | centreon/src/Core/MonitoringServer/Model/MonitoringServer.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\MonitoringServer\Model;
use Assert\Assertion;
class MonitoringServer
{
public const ILLEGAL_CHARACTERS = '~!$%^&*"|\'<>?,()=';
public const DEFAULT_ENGINE_START_COMMAND = 'systemctl start centengine';
public const DEFAULT_ENGINE_STOP_COMMAND = 'systemctl stop centengine';
public const DEFAULT_ENGINE_RESTART_COMMAND = 'systemctl restart centengine';
public const DEFAULT_ENGINE_RELOAD_COMMAND = 'systemctl reload centengine';
public const DEFAULT_BROKER_RELOAD_COMMAND = 'systemctl reload cbd';
public const VALID_COMMAND_START_REGEX = '/^(?:service\s+[a-zA-Z0-9_-]+\s+start|systemctl\s+start\s+[a-zA-Z0-9_-]+)$/';
public const VALID_COMMAND_STOP_REGEX = '/^(?:service\s+[a-zA-Z0-9_-]+\s+stop|systemctl\s+stop\s+[a-zA-Z0-9_-]+)$/';
public const VALID_COMMAND_RESTART_REGEX = '/^(?:service\s+[a-zA-Z0-9_-]+\s+restart|systemctl\s+restart\s+[a-zA-Z0-9_-]+)$/';
public const VALID_COMMAND_RELOAD_REGEX = '/^(?:service\s+[a-zA-Z0-9_-]+\s+reload|systemctl\s+reload\s+[a-zA-Z0-9_-]+)$/';
public function __construct(
private readonly int $id,
private string $name,
private ?string $engineStartCommand = null,
private ?string $engineStopCommand = null,
private ?string $engineRestartCommand = null,
private ?string $engineReloadCommand = null,
private ?string $brokerReloadCommand = null,
) {
$this->name = trim($name);
Assertion::notEmpty($this->name);
}
public function getId(): int
{
return $this->id;
}
public function getName(): string
{
return $this->name;
}
public function getEngineStartCommand(): ?string
{
return $this->engineStartCommand;
}
public function getEngineStopCommand(): ?string
{
return $this->engineStopCommand;
}
public function getEngineRestartCommand(): ?string
{
return $this->engineRestartCommand;
}
public function getEngineReloadCommand(): ?string
{
return $this->engineReloadCommand;
}
public function getBrokerReloadCommand(): ?string
{
return $this->brokerReloadCommand;
}
public function update(
string $name,
?string $engineStartCommand,
?string $engineStopCommand,
?string $engineReloadCommand,
?string $engineRestartCommand,
?string $brokerReloadCommand,
): void {
Assertion::notEmpty($name);
Assertion::nullOrRegex($engineStartCommand, self::VALID_COMMAND_START_REGEX);
Assertion::nullOrRegex($engineStopCommand, self::VALID_COMMAND_STOP_REGEX);
Assertion::nullOrRegex($engineReloadCommand, self::VALID_COMMAND_RELOAD_REGEX);
Assertion::nullOrRegex($engineRestartCommand, self::VALID_COMMAND_RESTART_REGEX);
Assertion::nullOrRegex($brokerReloadCommand, self::VALID_COMMAND_RELOAD_REGEX);
$this->name = $name;
$this->engineStartCommand = $engineStartCommand;
$this->engineStopCommand = $engineStopCommand;
$this->engineReloadCommand = $engineReloadCommand;
$this->engineRestartCommand = $engineRestartCommand;
$this->brokerReloadCommand = $brokerReloadCommand;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/MonitoringServer/Application/UseCase/UpdateMonitoringServer/UpdateMonitoringServerRequest.php | centreon/src/Core/MonitoringServer/Application/UseCase/UpdateMonitoringServer/UpdateMonitoringServerRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\MonitoringServer\Application\UseCase\UpdateMonitoringServer;
final readonly class UpdateMonitoringServerRequest
{
public function __construct(
public int $id,
public string $name,
public ?string $engineStartCommand,
public ?string $engineStopCommand,
public ?string $engineRestartCommand,
public ?string $engineReloadCommand,
public ?string $brokerReloadCommand,
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/MonitoringServer/Application/UseCase/UpdateMonitoringServer/UpdateMonitoringServer.php | centreon/src/Core/MonitoringServer/Application/UseCase/UpdateMonitoringServer/UpdateMonitoringServer.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\MonitoringServer\Application\UseCase\UpdateMonitoringServer;
use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Core\MonitoringServer\Application\Repository\WriteMonitoringServerRepositoryInterface;
final readonly class UpdateMonitoringServer
{
public function __construct(
private WriteMonitoringServerRepositoryInterface $writeRepository,
private ReadMonitoringServerRepositoryInterface $readRepository,
) {
}
public function __invoke(UpdateMonitoringServerRequest $request): void
{
$monitoringServer = $this->readRepository->get($request->id);
$monitoringServer->update(
name: $request->name,
engineStartCommand: $request->engineStartCommand,
engineStopCommand: $request->engineStopCommand,
engineRestartCommand: $request->engineRestartCommand,
engineReloadCommand: $request->engineReloadCommand,
brokerReloadCommand: $request->brokerReloadCommand
);
$this->writeRepository->update($monitoringServer);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/MonitoringServer/Application/Repository/ReadMonitoringServerRepositoryInterface.php | centreon/src/Core/MonitoringServer/Application/Repository/ReadMonitoringServerRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\MonitoringServer\Application\Repository;
use Centreon\Domain\Exception\EntityNotFoundException;
use Core\MonitoringServer\Model\MonitoringServer;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
interface ReadMonitoringServerRepositoryInterface
{
/**
* Determine if a monitoring server exists by its ID.
*
* @param int $monitoringServerId
*
* @return bool
*/
public function exists(int $monitoringServerId): bool;
/**
* Determine if a monitoring server exists by its ID and access groups.
*
* @param int $monitoringServerId
* @param AccessGroup[] $accessGroups
*
* @return bool
*/
public function existsByAccessGroups(int $monitoringServerId, array $accessGroups): bool;
/**
* Determine if monitoring servers exist by their IDs.
* Return the ids found.
*
* @param int[] $monitoringServerIds
*
* @return int[]
*/
public function exist(array $monitoringServerIds): array;
/**
* Determine if monitoring servers exist by their IDs and access groups.
* Return the ids found.
*
* @param int[] $monitoringServerIds
* @param AccessGroup[] $accessGroups
*
* @return int[]
*/
public function existByAccessGroups(array $monitoringServerIds, array $accessGroups): array;
/**
* Get a monitoring server by its associated host ID.
*
* @param int $hostId
*
* @return MonitoringServer|null
*/
public function findByHost(int $hostId): ?MonitoringServer;
/**
* Get monitoring servers by their IDs.
*
* @param int[] $ids
*
* @return MonitoringServer[]
*/
public function findByIds(array $ids): array;
/**
* Retrieves monitoring servers IDs by their associated host IDs.
*
* @param int[] $hostIds
*
* @return int[] The list of distinct server IDs
*/
public function findByHostsIds(array $hostIds): array;
/**
* Gets a monitoring server if it is a central server from the list of IDs.
*
* @param int[] $ids
*
* @return MonitoringServer|null
*/
public function findCentralByIds(array $ids): ?MonitoringServer;
/**
* Find all the Monitoring Servers.
*
* @return MonitoringServer[]
*/
public function findAll(): array;
/**
* Get a monitoring server.
*
* @param int $monitoringServerId
*
* @throws EntityNotFoundException when no Monitoring server are found
* @return MonitoringServer
*/
public function get(int $monitoringServerId): MonitoringServer;
/**
* Check if the monitoring server is ready for encryption.
*
* @param int $monitoringServerId
*
* @return bool
*/
public function isEncryptionReady(int $monitoringServerId): 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/MonitoringServer/Application/Repository/WriteMonitoringServerRepositoryInterface.php | centreon/src/Core/MonitoringServer/Application/Repository/WriteMonitoringServerRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\MonitoringServer\Application\Repository;
use Core\MonitoringServer\Model\MonitoringServer;
interface WriteMonitoringServerRepositoryInterface
{
/**
* Define the monitoring server as changed since its last configuration export.
*
* @param int $monitoringServerId
*/
public function notifyConfigurationChange(int $monitoringServerId): void;
/**
* Notify the monitoring servers as changed.
*
* @param int[] $monitoringServerIds
*/
public function notifyConfigurationChanges(array $monitoringServerIds): void;
/**
* Update a monitoring server.
*
* @param MonitoringServer $monitoringServer
*/
public function update(MonitoringServer $monitoringServer): void;
/**
* Update the encryption readiness of Monitoring Server configuration,
* based on the value of the Monitoring Server readiness in real time.
*
* This ensure that the configuration is always up to date with the realtime.
*/
public function updateAllEncryptionReadyFromRealtime(): 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/MonitoringServer/Infrastructure/Repository/DbReadMonitoringServerRepository.php | centreon/src/Core/MonitoringServer/Infrastructure/Repository/DbReadMonitoringServerRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\MonitoringServer\Infrastructure\Repository;
use Assert\AssertionFailedException;
use Centreon\Domain\Exception\EntityNotFoundException;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait;
use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Core\MonitoringServer\Model\MonitoringServer;
use Utility\SqlConcatenator;
/**
* @phpstan-type MSResultSet array{
* id: int,
* name: string,
* engine_start_command ?: string|null,
* engine_stop_command ?: string|null,
* engine_restart_command ?: string|null,
* engine_reload_command ?: string|null,
* broker_reload_command ?: string|null
* }
*/
class DbReadMonitoringServerRepository extends AbstractRepositoryRDB implements ReadMonitoringServerRepositoryInterface
{
use MonitoringServerRepositoryTrait;
use LoggerTrait;
use SqlMultipleBindTrait;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function exists(int $monitoringServerId): bool
{
$this->debug('Check existence of monitoring server with ID #' . $monitoringServerId);
$request = $this->translateDbName(
<<<'SQL'
SELECT 1
FROM `:db`.`nagios_server`
WHERE `id` = :monitoringServerId
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':monitoringServerId', $monitoringServerId, \PDO::PARAM_INT);
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* @inheritDoc
*/
public function existsByAccessGroups(int $monitoringServerId, array $accessGroups): bool
{
$this->debug(
'Check existence of monitoring server with',
['id' => $monitoringServerId, 'access_groups' => $accessGroups]
);
if ($accessGroups === []) {
$this->debug('Access groups array is empty');
return false;
}
$accessGroupIds = array_map(
fn ($accessGroup) => $accessGroup->getId(),
$accessGroups
);
if (! $this->hasRestrictedAccessToMonitoringServers($accessGroupIds)) {
return $this->exists($monitoringServerId);
}
[$bindValues, $bindQuery] = $this->createMultipleBindQuery($accessGroupIds, ':access_group_id_');
$request = $this->translateDbName(
<<<SQL
SELECT 1
FROM `:db`.`nagios_server` ns
INNER JOIN `:db`.`acl_resources_poller_relations` arpr
ON arpr.`poller_id` = ns.`id`
INNER JOIN `:db`.`acl_res_group_relations` argr
ON argr.`acl_res_id` = arpr.`acl_res_id`
INNER JOIN `:db`.`acl_groups` ag
ON ag.`acl_group_id` = argr.`acl_group_id`
WHERE `id` = :monitoring_server_id
AND ag.`acl_group_id` IN ({$bindQuery})
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':monitoring_server_id', $monitoringServerId, \PDO::PARAM_INT);
foreach ($bindValues as $bindParam => $bindValue) {
$statement->bindValue($bindParam, $bindValue, \PDO::PARAM_INT);
}
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* @inheritDoc
*/
public function exist(array $monitoringServerIds): array
{
[$bindValues, $bindQuery] = $this->createMultipleBindQuery(
$monitoringServerIds,
':monitoringServerIds_'
);
$statement = $this->db->prepare($this->translateDbName(
<<<SQL
SELECT id
FROM `:db`.`nagios_server`
WHERE `id` IN ({$bindQuery})
SQL
));
foreach ($bindValues as $bindParam => $bindValue) {
$statement->bindValue($bindParam, $bindValue, \PDO::PARAM_INT);
}
$statement->execute();
return $statement->fetchAll(\PDO::FETCH_COLUMN);
}
/**
* @inheritDoc
*/
public function existByAccessGroups(array $monitoringServerIds, array $accessGroups): array
{
if ($accessGroups === []) {
return [];
}
$accessGroupIds = array_map(
fn ($accessGroup) => $accessGroup->getId(),
$accessGroups
);
if (! $this->hasRestrictedAccessToMonitoringServers($accessGroupIds)) {
return $this->exist($monitoringServerIds);
}
[$bindValuesPollerIds, $bindQueryPollerIds] = $this->createMultipleBindQuery(
$monitoringServerIds,
':monitoringServerIds_'
);
[$bindValuesACLs, $bindQueryACLs] = $this->createMultipleBindQuery($accessGroupIds, ':accessGroupIds_');
$statement = $this->db->prepare($this->translateDbName(
<<<SQL
SELECT arpr.`poller_id`
FROM `:db`.`acl_resources_poller_relations` arpr
INNER JOIN `:db`.`acl_res_group_relations` argr
ON argr.`acl_res_id` = arpr.`acl_res_id`
WHERE arpr.`poller_id` IN ({$bindQueryPollerIds})
AND argr.`acl_group_id` IN ({$bindQueryACLs})
SQL
));
$bindValues = [...$bindValuesPollerIds, ...$bindValuesACLs];
foreach ($bindValues as $bindParam => $bindValue) {
$statement->bindValue($bindParam, $bindValue, \PDO::PARAM_INT);
}
$statement->execute();
return $statement->fetchAll(\PDO::FETCH_COLUMN);
}
public function findByHost(int $hostId): ?MonitoringServer
{
$request = $this->translateDbName(
<<<'SQL'
SELECT `id`, `name`
FROM `:db`.`nagios_server` ns
INNER JOIN `:db`.`ns_host_relation` ns_hrel
ON ns_hrel.nagios_server_id = ns.id
WHERE ns_hrel.host_host_id = :host_id
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':host_id', $hostId, \PDO::PARAM_INT);
$statement->execute();
/** @var MSResultSet|false */
$data = $statement->fetch(\PDO::FETCH_ASSOC);
return $data ? $this->createMonitoringServerFromArray($data) : null;
}
/**
* @inheritDoc
*/
public function findByIds(array $ids): array
{
if ($ids === []) {
return $ids;
}
$concatenator = new SqlConcatenator();
$concatenator->defineSelect(
<<<'SQL'
SELECT
`id`,
`name`
FROM `:db`.`nagios_server` ns
WHERE ns.id IN (:ids)
SQL
);
$concatenator->storeBindValueMultiple(':ids', $ids, \PDO::PARAM_INT);
$statement = $this->db->prepare($this->translateDbName($concatenator->__toString()));
$concatenator->bindValuesToStatement($statement);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
$monitoringServers = [];
foreach ($statement as $row) {
/** @var MSResultSet $row */
$monitoringServers[] = $this->createMonitoringServerFromArray($row);
}
return $monitoringServers;
}
/**
* @inheritDoc
*/
public function findByHostsIds(array $hostIds): array
{
if ($hostIds === []) {
return [];
}
[$bindValues, $bindQuery] = $this->createMultipleBindQuery($hostIds, ':host_id_');
$request = $this->translateDbName(
<<<SQL
SELECT DISTINCT(phr.nagios_server_id)
FROM `:db`.`ns_host_relation` phr
JOIN `:db`.`host` ON host.host_id = phr.host_host_id
WHERE host.host_activate = '1'
AND phr.host_host_id IN ({$bindQuery})
SQL
);
$statement = $this->db->prepare($request);
foreach ($bindValues as $bindParam => $bindValue) {
$statement->bindValue($bindParam, $bindValue, \PDO::PARAM_INT);
}
$statement->execute();
return $statement->fetchAll(\PDO::FETCH_COLUMN);
}
/**
* @inheritDoc
*/
public function findCentralByIds(array $ids): ?MonitoringServer
{
if ($ids === []) {
return null;
}
[$bindValues, $bindQuery] = $this->createMultipleBindQuery($ids, ':poller_id_');
$statement = $this->db->prepare($this->translateDbName(
<<<SQL
SELECT
ng.`id`,
ng.`name`
FROM `:db`.`nagios_server` ng
WHERE ng.`id` IN ({$bindQuery})
AND ng.`localhost` = '1'
AND NOT EXISTS (
SELECT 1
FROM `:db`.`remote_servers` rs
WHERE rs.server_id = ng.id
)
SQL
));
foreach ($bindValues as $bindParam => $bindValue) {
$statement->bindValue($bindParam, $bindValue, \PDO::PARAM_INT);
}
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
/** @var MSResultSet|false */
$data = $statement->fetch(\PDO::FETCH_ASSOC);
return $data ? $this->createMonitoringServerFromArray($data) : null;
}
public function findAll(): array
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
SELECT
id,
name,
engine_start_command,
engine_stop_command,
engine_restart_command,
engine_reload_command,
broker_reload_command
FROM `:db`.`nagios_server`
SQL
));
$statement->execute();
$monitoringServers = [];
foreach ($statement->fetchAll(\PDO::FETCH_ASSOC) as $result) {
$monitoringServers[] = $this->createMonitoringServerFromArray($result);
}
return $monitoringServers;
}
public function get(int $monitoringServerId): MonitoringServer
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
SELECT
id,
name,
engine_start_command,
engine_stop_command,
engine_restart_command,
engine_reload_command,
broker_reload_command
FROM `:db`.`nagios_server`
WHERE id = :monitoringServerId
SQL
));
$statement->bindValue(':monitoringServerId', $monitoringServerId, \PDO::PARAM_INT);
$statement->execute();
/** @var MSResultSet|false */
$data = $statement->fetch(\PDO::FETCH_ASSOC);
return $data
? $this->createMonitoringServerFromArray($data)
: throw new EntityNotFoundException(sprintf('Monitoring Server [%d] does not exist', $monitoringServerId));
}
public function isEncryptionReady(int $monitoringServerId): bool
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
SELECT 1
FROM `:dbstg`.`instances`
WHERE instance_id = :monitoringServerId
AND is_encryption_ready = 1
SQL
));
$statement->bindValue(':monitoringServerId', $monitoringServerId, \PDO::PARAM_INT);
$statement->execute();
if ($statement->fetchColumn()) {
return true;
}
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
SELECT 1
FROM `:db`.`nagios_server`
WHERE id = :monitoringServerId
AND is_encryption_ready = 1
SQL
));
$statement->bindValue(':monitoringServerId', $monitoringServerId, \PDO::PARAM_INT);
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* @param MSResultSet $result
*
* @throws AssertionFailedException
*
* @return MonitoringServer
*/
private function createMonitoringServerFromArray(array $result): MonitoringServer
{
return new MonitoringServer(
id: $result['id'],
name: $result['name'],
engineStartCommand: $result['engine_start_command'] ?? null,
engineStopCommand: $result['engine_stop_command'] ?? null,
engineReloadCommand: $result['engine_reload_command'] ?? null,
engineRestartCommand: $result['engine_restart_command'] ?? null,
brokerReloadCommand: $result['broker_reload_command'] ?? null,
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/MonitoringServer/Infrastructure/Repository/MonitoringServerRepositoryTrait.php | centreon/src/Core/MonitoringServer/Infrastructure/Repository/MonitoringServerRepositoryTrait.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\MonitoringServer\Infrastructure\Repository;
use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait;
trait MonitoringServerRepositoryTrait
{
use SqlMultipleBindTrait;
/**
* @param int[] $accessGroupIds
*
* @return bool
*/
public function hasRestrictedAccessToMonitoringServers(array $accessGroupIds): bool
{
if ($accessGroupIds === []) {
return false;
}
[$bindValues, $bindQuery] = $this->createMultipleBindQuery($accessGroupIds, ':access_group_id_');
$request = <<<SQL
SELECT 1
FROM `:db`.acl_resources_poller_relations arpr
INNER JOIN `:db`.acl_resources res
ON res.acl_res_id = arpr.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 $bindParam => $bindValue) {
$statement->bindValue($bindParam, $bindValue, \PDO::PARAM_INT);
}
$statement->execute();
return (bool) $statement->fetchColumn();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/MonitoringServer/Infrastructure/Repository/DbWriteMonitoringServerRepository.php | centreon/src/Core/MonitoringServer/Infrastructure/Repository/DbWriteMonitoringServerRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\MonitoringServer\Infrastructure\Repository;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait;
use Core\MonitoringServer\Application\Repository\WriteMonitoringServerRepositoryInterface;
use Core\MonitoringServer\Model\MonitoringServer;
class DbWriteMonitoringServerRepository extends AbstractRepositoryRDB implements WriteMonitoringServerRepositoryInterface
{
use LoggerTrait;
use SqlMultipleBindTrait;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function notifyConfigurationChange(int $monitoringServerId): void
{
$this->debug('Signal configuration change on monitoring server with ID #' . $monitoringServerId);
$request = $this->translateDbName(
<<<'SQL'
UPDATE `:db`.`nagios_server`
SET `updated` = '1'
WHERE `id` = :monitoringServerId
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':monitoringServerId', $monitoringServerId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @inheritDoc
*/
public function notifyConfigurationChanges(array $monitoringServerIds): void
{
if ($monitoringServerIds === []) {
return;
}
$this->debug('Signal configuration change on monitoring servers with IDs ' . implode(', ', $monitoringServerIds));
[$bindValues, $bindQuery] = $this->createMultipleBindQuery($monitoringServerIds, ':monitoring_server_id_');
$request = $this->translateDbName(
<<<SQL
UPDATE `:db`.`nagios_server`
SET `updated` = '1'
WHERE `id` IN ({$bindQuery})
SQL
);
$statement = $this->db->prepare($request);
foreach ($bindValues as $bindParam => $bindValue) {
$statement->bindValue($bindParam, $bindValue, \PDO::PARAM_INT);
}
$statement->execute();
}
public function update(MonitoringServer $monitoringServer): void
{
$request = $this->translateDbName(
<<<'SQL'
UPDATE `:db`.`nagios_server`
SET `name` = :name,
`engine_reload_command` = :engineReloadCommand,
`engine_restart_command` = :engineRestartCommand,
`engine_stop_command` = :engineStopCommand,
`engine_start_command` = :engineStartCommand,
`broker_reload_command` = :brokerReloadCommand
WHERE `id` = :monitoringServerId
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':name', $monitoringServer->getName(), \PDO::PARAM_STR);
$statement->bindValue(':engineReloadCommand', $monitoringServer->getEngineReloadCommand(), \PDO::PARAM_STR);
$statement->bindValue(':engineRestartCommand', $monitoringServer->getEngineRestartCommand(), \PDO::PARAM_STR);
$statement->bindValue(':engineStopCommand', $monitoringServer->getEngineStopCommand(), \PDO::PARAM_STR);
$statement->bindValue(':engineStartCommand', $monitoringServer->getEngineStartCommand(), \PDO::PARAM_STR);
$statement->bindValue(':brokerReloadCommand', $monitoringServer->getBrokerReloadCommand(), \PDO::PARAM_STR);
$statement->bindValue(':monitoringServerId', $monitoringServer->getId(), \PDO::PARAM_INT);
$statement->execute();
}
public function updateAllEncryptionReadyFromRealtime(): void
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
UPDATE `:db`.nagios_server ns
INNER JOIN `:dbstg`.instances i
ON ns.id = i.instance_id
SET ns.is_encryption_ready = i.is_encryption_ready
SQL
));
$statement->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/MonitoringServer/Infrastructure/Command/CleanEngineBrokerCommandsCommand.php | centreon/src/Core/MonitoringServer/Infrastructure/Command/CleanEngineBrokerCommandsCommand.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\MonitoringServer\Infrastructure\Command;
use Centreon\Domain\Log\LoggerTrait;
use Core\Common\Domain\Exception\RepositoryException;
use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Core\MonitoringServer\Application\UseCase\UpdateMonitoringServer\UpdateMonitoringServer;
use Core\MonitoringServer\Application\UseCase\UpdateMonitoringServer\UpdateMonitoringServerRequest;
use Core\MonitoringServer\Infrastructure\Command\CleanEngineBrokerCommandsCommand\ValidMonitoringServerDto;
use Core\MonitoringServer\Model\MonitoringServer;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\Validator\ValidatorInterface;
#[AsCommand(
name: 'web:monitoring-server:clean-engine-broker-command',
description: 'Command to clean syntax of engine and broker syntaxes',
help: 'This command will check the engine and broker commands of all Monitoring Servers '
. 'and will fix them if they are not valid.'
. PHP_EOL . 'If dry run mode is set, it will only list the Monitoring Servers with invalid commands.'
. PHP_EOL . 'If dry run mode is not set, it will fix the invalid commands.' . PHP_EOL
. PHP_EOL . 'By default, the command will be updated as follows:'
. PHP_EOL . ' - Engine Reload Command: will be set to "systemctl reload centengine"'
. PHP_EOL . ' - Engine Restart Command: will be set to "systemctl restart centengine"'
. PHP_EOL . ' - Engine Stop Command: will be set to "systemctl stop centengine"'
. PHP_EOL . ' - Engine Start Command: will be set to "systemctl start centengine"'
. PHP_EOL . ' - Broker Reload Command: will be set to "systemctl reload cbd"' . PHP_EOL
. PHP_EOL . 'You can also change those commands manually by using the following regex patterns:'
. PHP_EOL . "^(?:service\s+[a-zA-Z0-9_-]+\s+(?:start|stop|restart|reload)|"
. "systemctl\s+(?:start|stop|restart|reload)\s+[a-zA-Z0-9_-]+)$"
)]
final class CleanEngineBrokerCommandsCommand extends Command
{
use LoggerTrait;
public function __construct(
private readonly UpdateMonitoringServer $useCase,
private readonly ReadMonitoringServerRepositoryInterface $readRepository,
private readonly ValidatorInterface $validator,
) {
parent::__construct();
}
public function configure(): void
{
$this->addOption(
name: 'dry-run',
shortcut: 'dr',
description: 'execute the script in dry run mode to only list '
. 'the affected Monitoring Server with invalid path'
);
}
public function execute(InputInterface $input, OutputInterface $output): int
{
$monitoringServers = $this->readRepository->findAll();
foreach ($monitoringServers as $monitoringServer) {
$output->writeln('Monitoring Server: ' . $monitoringServer->getName());
$violations = $this->validator->validate(ValidMonitoringServerDto::fromModel($monitoringServer));
if ($violations->count() === 0) {
$output->writeln('No invalid commands found.');
continue;
}
$invalidPropertyPaths = [];
foreach ($violations as $violation) {
/** @var ConstraintViolation $violation */
$invalidPropertyPaths[] = $violation->getPropertyPath();
$output->writeln(
sprintf(
'Invalid command: %s - %s',
$violation->getPropertyPath(),
$violation->getInvalidValue()
)
);
}
if ($input->getOption('dry-run')) {
continue;
}
try {
($this->useCase)(new UpdateMonitoringServerRequest(
id: $monitoringServer->getId(),
name: $monitoringServer->getName(),
engineRestartCommand: in_array('engineRestartCommand', $invalidPropertyPaths, true)
? MonitoringServer::DEFAULT_ENGINE_RESTART_COMMAND
: $monitoringServer->getEngineRestartCommand(),
engineReloadCommand: in_array('engineReloadCommand', $invalidPropertyPaths, true)
? MonitoringServer::DEFAULT_ENGINE_RELOAD_COMMAND
: $monitoringServer->getEngineReloadCommand(),
engineStopCommand: in_array('engineStopCommand', $invalidPropertyPaths, true)
? MonitoringServer::DEFAULT_ENGINE_STOP_COMMAND
: $monitoringServer->getEngineStopCommand(),
engineStartCommand: in_array('engineStartCommand', $invalidPropertyPaths, true)
? MonitoringServer::DEFAULT_ENGINE_START_COMMAND
: $monitoringServer->getEngineStartCommand(),
brokerReloadCommand: in_array('brokerReloadCommand', $invalidPropertyPaths, true)
? MonitoringServer::DEFAULT_BROKER_RELOAD_COMMAND
: $monitoringServer->getBrokerReloadCommand()
));
$output->writeln('Commands have been correctly cleaned');
} catch (RepositoryException $ex) {
$this->error('An error occured while cleaning engine commands', [
'exception' => $ex,
]);
$output->writeln('An error occured while cleaning engine commands, please retry');
continue;
}
}
$input->getOption('dry-run')
? $output->writeln('Dry run completed. No changes were made.')
: $output->writeln('All invalid commands have been cleaned.');
return Command::SUCCESS;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/MonitoringServer/Infrastructure/Command/CleanEngineBrokerCommandsCommand/ValidMonitoringServerDto.php | centreon/src/Core/MonitoringServer/Infrastructure/Command/CleanEngineBrokerCommandsCommand/ValidMonitoringServerDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\MonitoringServer\Infrastructure\Command\CleanEngineBrokerCommandsCommand;
use Core\MonitoringServer\Model\MonitoringServer;
use Symfony\Component\Validator\Constraints as Assert;
final readonly class ValidMonitoringServerDto
{
public function __construct(
public int $id,
public string $name,
#[Assert\Regex(
pattern: MonitoringServer::VALID_COMMAND_START_REGEX,
message: 'Invalid command format.'
)]
public ?string $engineStartCommand = null,
#[Assert\Regex(
pattern: MonitoringServer::VALID_COMMAND_STOP_REGEX,
message: 'Invalid command format.'
)]
public ?string $engineStopCommand = null,
#[Assert\Regex(
pattern: MonitoringServer::VALID_COMMAND_RESTART_REGEX,
message: 'Invalid command format.'
)]
public ?string $engineRestartCommand = null,
#[Assert\Regex(
pattern: MonitoringServer::VALID_COMMAND_RELOAD_REGEX,
message: 'Invalid command format.'
)]
public ?string $engineReloadCommand = null,
#[Assert\Regex(
pattern: MonitoringServer::VALID_COMMAND_RELOAD_REGEX,
message: 'Invalid command format.'
)]
public ?string $brokerReloadCommand = null,
) {
}
public static function fromModel(MonitoringServer $monitoringServer): self
{
return new self(
id: $monitoringServer->getId(),
name: $monitoringServer->getName(),
engineStartCommand: $monitoringServer->getEngineStartCommand(),
engineStopCommand: $monitoringServer->getEngineStopCommand(),
engineRestartCommand: $monitoringServer->getEngineRestartCommand(),
engineReloadCommand: $monitoringServer->getEngineReloadCommand(),
brokerReloadCommand: $monitoringServer->getBrokerReloadCommand()
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/PerformanceGraph/Application/Repository/ReadPerformanceGraphRepositoryInterface.php | centreon/src/Core/PerformanceGraph/Application/Repository/ReadPerformanceGraphRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\PerformanceGraph\Application\Repository;
interface ReadPerformanceGraphRepositoryInterface
{
/**
* Indicates whether the performance graph already exists.
*
* @param int $performanceGraphId
*
* @throws \Throwable
*
* @return bool
*/
public function exists(int $performanceGraphId): 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/PerformanceGraph/Infrastructure/Repository/DbReadPerformanceGraphRepository.php | centreon/src/Core/PerformanceGraph/Infrastructure/Repository/DbReadPerformanceGraphRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\PerformanceGraph\Infrastructure\Repository;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\PerformanceGraph\Application\Repository\ReadPerformanceGraphRepositoryInterface;
class DbReadPerformanceGraphRepository extends AbstractRepositoryRDB implements ReadPerformanceGraphRepositoryInterface
{
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
public function exists(int $performanceGraphId): bool
{
$request = $this->translateDbName('SELECT * FROM `:db`.giv_graphs_template WHERE graph_id = :id');
$statement = $this->db->prepare($request);
$statement->bindValue(':id', $performanceGraphId, \PDO::PARAM_INT);
$statement->execute();
return (bool) $statement->fetchColumn();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Installation/Infrastructure/InstallationHelper.php | centreon/src/Core/Installation/Infrastructure/InstallationHelper.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Installation\Infrastructure;
use Core\Engine\Application\Repository\EngineRepositoryInterface;
use Core\Engine\Domain\Model\EngineKey;
use Core\Engine\Domain\Model\EngineSecrets;
use Security\Interfaces\EncryptionInterface;
final readonly class InstallationHelper
{
public function __construct(
private EngineRepositoryInterface $engineRepository,
private EncryptionInterface $encryption,
private string $appSecret,
) {
}
/**
* Write Engine Secrets content in EngineContext File.
*/
public function writeEngineContextFile(): void
{
$engineSecrets = new EngineSecrets(
firstKey: new EngineKey($this->appSecret),
secondKey: new EngineKey($this->encryption->generateRandomString())
);
$this->engineRepository->writeEngineSecrets($engineSecrets);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ViewImg/Application/Repository/ReadViewImgRepositoryInterface.php | centreon/src/Core/ViewImg/Application/Repository/ReadViewImgRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ViewImg\Application\Repository;
interface ReadViewImgRepositoryInterface
{
/**
* Tells whether the image exists.
*
* @param int $imageId
*
* @throws \Throwable
*
* @return bool
*/
public function existsOne(int $imageId): 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/ViewImg/Infrastructure/Repository/DbReadViewImgRepository.php | centreon/src/Core/ViewImg/Infrastructure/Repository/DbReadViewImgRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ViewImg\Infrastructure\Repository;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Core\ViewImg\Application\Repository\ReadViewImgRepositoryInterface;
class DbReadViewImgRepository extends AbstractRepositoryDRB implements ReadViewImgRepositoryInterface
{
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function existsOne(int $imageId): bool
{
$query = <<<'SQL'
SELECT img_id
FROM `:db`.`view_img`
WHERE img_id = :image_id
SQL;
$statement = $this->db->prepare($this->translateDbName($query));
$statement->bindValue(':image_id', $imageId, \PDO::PARAM_INT);
$statement->execute();
return (bool) $statement->fetchColumn();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Option/Application/Repository/WriteOptionRepositoryInterface.php | centreon/src/Core/Option/Application/Repository/WriteOptionRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Option\Application\Repository;
use Core\Option\Domain\Option;
interface WriteOptionRepositoryInterface
{
/**
* Update option.
*
* @param Option $option
*
* @throws \Throwable
*/
public function update(Option $option): 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/Option/Application/Repository/ReadOptionRepositoryInterface.php | centreon/src/Core/Option/Application/Repository/ReadOptionRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Option\Application\Repository;
use Core\Option\Domain\Option;
interface ReadOptionRepositoryInterface
{
/**
* find an option by its name.
*
* @param string $name
*
* @return Option|null
*/
public function findByName(string $name): ?Option;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Option/Domain/Option.php | centreon/src/Core/Option/Domain/Option.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Option\Domain;
class Option
{
public function __construct(private string $name, private ?string $value)
{
}
public function getName(): string
{
return $this->name;
}
public function getValue(): ?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/Option/Infrastructure/Repository/DbWriteOptionRepository.php | centreon/src/Core/Option/Infrastructure/Repository/DbWriteOptionRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Option\Infrastructure\Repository;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Option\Application\Repository\WriteOptionRepositoryInterface;
use Core\Option\Domain\Option;
class DbWriteOptionRepository extends AbstractRepositoryRDB implements WriteOptionRepositoryInterface
{
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function update(Option $option): void
{
$statement = $this->db->prepare('UPDATE options SET value = :value WHERE `key` = :key');
$statement->bindValue(':value', $option->getValue(), \PDO::PARAM_STR);
$statement->bindValue(':key', $option->getName(), \PDO::PARAM_STR);
$statement->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Option/Infrastructure/Repository/DbReadOptionRepository.php | centreon/src/Core/Option/Infrastructure/Repository/DbReadOptionRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Option\Infrastructure\Repository;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Option\Application\Repository\ReadOptionRepositoryInterface;
use Core\Option\Domain\Option;
class DbReadOptionRepository extends AbstractRepositoryRDB implements ReadOptionRepositoryInterface
{
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function findByName(string $name): ?Option
{
$statement = $this->db->prepare('SELECT * FROM options WHERE `key` = :key LIMIT 1');
$statement->bindValue(':key', $name, \PDO::PARAM_STR);
$statement->execute();
$option = null;
while ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
/**
* @var array{key: string, value: ?string} $result
*/
$option = new Option($result['key'], $result['value']);
}
return $option;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Resources/Application/UseCase/CountResources/CountResources.php | centreon/src/Core/Resources/Application/UseCase/CountResources/CountResources.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Application\UseCase\CountResources;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Resources\Application\Repository\ReadResourceRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
/**
* Class
*
* @class CountResources
* @package Core\Resources\Application\UseCase\CountResources
*/
final readonly class CountResources
{
/**
* CountResources constructor
*
* @param ReadResourceRepositoryInterface $readResourceRepository
* @param ReadAccessGroupRepositoryInterface $accessGroupRepository
*/
public function __construct(
private ReadResourceRepositoryInterface $readResourceRepository,
private ReadAccessGroupRepositoryInterface $accessGroupRepository,
) {
}
/**
* @param CountResourcesRequest $request
* @param CountResourcesPresenterInterface $presenter
*
* @return void
*/
public function __invoke(
CountResourcesRequest $request,
CountResourcesPresenterInterface $presenter,
): void {
$response = new CountResourcesResponse();
try {
if ($request->isAdmin) {
$countFilteredResources = $this->readResourceRepository->countResourcesByFilter(
$request->resourceFilter,
$request->allPages
);
$countTotalResources = $this->readResourceRepository->countAllResources();
} else {
$accessGroups = $this->accessGroupRepository->findByContactId($request->contactId);
$accessGroupIds = $accessGroups->getIds();
$countFilteredResources = $this->readResourceRepository->countResourcesByFilterAndAccessGroupIds(
$request->resourceFilter,
$request->allPages,
$accessGroupIds
);
$countTotalResources = $this->readResourceRepository->countAllResourcesByAccessGroupIds($accessGroupIds);
}
$response->setTotalFilteredResources($countFilteredResources);
$response->setTotalResources($countTotalResources);
$presenter->presentResponse($response);
} catch (RepositoryException $exception) {
$presenter->presentResponse(
new ErrorResponse(
message: 'An error occurred while counting resources',
context: [
'use_case' => 'CountResources',
'user_is_admin' => $request->isAdmin,
'contact_id' => $request->contactId,
'resources_filter' => $request->resourceFilter,
],
exception: $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/Resources/Application/UseCase/CountResources/CountResourcesRequest.php | centreon/src/Core/Resources/Application/UseCase/CountResources/CountResourcesRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Application\UseCase\CountResources;
use Centreon\Domain\Monitoring\ResourceFilter;
/**
* Class
*
* @class CountResourcesRequest
* @package Core\Resources\Application\UseCase\CountResources
*/
final readonly class CountResourcesRequest
{
/**
* CountResourcesRequest constructor
*
* @param ResourceFilter $resourceFilter
* @param bool $allPages
* @param int $contactId
* @param bool $isAdmin
*/
public function __construct(
public ResourceFilter $resourceFilter,
public bool $allPages,
public int $contactId,
public bool $isAdmin,
) {
$this->validateRequest();
}
/**
* @return void
*/
private function validateRequest(): void
{
if ($this->contactId <= 0) {
throw new \InvalidArgumentException("Contact ID must be greater than 0, {$this->contactId} given");
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Resources/Application/UseCase/CountResources/CountResourcesResponse.php | centreon/src/Core/Resources/Application/UseCase/CountResources/CountResourcesResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Application\UseCase\CountResources;
/**
* Class
*
* @class CountResourcesResponse
* @package Core\Resources\Application\UseCase\CountResources
*/
final class CountResourcesResponse
{
/** @var int */
private int $totalFilteredResources = 0;
/** @var int */
private int $totalResources = 0;
/**
* @return int
*/
public function getTotalFilteredResources(): int
{
return $this->totalFilteredResources;
}
/**
* @param int $totalFilteredResources
*
* @return CountResourcesResponse
*/
public function setTotalFilteredResources(int $totalFilteredResources): self
{
$this->totalFilteredResources = $totalFilteredResources;
return $this;
}
/**
* @return int
*/
public function getTotalResources(): int
{
return $this->totalResources;
}
/**
* @param int $totalResources
*
* @return $this
*/
public function setTotalResources(int $totalResources): self
{
$this->totalResources = $totalResources;
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/Resources/Application/UseCase/CountResources/CountResourcesPresenterInterface.php | centreon/src/Core/Resources/Application/UseCase/CountResources/CountResourcesPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Application\UseCase\CountResources;
use Core\Application\Common\UseCase\ResponseStatusInterface;
/**
* Interface
*
* @class CountResourcesPresenterInterface
* @package Core\Resources\Application\UseCase\CountResources
*/
interface CountResourcesPresenterInterface
{
public function presentResponse(ResponseStatusInterface|CountResourcesResponse $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/Resources/Application/UseCase/FindResources/FindResourcesResponse.php | centreon/src/Core/Resources/Application/UseCase/FindResources/FindResourcesResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Application\UseCase\FindResources;
use Core\Resources\Application\UseCase\FindResources\Response\ResourceResponseDto;
final class FindResourcesResponse
{
/**
* @param ResourceResponseDto[] $resources
* @param array<string, array<mixed, mixed>> $extraData
*/
public function __construct(
public array $resources = [],
public array $extraData = [],
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Resources/Application/UseCase/FindResources/FindResourcesFactory.php | centreon/src/Core/Resources/Application/UseCase/FindResources/FindResourcesFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Application\UseCase\FindResources;
use Centreon\Domain\Monitoring\Icon as LegacyIcon;
use Centreon\Domain\Monitoring\Notes;
use Centreon\Domain\Monitoring\Resource as ResourceEntity;
use Centreon\Domain\Monitoring\ResourceStatus;
use Core\Domain\RealTime\Model\Icon;
use Core\Resources\Application\UseCase\FindResources\Response\IconResponseDto;
use Core\Resources\Application\UseCase\FindResources\Response\NotesResponseDto;
use Core\Resources\Application\UseCase\FindResources\Response\ParentResourceResponseDto;
use Core\Resources\Application\UseCase\FindResources\Response\ResourceResponseDto;
use Core\Resources\Application\UseCase\FindResources\Response\ResourceStatusResponseDto;
use Core\Resources\Application\UseCase\FindResources\Response\SeverityResponseDto;
use Core\Severity\RealTime\Domain\Model\Severity;
final class FindResourcesFactory
{
/**
* @param list<ResourceEntity> $resources
* @param array<string, array<mixed, mixed>> $extraData
*
* @return FindResourcesResponse
*/
public static function createResponse(
array $resources,
array $extraData = [],
): FindResourcesResponse {
$response = new FindResourcesResponse();
$response->extraData = $extraData;
foreach ($resources as $resource) {
$parentResource = $resource->getParent();
$resourceDto = new ResourceResponseDto();
$resourceDto->resourceId = $resource->getResourceId();
$resourceDto->uuid = $resource->getUuid();
$resourceDto->id = $resource->getId();
$resourceDto->internalId = $resource->getInternalId();
$resourceDto->name = $resource->getName();
$resourceDto->type = $resource->getType();
$resourceDto->fqdn = $resource->getFqdn();
$resourceDto->alias = $resource->getAlias();
$resourceDto->hostId = $resource->getHostId();
$resourceDto->serviceId = $resource->getServiceId();
$resourceDto->information = $resource->getInformation();
$resourceDto->isAcknowledged = $resource->getAcknowledged();
$resourceDto->isInDowntime = $resource->getInDowntime();
$resourceDto->isInFlapping = $resource->isInFlapping();
$resourceDto->percentStateChange = $resource->getPercentStateChange();
$resourceDto->withActiveChecks = $resource->getActiveChecks();
$resourceDto->withPassiveChecks = $resource->getPassiveChecks();
$resourceDto->monitoringServerName = $resource->getMonitoringServerName();
$resourceDto->shortType = $resource->getShortType();
$resourceDto->tries = $resource->getTries();
$resourceDto->status = self::createNullableStatusResponseDto($resource->getStatus());
$resourceDto->parent = self::createNullableParentResourceResponseDto($parentResource);
$resourceDto->severity = self::createNullableSeverityResponseDto($resource->getSeverity());
$resourceDto->icon = self::createNullableIconResponseDto($resource->getIcon());
$resourceDto->actionUrl = $resource->getLinks()->getExternals()->getActionUrl();
$resourceDto->notes = self::createNullableNotesResponseDto($resource->getLinks()->getExternals()->getNotes());
$resourceDto->hasGraphData = $resource->hasGraph();
$resourceDto->lastCheck = self::createNullableDateTimeImmutable($resource->getLastCheck());
$resourceDto->lastStatusChange = self::createNullableDateTimeImmutable($resource->getLastStatusChange());
$resourceDto->areNotificationsEnabled = $resource->isNotificationEnabled();
$response->resources[] = $resourceDto;
}
return $response;
}
/**
* @param \DateTimeImmutable|\DateTime|null $date
*
* @return ($date is null ? null : \DateTimeImmutable)
*/
private static function createNullableDateTimeImmutable(null|\DateTimeImmutable|\DateTime $date): ?\DateTimeImmutable
{
return match (true) {
$date === null => null,
$date instanceof \DateTime => \DateTimeImmutable::createFromMutable($date),
$date instanceof \DateTimeImmutable => $date,
};
}
/**
* @param ?Notes $notes
*
* @return ($notes is null ? null : NotesResponseDto)
*/
private static function createNullableNotesResponseDto(?Notes $notes): ?NotesResponseDto
{
if ($notes === null) {
return null;
}
$dto = new NotesResponseDto();
$dto->url = $notes->getUrl();
$dto->label = $notes->getLabel();
return $dto;
}
/**
* @param ?ResourceEntity $parentResource
*
* @return ($parentResource is null ? null : ParentResourceResponseDto)
*/
private static function createNullableParentResourceResponseDto(?ResourceEntity $parentResource): ?ParentResourceResponseDto
{
if ($parentResource === null) {
return null;
}
$dto = new ParentResourceResponseDto();
$dto->resourceId = $parentResource->getResourceId();
$dto->uuid = $parentResource->getUuid();
$dto->id = $parentResource->getId();
$dto->name = $parentResource->getName();
$dto->type = $parentResource->getType();
$dto->shortType = $parentResource->getShortType();
$dto->alias = $parentResource->getAlias();
$dto->fqdn = $parentResource->getFqdn();
$dto->status = self::createNullableStatusResponseDto($parentResource->getStatus());
return $dto;
}
/**
* @param ?ResourceStatus $status
*
* @return ($status is null ? null : ResourceStatusResponseDto)
*/
private static function createNullableStatusResponseDto(?ResourceStatus $status): ?ResourceStatusResponseDto
{
if ($status === null) {
return null;
}
$dto = new ResourceStatusResponseDto();
$dto->code = $status->getCode();
$dto->name = $status->getName();
$dto->severityCode = $status->getSeverityCode();
return $dto;
}
/**
* @param ?Severity $severity
*
* @return ($severity is null ? null : SeverityResponseDto)
*/
private static function createNullableSeverityResponseDto(?Severity $severity): ?SeverityResponseDto
{
if ($severity === null) {
return null;
}
$dto = new SeverityResponseDto();
$dto->id = $severity->getId();
$dto->name = $severity->getName();
$dto->type = $severity->getType();
$dto->level = $severity->getLevel();
$dto->icon = self::createNullableIconResponseDto($severity->getIcon());
return $dto;
}
/**
* @param LegacyIcon|Icon|null $icon
*
* @return ($icon is null ? null : IconResponseDto)
*/
private static function createNullableIconResponseDto(null|LegacyIcon|Icon $icon): ?IconResponseDto
{
if ($icon === null) {
return null;
}
$dto = new IconResponseDto();
$dto->id = $icon->getId();
$dto->name = $icon->getName();
$dto->url = $icon->getUrl();
return $dto;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Resources/Application/UseCase/FindResources/FindResourcesPresenterInterface.php | centreon/src/Core/Resources/Application/UseCase/FindResources/FindResourcesPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Application\UseCase\FindResources;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface FindResourcesPresenterInterface
{
/**
* @param FindResourcesResponse|ResponseStatusInterface $response
*/
public function presentResponse(FindResourcesResponse|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/Resources/Application/UseCase/FindResources/FindResources.php | centreon/src/Core/Resources/Application/UseCase/FindResources/FindResources.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Application\UseCase\FindResources;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Monitoring\Resource as ResourceEntity;
use Centreon\Domain\Monitoring\ResourceFilter;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Resources\Application\Exception\ResourceException;
use Core\Resources\Application\Repository\ReadResourceRepositoryInterface;
use Core\Resources\Infrastructure\Repository\ExtraDataProviders\ExtraDataProviderInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
final class FindResources
{
use LoggerTrait;
/**
* @param ReadResourceRepositoryInterface $repository
* @param ContactInterface $contact
* @param ReadAccessGroupRepositoryInterface $accessGroupRepository
* @param \Traversable<ExtraDataProviderInterface> $extraDataProviders
*/
public function __construct(
private readonly ReadResourceRepositoryInterface $repository,
private readonly ContactInterface $contact,
private readonly ReadAccessGroupRepositoryInterface $accessGroupRepository,
private readonly \Traversable $extraDataProviders,
) {
}
/**
* @param FindResourcesPresenterInterface $presenter
* @param ResourceFilter $filter
*/
public function __invoke(
FindResourcesPresenterInterface $presenter,
ResourceFilter $filter,
): void {
try {
$resources = $this->contact->isAdmin() ? $this->findResourcesAsAdmin($filter) : $this->findResourcesAsUser($filter);
$extraData = [];
foreach (iterator_to_array($this->extraDataProviders) as $provider) {
$extraData[$provider->getExtraDataSourceName()] = $provider->getExtraDataForResources($filter, $resources);
}
$presenter->presentResponse(FindResourcesFactory::createResponse($resources, $extraData));
} catch (RepositoryException $exception) {
$presenter->presentResponse(
new ErrorResponse(
message: ResourceException::errorWhileSearching(),
context: [
'use_case' => 'FindResources',
'user_is_admin' => $this->contact->isAdmin(),
'contact_id' => $this->contact->getId(),
'resources_filter' => $filter,
],
exception: $exception
)
);
}
}
/**
* @param ResourceFilter $filter
*
* @throws RepositoryException
* @return ResourceEntity[]
*/
private function findResourcesAsAdmin(ResourceFilter $filter): array
{
return $this->repository->findResources($filter);
}
/**
* @param ResourceFilter $filter
*
* @throws RepositoryException
* @return ResourceEntity[]
*/
private function findResourcesAsUser(ResourceFilter $filter): array
{
$accessGroupIds = array_map(
static fn (AccessGroup $accessGroup) => $accessGroup->getId(),
$this->accessGroupRepository->findByContact($this->contact)
);
return $this->repository->findResourcesByAccessGroupIds($filter, $accessGroupIds);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Resources/Application/UseCase/FindResources/Response/ResourceStatusResponseDto.php | centreon/src/Core/Resources/Application/UseCase/FindResources/Response/ResourceStatusResponseDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Application\UseCase\FindResources\Response;
final class ResourceStatusResponseDto
{
/**
* @param int|null $code
* @param string|null $name
* @param int|null $severityCode
*/
public function __construct(
public ?int $code = null,
public ?string $name = null,
public ?int $severityCode = null,
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Resources/Application/UseCase/FindResources/Response/NotesResponseDto.php | centreon/src/Core/Resources/Application/UseCase/FindResources/Response/NotesResponseDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Application\UseCase\FindResources\Response;
final class NotesResponseDto
{
/**
* @param string|null $label
* @param string|null $url
*/
public function __construct(
public ?string $label = null,
public ?string $url = null,
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Resources/Application/UseCase/FindResources/Response/SeverityResponseDto.php | centreon/src/Core/Resources/Application/UseCase/FindResources/Response/SeverityResponseDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Application\UseCase\FindResources\Response;
final class SeverityResponseDto
{
/**
* @param int $id
* @param string $name
* @param int $level
* @param int $type
* @param IconResponseDto $icon
*/
public function __construct(
public int $id = 0,
public string $name = '',
public int $level = 0,
public int $type = 0,
public IconResponseDto $icon = new IconResponseDto(),
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Resources/Application/UseCase/FindResources/Response/ResourceResponseDto.php | centreon/src/Core/Resources/Application/UseCase/FindResources/Response/ResourceResponseDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Application\UseCase\FindResources\Response;
final class ResourceResponseDto
{
public function __construct(
public ?int $resourceId = null,
public ?int $id = null,
public ?string $name = null,
public ?string $type = null,
public ?int $serviceId = null,
public ?int $hostId = null,
public ?int $internalId = null,
public ?string $alias = null,
public ?string $fqdn = null,
public ?IconResponseDto $icon = null,
public ?ResourceStatusResponseDto $status = null,
public bool $isInDowntime = false,
public bool $isAcknowledged = false,
public bool $isInFlapping = false,
public ?float $percentStateChange = null,
public bool $withActiveChecks = false,
public bool $withPassiveChecks = false,
public ?\DateTimeInterface $lastStatusChange = null,
public ?string $tries = null,
public ?string $information = null,
public bool $areNotificationsEnabled = false,
public string $monitoringServerName = '',
public ?SeverityResponseDto $severity = null,
public ?string $shortType = null,
public ?string $uuid = null,
public ?ParentResourceResponseDto $parent = null,
public ?\DateTimeInterface $lastCheck = null,
public ?string $actionUrl = null,
public ?NotesResponseDto $notes = null,
public bool $hasGraphData = 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/Resources/Application/UseCase/FindResources/Response/ParentResourceResponseDto.php | centreon/src/Core/Resources/Application/UseCase/FindResources/Response/ParentResourceResponseDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Application\UseCase\FindResources\Response;
final class ParentResourceResponseDto
{
/**
* @param int|null $resourceId
* @param string|null $uuid
* @param int|null $id
* @param string|null $name
* @param string|null $type
* @param string|null $alias
* @param string|null $fqdn
* @param ResourceStatusResponseDto|null $status
* @param string|null $monitoringServerName
* @param string|null $shortType
*/
public function __construct(
public ?int $resourceId = null,
public ?string $uuid = null,
public ?int $id = null,
public ?string $name = null,
public ?string $type = null,
public ?string $alias = null,
public ?string $fqdn = null,
public ?ResourceStatusResponseDto $status = null,
public ?string $monitoringServerName = null,
public ?string $shortType = null,
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Resources/Application/UseCase/FindResources/Response/IconResponseDto.php | centreon/src/Core/Resources/Application/UseCase/FindResources/Response/IconResponseDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Application\UseCase\FindResources\Response;
final class IconResponseDto
{
/**
* @param int|null $id
* @param string|null $name
* @param string|null $url
*/
public function __construct(
public ?int $id = null,
public ?string $name = null,
public ?string $url = null,
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Resources/Application/UseCase/FindResourcesByParent/FindResourcesByParentPresenterInterface.php | centreon/src/Core/Resources/Application/UseCase/FindResourcesByParent/FindResourcesByParentPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Application\UseCase\FindResourcesByParent;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface FindResourcesByParentPresenterInterface
{
/**
* @param FindResourcesByParentResponse|ResponseStatusInterface $response
*/
public function presentResponse(FindResourcesByParentResponse|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/Resources/Application/UseCase/FindResourcesByParent/FindResourcesByParentFactory.php | centreon/src/Core/Resources/Application/UseCase/FindResourcesByParent/FindResourcesByParentFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Application\UseCase\FindResourcesByParent;
use Core\Resources\Application\UseCase\FindResources\Response\ResourceResponseDto;
use Core\Resources\Application\UseCase\FindResourcesByParent\Response\ResourcesByParentResponseDto;
final class FindResourcesByParentFactory
{
private const STATUS_CODE_OK = 0;
private const STATUS_CODE_WARNING = 1;
private const STATUS_CODE_CRITICAL = 2;
private const STATUS_CODE_UNKNOWN = 3;
private const STATUS_CODE_PENDING = 4;
/**
* @param list<ResourceResponseDto> $parents
* @param list<ResourceResponseDto> $children
* @param array<string, array<mixed, mixed>> $extraData
*
* @return FindResourcesByParentResponse
*/
public static function createResponse(array $parents, array $children, array $extraData): FindResourcesByParentResponse
{
$resources = [];
foreach ($parents as $parent) {
$found = $parent->id === null ? [] : self::findChildrenAmongResponse($parent->id, $children);
$resources[] = new ResourcesByParentResponseDto(
$parent,
array_values($found),
count($found),
self::countInStatus(self::STATUS_CODE_OK, $found),
self::countInStatus(self::STATUS_CODE_WARNING, $found),
self::countInStatus(self::STATUS_CODE_CRITICAL, $found),
self::countInStatus(self::STATUS_CODE_UNKNOWN, $found),
self::countInStatus(self::STATUS_CODE_PENDING, $found)
);
}
return new FindResourcesByParentResponse($resources, $extraData);
}
/**
* Return all children of Parent identified by parentId.
*
* @param int $parentId
* @param ResourceResponseDto[] $children
*
* @return ResourceResponseDto[]
*/
private static function findChildrenAmongResponse(int $parentId, array $children): array
{
return array_filter(
$children,
static fn (ResourceResponseDto $child) => $child->parent?->id === $parentId
);
}
/**
* Count children in given status.
*
* @param int $statusCode
* @param ResourceResponseDto[] $children
*
* @return int
*/
private static function countInStatus(int $statusCode, array $children): int
{
$childrenInStatus = array_filter(
$children,
static fn (ResourceResponseDto $resource) => $resource->status?->code === $statusCode
);
return count($childrenInStatus);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Resources/Application/UseCase/FindResourcesByParent/FindResourcesByParentResponse.php | centreon/src/Core/Resources/Application/UseCase/FindResourcesByParent/FindResourcesByParentResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Application\UseCase\FindResourcesByParent;
use Core\Resources\Application\UseCase\FindResourcesByParent\Response\ResourcesByParentResponseDto;
final class FindResourcesByParentResponse
{
/**
* @param ResourcesByParentResponseDto[] $resources
* @param array<string, array<mixed, mixed>> $extraData
*/
public function __construct(
public array $resources = [],
public array $extraData = [],
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Resources/Application/UseCase/FindResourcesByParent/FindResourcesByParent.php | centreon/src/Core/Resources/Application/UseCase/FindResourcesByParent/FindResourcesByParent.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Application\UseCase\FindResourcesByParent;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Monitoring\Resource as ResourceEntity;
use Centreon\Domain\Monitoring\ResourceFilter;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Resources\Application\Exception\ResourceException;
use Core\Resources\Application\Repository\ReadResourceRepositoryInterface;
use Core\Resources\Application\UseCase\FindResources\FindResourcesFactory;
use Core\Resources\Application\UseCase\FindResources\FindResourcesResponse;
use Core\Resources\Infrastructure\Repository\ExtraDataProviders\ExtraDataProviderInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
final class FindResourcesByParent
{
use LoggerTrait;
private int $pageProvided = 1;
private string $searchProvided = '';
/** @var array<mixed> */
private array $sortProvided = [];
/**
* @param ReadResourceRepositoryInterface $repository
* @param ContactInterface $contact
* @param RequestParametersInterface $requestParameters
* @param ReadAccessGroupRepositoryInterface $accessGroupRepository
* @param \Traversable<ExtraDataProviderInterface> $extraDataProviders
*/
public function __construct(
private readonly ReadResourceRepositoryInterface $repository,
private readonly ContactInterface $contact,
private readonly RequestParametersInterface $requestParameters,
private readonly ReadAccessGroupRepositoryInterface $accessGroupRepository,
private readonly \Traversable $extraDataProviders,
) {
}
/**
* @param FindResourcesByParentPresenterInterface $presenter
* @param ResourceFilter $filter
*/
public function __invoke(
FindResourcesByParentPresenterInterface $presenter,
ResourceFilter $filter,
): void {
try {
// Save the search and sort provided to be restored later on
$this->searchProvided = $this->requestParameters->getSearchAsString();
$this->sortProvided = $this->requestParameters->getSort();
$this->pageProvided = $this->requestParameters->getPage();
// create specific filter for parent search
$parentFilter = (new ResourceFilter())->setTypes([ResourceFilter::TYPE_HOST]);
// Creating a new sort to search children as we want a specific order priority
$servicesSort = ['parent_id' => 'ASC', ...$this->sortProvided];
$parents = new FindResourcesResponse([]);
$this->requestParameters->setSort(json_encode($servicesSort) ?: '');
$resources = [];
$parentResources = [];
if ($this->contact->isAdmin()) {
$resources = $this->findResourcesAsAdmin($filter);
// Save total children found
$totalChildrenFound = $this->requestParameters->getTotal();
if ($resources !== []) {
// prepare special ResourceFilter for parent search
$parentFilter->setHostIds($this->extractParentIdsFromResources($resources));
// unset search provided in order to find parents linked to the resources found and restore sort
$this->prepareRequestParametersForParentSearch();
$parentResources = $this->findParentResources($parentFilter);
}
} else {
$resources = $this->findResourcesAsUser($filter);
// Save total children found
$totalChildrenFound = $this->requestParameters->getTotal();
if ($resources !== []) {
// prepare special ResourceFilter for parent search
$parentFilter->setHostIds($this->extractParentIdsFromResources($resources));
// unset search provided in order to find parents linked to the resources found and restore sort
$this->prepareRequestParametersForParentSearch();
$parentResources = $this->findParentResources($parentFilter);
}
}
// Only get extra data for services
$extraData = [];
foreach (iterator_to_array($this->extraDataProviders) as $provider) {
$extraData[$provider->getExtraDataSourceName()] = $provider->getExtraDataForResources($filter, $resources);
}
// Set total to the number of children found
$this->requestParameters->setTotal($totalChildrenFound);
// Restore search and sort from initial request (for accurate meta in presenter).
$this->restoreProvidedSearchParameters();
$children = FindResourcesFactory::createResponse($resources);
$parents = FindResourcesFactory::createResponse($parentResources);
$presenter->presentResponse(
FindResourcesByParentFactory::createResponse($parents->resources, $children->resources, $extraData)
);
} catch (\Throwable $ex) {
$presenter->presentResponse(new ErrorResponse(ResourceException::errorWhileSearching()));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
}
}
private function prepareRequestParametersForParentSearch(): void
{
$this->requestParameters->unsetSearch();
$this->requestParameters->setSort(json_encode($this->sortProvided) ?: '');
$this->requestParameters->setPage(1);
}
private function restoreProvidedSearchParameters(): void
{
$this->requestParameters->setPage($this->pageProvided);
$this->requestParameters->setSearch($this->searchProvided);
}
/**
* @param ResourceEntity[] $resources
*
* @return int[]
*/
private function extractParentIdsFromResources(array $resources): array
{
$hostIds = array_map(
static fn (ResourceEntity $resource) => (int) $resource->getParent()?->getId(),
$resources
);
return array_unique($hostIds);
}
/**
* @param ResourceFilter $filter
*
* @throws \Throwable
* @return ResourceEntity[]
*/
private function findResourcesAsAdmin(ResourceFilter $filter): array
{
return $this->repository->findResources($filter);
}
/**
* @param ResourceFilter $filter
*
* @throws \Throwable
* @return ResourceEntity[]
*/
private function findParentResources(ResourceFilter $filter): array
{
return $this->repository->findParentResourcesById($filter);
}
/**
* @param ResourceFilter $filter
*
* @throws \Throwable
*
* @return ResourceEntity[]
*/
private function findResourcesAsUser(ResourceFilter $filter): array
{
$accessGroupIds = array_map(
static fn (AccessGroup $accessGroup) => $accessGroup->getId(),
$this->accessGroupRepository->findByContact($this->contact)
);
return $this->repository->findResourcesByAccessGroupIds($filter, $accessGroupIds);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Resources/Application/UseCase/FindResourcesByParent/Response/ResourcesByParentResponseDto.php | centreon/src/Core/Resources/Application/UseCase/FindResourcesByParent/Response/ResourcesByParentResponseDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Application\UseCase\FindResourcesByParent\Response;
use Core\Resources\Application\UseCase\FindResources\Response\ResourceResponseDto;
final class ResourcesByParentResponseDto
{
/**
* @param ResourceResponseDto $parent
* @param ResourceResponseDto[] $children
* @param int $total,
* @param int $totalOK,
* @param int $totalWarning,
* @param int $totalCritical,
* @param int $totalUnknown,
* @param int $totalPending,
*/
public function __construct(
public ResourceResponseDto $parent,
public array $children = [],
public int $total = 0,
public int $totalOK = 0,
public int $totalWarning = 0,
public int $totalCritical = 0,
public int $totalUnknown = 0,
public int $totalPending = 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/Resources/Application/UseCase/ExportResources/ExportResourcesPresenterInterface.php | centreon/src/Core/Resources/Application/UseCase/ExportResources/ExportResourcesPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Application\UseCase\ExportResources;
use Core\Application\Common\UseCase\ResponseStatusInterface;
/**
* Interface
*
* @class ExportResourcesPresenter
* @package Core\Resources\Application\UseCase\ExportResources
*/
interface ExportResourcesPresenterInterface
{
/**
* @param ExportResourcesResponse|ResponseStatusInterface $response
*
* @return void
*/
public function presentResponse(ExportResourcesResponse|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/Resources/Application/UseCase/ExportResources/ExportResources.php | centreon/src/Core/Resources/Application/UseCase/ExportResources/ExportResources.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Application\UseCase\ExportResources;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Resources\Application\Repository\ReadResourceRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
/**
* Class
*
* @class ExportResources
* @package Core\Resources\Application\UseCase\ExportResources
*/
final readonly class ExportResources
{
/**
* ExportResources constructor
*
* @param ReadResourceRepositoryInterface $readResourceRepository
* @param ReadAccessGroupRepositoryInterface $accessGroupRepository
*/
public function __construct(
private ReadResourceRepositoryInterface $readResourceRepository,
private ReadAccessGroupRepositoryInterface $accessGroupRepository,
) {
}
/**
* @param ExportResourcesRequest $request
* @param ExportResourcesPresenterInterface $presenter
*
* @return void
*/
public function __invoke(
ExportResourcesRequest $request,
ExportResourcesPresenterInterface $presenter,
): void {
$response = new ExportResourcesResponse();
try {
if ($request->isAdmin) {
$resources = $this->readResourceRepository->iterateResources(
filter: $request->resourceFilter,
maxResults: $request->allPages ? $request->maxResults : 0
);
} else {
$accessGroups = $this->accessGroupRepository->findByContactId($request->contactId);
$accessGroupIds = $accessGroups->getIds();
$resources = $this->readResourceRepository->iterateResourcesByAccessGroupIds(
filter: $request->resourceFilter,
accessGroupIds: $accessGroupIds,
maxResults: $request->allPages ? $request->maxResults : 0
);
}
$response->setExportedFormat($request->exportedFormat);
$response->setFilteredColumns($request->columns);
$response->setResources($resources);
$presenter->presentResponse($response);
} catch (RepositoryException $exception) {
$presenter->presentResponse(
new ErrorResponse(
message: 'An error occurred while iterating resources',
context: [
'use_case' => 'ExportResources',
'user_is_admin' => $request->isAdmin,
'contact_id' => $request->contactId,
'resources_filter' => $request->resourceFilter,
],
exception: $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/Resources/Application/UseCase/ExportResources/ExportResourcesRequest.php | centreon/src/Core/Resources/Application/UseCase/ExportResources/ExportResourcesRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Application\UseCase\ExportResources;
use Centreon\Domain\Monitoring\ResourceFilter;
use Core\Common\Domain\Collection\StringCollection;
use Core\Resources\Application\UseCase\ExportResources\Enum\AllowedFormatEnum;
/**
* Class
*
* @class ExportResourcesRequest
* @package Core\Resources\Application\UseCase\ExportResources
*/
final readonly class ExportResourcesRequest
{
/**
* ExportResourcesRequest constructor
*
* @param string $exportedFormat
* @param ResourceFilter $resourceFilter
* @param bool $allPages
* @param int $maxResults
* @param StringCollection $columns
* @param int $contactId
* @param bool $isAdmin
*/
public function __construct(
public string $exportedFormat,
public ResourceFilter $resourceFilter,
public bool $allPages,
public int $maxResults,
public StringCollection $columns,
public int $contactId,
public bool $isAdmin,
) {
$this->validateRequest();
}
/**
* @return void
*/
private function validateRequest(): void
{
if ($this->contactId <= 0) {
throw new \InvalidArgumentException("Contact ID must be greater than 0, {$this->contactId} given");
}
if (is_null(AllowedFormatEnum::tryFrom($this->exportedFormat))) {
throw new \InvalidArgumentException(
sprintf(
'Format must be one of the following: %s, %s given',
implode(', ', AllowedFormatEnum::values()),
$this->exportedFormat
)
);
}
if ($this->allPages && $this->maxResults === 0) {
throw new \InvalidArgumentException(
'Max number of resources is required when exporting all pages'
);
}
if ($this->allPages && $this->maxResults > 10000) {
throw new \InvalidArgumentException(
"Max number of resources to export must be equal or less than 10000, {$this->maxResults} given"
);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Resources/Application/UseCase/ExportResources/ExportResourcesResponse.php | centreon/src/Core/Resources/Application/UseCase/ExportResources/ExportResourcesResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Application\UseCase\ExportResources;
use Centreon\Domain\Monitoring\Resource as ResourceEntity;
use Core\Common\Domain\Collection\StringCollection;
/**
* Class
*
* @class ExportResourcesResponse
* @package Core\Resources\Application\UseCase\ExportResources
*/
final class ExportResourcesResponse
{
/** @var \Traversable<ResourceEntity> */
private \Traversable $resources;
/** @var StringCollection */
private StringCollection $filteredColumns;
/** @var string */
private string $exportedFormat;
/**
* @return \Traversable<ResourceEntity>
*/
public function getResources(): \Traversable
{
return $this->resources;
}
/**
* @param \Traversable<ResourceEntity> $resources
*
* @return ExportResourcesResponse
*/
public function setResources(\Traversable $resources): self
{
$this->resources = $resources;
return $this;
}
/**
* @return StringCollection
*/
public function getFilteredColumns(): StringCollection
{
return $this->filteredColumns;
}
/**
* @param StringCollection $filteredColumns
*
* @return ExportResourcesResponse
*/
public function setFilteredColumns(StringCollection $filteredColumns): self
{
$this->filteredColumns = $filteredColumns;
return $this;
}
/**
* @return string
*/
public function getExportedFormat(): string
{
return $this->exportedFormat;
}
/**
* @param string $exportedFormat
*
* @return ExportResourcesResponse
*/
public function setExportedFormat(string $exportedFormat): self
{
$this->exportedFormat = $exportedFormat;
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/Resources/Application/UseCase/ExportResources/Enum/AllowedFormatEnum.php | centreon/src/Core/Resources/Application/UseCase/ExportResources/Enum/AllowedFormatEnum.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Application\UseCase\ExportResources\Enum;
/**
* Enum
*
* @class AllowedFormatEnum
* @package Core\Resources\Application\UseCase\ExportResources\Enum
*/
enum AllowedFormatEnum: string
{
case CSV = 'csv';
/**
* @return array<string>
*/
public static function values(): array
{
return array_map(fn (self $case) => $case->value, self::cases());
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Resources/Application/Exception/ResourceException.php | centreon/src/Core/Resources/Application/Exception/ResourceException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Application\Exception;
class ResourceException extends \Exception
{
/**
* @return self
*/
public static function errorWhileSearching(): self
{
return new self(_('Error while searching for resources'));
}
public static function errorWhileFindingHostsStatusCount(): self
{
return new self(_('Error while retrieving the number of hosts by status'));
}
public static function errorWhileFindingServicesStatusCount(): self
{
return new self(_('Error while retrieving the number of services by status'));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Resources/Application/Repository/ReadResourceRepositoryInterface.php | centreon/src/Core/Resources/Application/Repository/ReadResourceRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Application\Repository;
use Centreon\Domain\Monitoring\Resource as ResourceEntity;
use Centreon\Domain\Monitoring\ResourceFilter;
use Core\Common\Domain\Exception\RepositoryException;
interface ReadResourceRepositoryInterface
{
/**
* Find all resources.
*
* @param ResourceFilter $filter
*
* @throws RepositoryException
*
* @return ResourceEntity[]
*/
public function findResources(ResourceFilter $filter): array;
/**
* Find all resources with filter on access group IDs.
*
* @param ResourceFilter $filter
* @param array<int> $accessGroupIds
*
* @throws RepositoryException
*
* @return ResourceEntity[]
*/
public function findResourcesByAccessGroupIds(ResourceFilter $filter, array $accessGroupIds): array;
/**
* @param ResourceFilter $filter
*
* @throws RepositoryException
*
* @return ResourceEntity[]
*/
public function findParentResourcesById(ResourceFilter $filter): array;
/**
* @param ResourceFilter $filter
* @param int $maxResults
*
* @throws RepositoryException
* @return \Traversable<ResourceEntity>
*/
public function iterateResources(ResourceFilter $filter, int $maxResults = 0): \Traversable;
/**
* @param ResourceFilter $filter
* @param array<int> $accessGroupIds
* @param int $maxResults
*
* @throws RepositoryException
* @return \Traversable<ResourceEntity>
*/
public function iterateResourcesByAccessGroupIds(
ResourceFilter $filter,
array $accessGroupIds,
int $maxResults = 0,
): \Traversable;
/**
* @param ResourceFilter $filter
* @param bool $allPages
*
* @throws RepositoryException
* @return int
*/
public function countResourcesByFilter(ResourceFilter $filter, bool $allPages): int;
/**
* @param ResourceFilter $filter
* @param bool $allPages
* @param array<int> $accessGroupIds
*
* @throws RepositoryException
* @return int
*/
public function countResourcesByFilterAndAccessGroupIds(
ResourceFilter $filter,
bool $allPages,
array $accessGroupIds,
): int;
/**
* @throws RepositoryException
* @return int
*/
public function countAllResources(): int;
/**
* @param array<int> $accessGroupIds
*
* @throws RepositoryException
* @return int
*/
public function countAllResourcesByAccessGroupIds(array $accessGroupIds): 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/Resources/Infrastructure/Repository/DbResourceFactory.php | centreon/src/Core/Resources/Infrastructure/Repository/DbResourceFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Infrastructure\Repository;
use Assert\AssertionFailedException;
use Centreon\Domain\Monitoring\Icon as LegacyIconModel;
use Centreon\Domain\Monitoring\Notes;
use Centreon\Domain\Monitoring\Resource as ResourceEntity;
use Centreon\Domain\Monitoring\ResourceStatus;
use Core\Domain\RealTime\Model\Icon;
use Core\Domain\RealTime\Model\ResourceTypes\HostResourceType;
use Core\Domain\RealTime\ResourceTypeInterface;
use Core\Infrastructure\Common\Repository\DbFactoryUtilitiesTrait;
use Core\Severity\RealTime\Domain\Model\Severity;
class DbResourceFactory
{
use DbFactoryUtilitiesTrait;
/**
* @param array<string,int|string|null> $record
* @param ResourceTypeInterface[] $availableResourceTypes
*
* @throws AssertionFailedException
*
* @return ResourceEntity
*/
public static function createFromRecord(array $record, array $availableResourceTypes): ResourceEntity
{
$resourceType = self::normalizeType((int) $record['type'], $availableResourceTypes);
$parent = null;
$resourceHasParent = self::resourceHasParent((int) $record['type'], $availableResourceTypes);
if ($resourceHasParent === true) {
$parentStatus = (new ResourceStatus())
->setCode((int) $record['parent_status'])
->setName(self::getStatusAsString(HostResourceType::TYPE_NAME, (int) $record['parent_status']))
->setSeverityCode(self::normalizeSeverityCode((int) $record['parent_status_ordered']));
/** @var string|null $name */
$name = $record['parent_name'];
/** @var string|null $alias */
$alias = $record['parent_alias'];
/** @var string|null $fqdn */
$fqdn = $record['parent_fqdn'];
$parent = (new ResourceEntity())
->setResourceId((int) $record['parent_resource_id'])
->setId((int) $record['parent_id'])
->setName($name)
->setAlias($alias)
->setType(HostResourceType::TYPE_NAME)
->setFqdn($fqdn)
->setStatus($parentStatus);
}
$status = (new ResourceStatus())
->setCode((int) $record['status'])
->setName(self::getStatusAsString($resourceType, (int) $record['status']))
->setSeverityCode(self::normalizeSeverityCode((int) $record['status_ordered']));
/** @var string|null */
$label = $record['notes'];
/** @var string|null */
$url = $record['notes_url'];
$notes = (new Notes())
->setLabel($label)
->setUrl($url);
$statusConfirmedAsString = (int) $record['status_confirmed'] === 1 ? 'H' : 'S';
$tries = $record['check_attempts']
. '/' . $record['max_check_attempts'] . ' (' . $statusConfirmedAsString . ')';
$severity = null;
if (! empty($record['severity_id'])) {
$severityIcon = (new Icon())
->setId((int) $record['severity_icon_id']);
$severity = new Severity(
(int) $record['severity_id'],
(string) $record['severity_name'],
(int) $record['severity_level'],
(int) $record['severity_type'],
$severityIcon
);
}
/** @var string|null $name */
$name = $record['name'];
/** @var string|null $alias */
$alias = $record['alias'];
/** @var string|null $fqdn */
$fqdn = $record['address'];
/** @var string|null $information */
$information = $record['output'];
$resource = (new ResourceEntity())
->setResourceId((int) $record['resource_id'])
->setType($resourceType)
->setParent($parent)
->setStatus($status)
->setTries($tries)
->setServiceId((int) $record['id'])
->setHostId((int) $record['parent_id'])
->setParent($parent)
->setStatus($status)
->setInDowntime((int) $record['in_downtime'] === 1)
->setAcknowledged((int) $record['acknowledged'] === 1)
->setFlapping((int) $record['flapping'] === 1)
->setPercentStateChange(self::getFloatOrNull($record['percent_state_change']))
->setStateType((int) $record['status_confirmed'])
->setName($name)
->setAlias($alias)
->setFqdn($fqdn)
->setPassiveChecks((int) $record['passive_checks_enabled'] === 1)
->setActiveChecks((int) $record['active_checks_enabled'] === 1)
->setNotificationEnabled((int) $record['notifications_enabled'] === 1)
->setLastCheck(self::createDateTimeFromTimestamp(is_numeric($record['last_check']) ? (int) $record['last_check'] : null))
->setInformation($information)
->setMonitoringServerName((string) $record['monitoring_server_name'])
->setLastStatusChange(self::createDateTimeFromTimestamp(is_numeric($record['last_status_change']) ? (int) $record['last_status_change'] : null))
->setHasGraph((int) $record['has_graph'] === 1)
->setSeverity($severity)
->setInternalId(self::getIntOrNull($record['internal_id']));
$resource->setId(
self::resourceHasInternalId((int) $record['type'], $availableResourceTypes) === true
? (int) $record['internal_id']
: (int) $record['id']
);
$resource->setServiceId($resourceHasParent === true ? (int) $record['id'] : null);
$resource->setHostId($resourceHasParent === true ? (int) $record['parent_id'] : (int) $record['id']);
/** @var string|null */
$actionUrl = $record['action_url'];
$resource->getLinks()->getExternals()->setActionUrl($actionUrl);
$resource->getLinks()->getExternals()->setNotes($notes);
if (empty($record['icon_id']) === false) {
$resource->setIcon((new LegacyIconModel())->setId((int) $record['icon_id']));
}
return $resource;
}
/**
* Returns status as string regarding the resource type.
*
* @param string $resourceType
* @param int $statusCode
*
* @return string
*/
private static function getStatusAsString(string $resourceType, int $statusCode): string
{
if ($resourceType === ResourceEntity::TYPE_HOST) {
return match ($statusCode) {
0 => ResourceStatus::STATUS_NAME_UP,
1 => ResourceStatus::STATUS_NAME_DOWN,
2 => ResourceStatus::STATUS_NAME_UNREACHABLE,
4 => ResourceStatus::STATUS_NAME_PENDING,
default => ResourceStatus::STATUS_NAME_PENDING,
};
}
return match ($statusCode) {
0 => ResourceStatus::STATUS_NAME_OK,
1 => ResourceStatus::STATUS_NAME_WARNING,
2 => ResourceStatus::STATUS_NAME_CRITICAL,
3 => ResourceStatus::STATUS_NAME_UNKNOWN,
4 => ResourceStatus::STATUS_NAME_PENDING,
default => ResourceStatus::STATUS_NAME_PENDING,
};
}
/**
* Normalizes the status severity code.
*
* @param int $severityCode
*
* @return int
*/
private static function normalizeSeverityCode(int $severityCode): int
{
return match ($severityCode) {
0 => ResourceStatus::SEVERITY_OK,
1 => ResourceStatus::SEVERITY_PENDING,
2 => ResourceStatus::SEVERITY_LOW,
3 => ResourceStatus::SEVERITY_MEDIUM,
4 => ResourceStatus::SEVERITY_HIGH,
default => ResourceStatus::SEVERITY_PENDING,
};
}
/**
* Converts the resource type value stored as int into a string.
*
* @param int $type
* @param ResourceTypeInterface[] $availableResourceTypes
*
* @return string
*/
private static function normalizeType(int $type, array $availableResourceTypes): string
{
$normalizedType = '';
foreach ($availableResourceTypes as $resourceType) {
if ($resourceType->isValidForTypeId($type)) {
$normalizedType = $resourceType->getName();
}
}
return $normalizedType;
}
/**
* Checks if the Resource has a parent to define.
*
* @param int $resourceTypeId
* @param ResourceTypeInterface[] $availableResourceTypes
*
* @return bool
*/
private static function resourceHasParent(int $resourceTypeId, array $availableResourceTypes): bool
{
$hasParent = false;
foreach ($availableResourceTypes as $resourceType) {
if ($resourceType->isValidForTypeId($resourceTypeId)) {
$hasParent = $resourceType->hasParent();
}
}
return $hasParent;
}
/**
* @param int $resourceTypeId
* @param ResourceTypeInterface[] $availableResourceTypes
*
* @return bool
*/
private static function resourceHasInternalId(int $resourceTypeId, array $availableResourceTypes): bool
{
$hasInternalId = false;
foreach ($availableResourceTypes as $resourceType) {
if ($resourceType->isValidForTypeId($resourceTypeId)) {
$hasInternalId = $resourceType->hasInternalId();
}
}
return $hasInternalId;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Resources/Infrastructure/Repository/DbReadResourceRepository.php | centreon/src/Core/Resources/Infrastructure/Repository/DbReadResourceRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Infrastructure\Repository;
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\ConnectionInterface;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Assert\AssertionFailedException;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Monitoring\Resource as ResourceEntity;
use Centreon\Domain\Monitoring\ResourceFilter;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\RequestParameters\RequestParametersTranslatorException;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use Core\Common\Domain\Exception\CollectionException;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Common\Domain\Exception\TransformerException;
use Core\Common\Domain\Exception\ValueObjectException;
use Core\Common\Infrastructure\Repository\DatabaseRepository;
use Core\Common\Infrastructure\RequestParameters\Transformer\SearchRequestParametersTransformer;
use Core\Domain\RealTime\ResourceTypeInterface;
use Core\Resources\Application\Repository\ReadResourceRepositoryInterface;
use Core\Resources\Infrastructure\Repository\ExtraDataProviders\ExtraDataProviderInterface;
use Core\Resources\Infrastructure\Repository\ResourceACLProviders\ResourceACLProviderInterface;
use Core\Severity\RealTime\Domain\Model\Severity;
class DbReadResourceRepository extends DatabaseRepository implements ReadResourceRepositoryInterface
{
use LoggerTrait;
private const RESOURCE_TYPE_HOST = 1;
/** @var ResourceEntity[] */
private array $resources = [];
/** @var ResourceTypeInterface[] */
private array $resourceTypes;
/** @var SqlRequestParametersTranslator */
private SqlRequestParametersTranslator $sqlRequestTranslator;
/** @var ExtraDataProviderInterface[] */
private array $extraDataProviders;
/** @var array<string, string> */
private array $resourceConcordances = [
'id' => 'resources.id',
'name' => 'resources.name',
'alias' => 'resources.alias',
'fqdn' => 'resources.address',
'type' => 'resources.type',
'h.name' => 'CASE WHEN resources.type = 1 THEN resources.name ELSE resources.parent_name END',
'h.alias' => 'CASE WHEN resources.type = 1 THEN resources.alias ELSE parent_resource.alias END',
'h.address' => 'parent_resource.address',
's.description' => 'resources.type IN (0,2,4) AND resources.name',
'status_code' => 'resources.status',
'status_severity_code' => 'resources.status_ordered',
'action_url' => 'resources.action_url',
'parent_id' => 'resources.parent_id',
'parent_name' => 'resources.parent_name',
'parent_alias' => 'parent_resource.alias',
'parent_status' => 'parent_resource.status',
'severity_level' => 'severity_level',
'in_downtime' => 'resources.in_downtime',
'acknowledged' => 'resources.acknowledged',
'last_status_change' => 'resources.last_status_change',
'tries' => 'resources.check_attempts',
'last_check' => 'resources.last_check',
'monitoring_server_name' => 'monitoring_server_name',
'information' => 'resources.output',
];
/**
* DbReadResourceRepository constructor
*
* @param ConnectionInterface $db
* @param SqlRequestParametersTranslator $sqlRequestTranslator
* @param \Traversable<ResourceTypeInterface> $resourceTypes
* @param \Traversable<ResourceACLProviderInterface> $resourceACLProviders
* @param \Traversable<ExtraDataProviderInterface> $extraDataProviders
*
* @throws \InvalidArgumentException
*/
public function __construct(
ConnectionInterface $db,
SqlRequestParametersTranslator $sqlRequestTranslator,
\Traversable $resourceTypes,
private readonly \Traversable $resourceACLProviders,
\Traversable $extraDataProviders,
) {
parent::__construct($db);
$this->sqlRequestTranslator = $sqlRequestTranslator;
$this->sqlRequestTranslator
->getRequestParameters()
->setConcordanceStrictMode(RequestParameters::CONCORDANCE_MODE_STRICT)
->setConcordanceErrorMode(RequestParameters::CONCORDANCE_ERRMODE_SILENT);
if ($resourceTypes instanceof \Countable && count($resourceTypes) === 0) {
throw new \InvalidArgumentException(
_('You must add at least one resource provider')
);
}
$this->resourceTypes = iterator_to_array($resourceTypes);
$this->extraDataProviders = iterator_to_array($extraDataProviders);
}
public function findParentResourcesById(ResourceFilter $filter): array
{
$this->resources = [];
$queryParametersFromRequestParameters = new QueryParameters();
$this->sqlRequestTranslator->setConcordanceArray($this->resourceConcordances);
$resourceTypeHost = self::RESOURCE_TYPE_HOST;
$query = <<<SQL
SELECT SQL_CALC_FOUND_ROWS DISTINCT
1 AS REALTIME,
resources.resource_id,
resources.name,
resources.alias,
resources.address,
resources.id,
resources.internal_id,
resources.parent_id,
resources.parent_name,
parent_resource.status AS `parent_status`,
parent_resource.alias AS `parent_alias`,
parent_resource.status_ordered AS `parent_status_ordered`,
parent_resource.address AS `parent_fqdn`,
severities.level AS `severity_level`,
severities.name AS `severity_name`,
severities.type AS `severity_type`,
severities.icon_id AS `severity_icon_id`,
resources.type,
resources.status,
resources.status_ordered,
resources.status_confirmed,
resources.in_downtime,
resources.acknowledged,
resources.flapping,
resources.percent_state_change,
resources.passive_checks_enabled,
resources.active_checks_enabled,
resources.notifications_enabled,
resources.last_check,
resources.last_status_change,
resources.check_attempts,
resources.max_check_attempts,
resources.notes,
resources.notes_url,
resources.action_url,
resources.output,
resources.poller_id,
resources.has_graph,
instances.name AS `monitoring_server_name`,
resources.enabled,
resources.icon_id,
resources.severity_id
FROM `:dbstg`.`resources`
LEFT JOIN `:dbstg`.`resources` parent_resource
ON parent_resource.id = resources.parent_id
AND parent_resource.type = {$resourceTypeHost}
LEFT JOIN `:dbstg`.`severities`
ON `severities`.severity_id = `resources`.severity_id
LEFT JOIN `:dbstg`.`resources_tags` AS rtags
ON `rtags`.resource_id = `resources`.resource_id
INNER JOIN `:dbstg`.`instances`
ON `instances`.instance_id = `resources`.poller_id
WHERE resources.name NOT LIKE '\_Module\_%'
AND resources.parent_name NOT LIKE '\_Module\_BAM%'
AND resources.enabled = 1
AND resources.type != 3
SQL;
try {
$query .= $this->addResourceParentIdSubRequest($filter, $queryParametersFromRequestParameters);
} catch (ValueObjectException|CollectionException $exception) {
throw new RepositoryException(
message: 'An error occurred while adding the parent id subrequest',
previous: $exception
);
}
/**
* Resource Type filter
* 'service', 'metaservice', 'host'.
*/
$query .= $this->addResourceTypeSubRequest($filter);
foreach ($this->extraDataProviders as $provider) {
if ($provider->supportsExtraData($filter)) {
$query .= $provider->getSubFilter($filter);
}
}
/**
* Handle sort parameters.
*/
$query .= $this->sqlRequestTranslator->translateSortParameterToSql()
?: ' ORDER BY resources.status_ordered DESC, resources.name ASC';
/**
* Handle pagination.
*/
$query .= $this->sqlRequestTranslator->translatePaginationToSql();
try {
$queryResources = $this->translateDbName($query);
$queryParametersFromSearchValues = SearchRequestParametersTransformer::reverseToQueryParameters(
$this->sqlRequestTranslator->getSearchValues()
);
$queryParameters = $queryParametersFromSearchValues->mergeWith($queryParametersFromRequestParameters);
foreach ($this->connection->iterateAssociative($queryResources, $queryParameters) as $resourceRecord) {
/** @var array<string,int|string|null> $resourceRecord */
$this->resources[] = DbResourceFactory::createFromRecord($resourceRecord, $this->resourceTypes);
}
// get total without pagination
$queryTotal = $this->translateDbName('SELECT FOUND_ROWS() AS REALTIME from `:dbstg`.`resources`');
if (($total = $this->connection->fetchOne($queryTotal)) !== false) {
$this->sqlRequestTranslator->getRequestParameters()->setTotal((int) $total);
}
} catch (AssertionFailedException|TransformerException|CollectionException|ConnectionException $exception) {
throw new RepositoryException(
message: 'An error occurred while finding parent resources by id',
context: ['filter' => $filter],
previous: $exception
);
}
$iconIds = $this->getIconIdsFromResources();
$icons = $this->getIconsDataForResources($iconIds);
$this->completeResourcesWithIcons($icons);
return $this->resources;
}
/**
* @param ResourceFilter $filter
*
* @throws RepositoryException
* @return ResourceEntity[]
*/
public function findResources(ResourceFilter $filter): array
{
try {
$this->resources = [];
$queryParametersFromRequestParameter = new QueryParameters();
$query = $this->generateFindResourcesRequest(
filter: $filter,
queryParametersFromRequestParameter: $queryParametersFromRequestParameter
);
$this->find($query, $queryParametersFromRequestParameter);
return $this->resources;
} catch (\Throwable $exception) {
throw new RepositoryException(
message: 'An error occurred while finding resources',
context: ['filter' => $filter],
previous: $exception
);
}
}
/**
* @param ResourceFilter $filter
* @param array<int> $accessGroupIds
*
* @throws RepositoryException
* @return ResourceEntity[]
*/
public function findResourcesByAccessGroupIds(ResourceFilter $filter, array $accessGroupIds): array
{
try {
$this->resources = [];
$queryParametersFromRequestParameter = new QueryParameters();
$query = $this->generateFindResourcesRequest(
filter: $filter,
queryParametersFromRequestParameter: $queryParametersFromRequestParameter,
accessGroupIds: $accessGroupIds
);
$this->find($query, $queryParametersFromRequestParameter);
return $this->resources;
} catch (\Throwable $exception) {
throw new RepositoryException(
message: 'An error occurred while finding resources by access group ids',
context: ['filter' => $filter, 'accessGroupIds' => $accessGroupIds],
previous: $exception
);
}
}
/**
* @param ResourceFilter $filter
* @param int $maxResults
*
* @throws RepositoryException
* @return \Traversable<ResourceEntity>
*/
public function iterateResources(ResourceFilter $filter, int $maxResults = 0): \Traversable
{
try {
$this->resources = [];
// if $maxResults is set to 0, we use pagination and limit
if ($maxResults > 0) {
// for an export, we can have no pagination, so we limit the number of results in this case
// page is always 1 and limit is the maxResults
$this->sqlRequestTranslator->getRequestParameters()->setPage(1);
$this->sqlRequestTranslator->getRequestParameters()->setLimit($maxResults);
}
$queryParametersFromRequestParameter = new QueryParameters();
$query = $this->generateFindResourcesRequest(
filter: $filter,
queryParametersFromRequestParameter: $queryParametersFromRequestParameter
);
return $this->iterate($query, $queryParametersFromRequestParameter);
} catch (\Throwable $exception) {
throw new RepositoryException(
message: 'An error occurred while iterating resources by max results',
context: ['filter' => $filter, 'maxResults' => $maxResults],
previous: $exception
);
}
}
/**
* @param ResourceFilter $filter
* @param array<int> $accessGroupIds
* @param int $maxResults
*
* @throws RepositoryException
* @return \Traversable<ResourceEntity>
*/
public function iterateResourcesByAccessGroupIds(
ResourceFilter $filter,
array $accessGroupIds,
int $maxResults = 0,
): \Traversable {
try {
$this->resources = [];
// if $maxResults is set to 0, we use pagination and limit
if ($maxResults > 0) {
// for an export, we can have no pagination, so we limit the number of results in this case
// page is always 1 and limit is the maxResults
$this->sqlRequestTranslator->getRequestParameters()->setPage(1);
$this->sqlRequestTranslator->getRequestParameters()->setLimit($maxResults);
}
$queryParametersFromRequestParameter = new QueryParameters();
$query = $this->generateFindResourcesRequest(
filter: $filter,
queryParametersFromRequestParameter: $queryParametersFromRequestParameter,
accessGroupIds: $accessGroupIds
);
return $this->iterate($query, $queryParametersFromRequestParameter);
} catch (\Throwable $exception) {
throw new RepositoryException(
message: 'An error occurred while iterating resources by access group ids and max results',
context: ['filter' => $filter, 'accessGroupIds' => $accessGroupIds, 'maxResults' => $maxResults],
previous: $exception
);
}
}
/**
* @param ResourceFilter $filter
* @param bool $allPages
*
* @throws RepositoryException
* @return int
*/
public function countResourcesByFilter(ResourceFilter $filter, bool $allPages): int
{
if ($allPages) {
// For a count, there isn't pagination we limit the number of results
// page is always 1 and limit is the maxResults in case of an export
$this->sqlRequestTranslator->getRequestParameters()->setPage(1);
$this->sqlRequestTranslator->getRequestParameters()->setLimit(0);
}
try {
$queryParametersFromRequestParameter = new QueryParameters();
$query = $this->generateFindResourcesRequest(
filter: $filter,
queryParametersFromRequestParameter: $queryParametersFromRequestParameter,
onlyCount: true
);
return $this->count($query, $queryParametersFromRequestParameter);
} catch (\Throwable $exception) {
throw new RepositoryException(
message: 'An error occurred while counting resources by max results',
context: ['filter' => $filter],
previous: $exception
);
}
}
/**
* @param ResourceFilter $filter
* @param bool $allPages
* @param array<int> $accessGroupIds
*
* @throws RepositoryException
* @return int
*/
public function countResourcesByFilterAndAccessGroupIds(
ResourceFilter $filter,
bool $allPages,
array $accessGroupIds,
): int {
// if $allPages is set to true, we don't use pagination and limit because count all resources
if ($allPages) {
$this->sqlRequestTranslator->getRequestParameters()->setPage(1);
$this->sqlRequestTranslator->getRequestParameters()->setLimit(0);
}
try {
$queryParametersFromRequestParameter = new QueryParameters();
$query = $this->generateFindResourcesRequest(
filter: $filter,
queryParametersFromRequestParameter: $queryParametersFromRequestParameter,
accessGroupIds: $accessGroupIds,
onlyCount: true
);
return $this->count($query, $queryParametersFromRequestParameter);
} catch (\Throwable $exception) {
throw new RepositoryException(
message: 'An error occurred while counting resources by access group ids and max results',
context: ['filter' => $filter, 'accessGroupIds' => $accessGroupIds],
previous: $exception
);
}
}
/**
* @throws RepositoryException
* @return int
*/
public function countAllResources(): int
{
try {
$query = $this->connection->createQueryBuilder()
->select('COUNT(DISTINCT resources.resource_id) AS REALTIME')
->from('`:dbstg`.`resources`')
->getQuery();
return (int) $this->connection->fetchOne($this->translateDbName($query));
} catch (\Throwable $exception) {
throw new RepositoryException(
message: 'An error occurred while counting all resources',
previous: $exception
);
}
}
/**
* @param array<int> $accessGroupIds
*
* @throws RepositoryException
* @return int
*/
public function countAllResourcesByAccessGroupIds(array $accessGroupIds): int
{
try {
$accessGroupRequest = $this->addResourceAclSubRequest($accessGroupIds);
$query = $this->connection->createQueryBuilder()
->select('COUNT(DISTINCT resources.resource_id) AS REALTIME')
->from('`:dbstg`.`resources`')
->where($accessGroupRequest)
->getQuery();
return (int) $this->connection->fetchOne($this->translateDbName($query));
} catch (\Throwable $exception) {
throw new RepositoryException(
message: 'An error occurred while counting resources by access group ids and max results',
context: ['accessGroupIds' => $accessGroupIds],
previous: $exception
);
}
}
// ------------------------------------- PRIVATE METHODS -------------------------------------
/**
* @param ResourceFilter $filter
* @param QueryParameters $queryParametersFromRequestParameter
* @param int[] $accessGroupIds
* @param bool $onlyCount
*
* @throws CollectionException
* @throws RepositoryException
* @throws ValueObjectException
* @return string
*/
private function generateFindResourcesRequest(
ResourceFilter $filter,
QueryParameters $queryParametersFromRequestParameter,
array $accessGroupIds = [],
bool $onlyCount = false,
): string {
$this->sqlRequestTranslator->setConcordanceArray($this->resourceConcordances);
$query = $this->createQueryHeaders($filter, $queryParametersFromRequestParameter);
$resourceType = self::RESOURCE_TYPE_HOST;
$joinCtes = $query === ''
? ''
: ' INNER JOIN cte ON cte.resource_id = resources.resource_id ';
$query .= <<<SQL
SELECT :sql_query_find DISTINCT
1 AS REALTIME,
resources.resource_id,
resources.name,
resources.alias,
resources.address,
resources.id,
resources.internal_id,
resources.parent_id,
resources.parent_name,
parent_resource.resource_id AS `parent_resource_id`,
parent_resource.status AS `parent_status`,
parent_resource.alias AS `parent_alias`,
parent_resource.status_ordered AS `parent_status_ordered`,
parent_resource.address AS `parent_fqdn`,
severities.level AS `severity_level`,
severities.name AS `severity_name`,
severities.type AS `severity_type`,
severities.icon_id AS `severity_icon_id`,
resources.type,
resources.status,
resources.status_ordered,
resources.status_confirmed,
resources.in_downtime,
resources.acknowledged,
resources.passive_checks_enabled,
resources.active_checks_enabled,
resources.notifications_enabled,
resources.last_check,
resources.last_status_change,
resources.check_attempts,
resources.max_check_attempts,
resources.notes,
resources.notes_url,
resources.action_url,
resources.output,
resources.poller_id,
resources.has_graph,
instances.name AS `monitoring_server_name`,
resources.enabled,
resources.icon_id,
resources.severity_id,
resources.flapping,
resources.percent_state_change
FROM `:dbstg`.`resources`
INNER JOIN `:dbstg`.`instances`
ON `instances`.instance_id = `resources`.poller_id
{$joinCtes}
LEFT JOIN `:dbstg`.`resources` parent_resource
ON parent_resource.id = resources.parent_id
AND parent_resource.type = {$resourceType}
LEFT JOIN `:dbstg`.`severities`
ON `severities`.severity_id = `resources`.severity_id
LEFT JOIN `:dbstg`.`resources_tags` AS rtags
ON `rtags`.resource_id = `resources`.resource_id
SQL;
/**
* Handle search values.
*/
$searchSubRequest = null;
try {
$searchSubRequest .= $this->sqlRequestTranslator->translateSearchParameterToSql();
} catch (RequestParametersTranslatorException $exception) {
throw new RepositoryException(
message: 'An error occurred while generating the request',
previous: $exception
);
}
$query .= ! empty($searchSubRequest) ? $searchSubRequest . ' AND ' : ' WHERE ';
$query .= <<<SQL
resources.name NOT LIKE '\_Module\_%'
AND resources.parent_name NOT LIKE '\_Module\_BAM%'
AND resources.enabled = 1
AND resources.type != 3
SQL;
// Apply only_with_performance_data
if ($filter->getOnlyWithPerformanceData() === true) {
$query .= ' AND resources.has_graph = 1';
}
foreach ($this->extraDataProviders as $provider) {
$query .= $provider->getSubFilter($filter);
}
if ($accessGroupIds !== []) {
$query .= " AND {$this->addResourceAclSubRequest($accessGroupIds)}";
}
$query .= $this->addResourceParentIdSubRequest($filter, $queryParametersFromRequestParameter);
/**
* Resource Type filter
* 'service', 'metaservice', 'host'.
*/
$query .= $this->addResourceTypeSubRequest($filter);
/**
* State filter
* 'unhandled_problems', 'resource_problems', 'acknowledged', 'in_downtime'.
*/
$query .= $this->addResourceStateSubRequest($filter);
/**
* Status filter
* 'OK', 'WARNING', 'CRITICAL', 'UNKNOWN', 'UP', 'UNREACHABLE', 'DOWN', 'PENDING'.
*/
$query .= $this->addResourceStatusSubRequest($filter);
/**
* Status type filter
* 'HARD', 'SOFT'.
*/
$query .= $this->addStatusTypeSubRequest($filter);
/**
* Monitoring Server filter.
*/
$query .= $this->addMonitoringServerSubRequest($filter, $queryParametersFromRequestParameter);
/**
* Severity filter (levels and/or names).
*/
$query .= $this->addSeveritySubRequest($filter, $queryParametersFromRequestParameter);
if (! $onlyCount) {
/**
* Handle sort parameters.
*/
$query .= $this->sqlRequestTranslator->translateSortParameterToSql()
?: ' ORDER BY resources.status_ordered DESC, resources.name ASC';
}
/**
* Handle pagination.
*/
if ($this->sqlRequestTranslator->getRequestParameters()->getLimit() !== 0) {
$query .= $this->sqlRequestTranslator->translatePaginationToSql();
}
if ($onlyCount) {
$query = str_replace(':sql_query_find', '', $query);
$query = "SELECT COUNT(*) FROM ({$query}) AS temp";
} else {
$query = str_replace(':sql_query_find', 'SQL_CALC_FOUND_ROWS', $query);
}
return $query;
}
/**
* @param int[] $accessGroupIds
*
* @throws \InvalidArgumentException
*/
private function addResourceAclSubRequest(array $accessGroupIds): string
{
$orConditions = array_map(
static fn (ResourceACLProviderInterface $provider): string => $provider->buildACLSubRequest($accessGroupIds),
iterator_to_array($this->resourceACLProviders)
);
if ($orConditions === []) {
throw new \InvalidArgumentException(_('You must provide at least one ACL provider'));
}
return sprintf('(%s)', implode(' OR ', $orConditions));
}
/**
* @param ResourceFilter $filter
* @param QueryParameters $queryParametersFromRequestParameter
*
* @throws CollectionException
* @throws ValueObjectException
* @return string
*/
private function createQueryHeaders(
ResourceFilter $filter,
QueryParameters $queryParametersFromRequestParameter,
): string {
$headers = '';
$nextHeaders = function () use (&$headers): void {
$headers .= $headers !== '' ? ",\n" : 'WITH ';
};
$cteToIntersect = [];
// Create CTE for each tag type
if ($filter->getHostgroupNames() !== []) {
$cteToIntersect[] = 'host_groups';
$hostGroupKeys = [];
foreach ($filter->getHostgroupNames() as $index => $hostGroupName) {
$key = ":host_group_{$index}";
$queryParametersFromRequestParameter->add($key, QueryParameter::string($key, $hostGroupName));
$hostGroupKeys[] = $key;
}
$hostGroupPrepareKeys = implode(', ', $hostGroupKeys);
$headers = <<<SQL
WITH host_groups AS (
SELECT resources.resource_id
FROM `:dbstg`.`resources` AS resources
INNER JOIN `:dbstg`.`resources_tags` AS rtags
ON rtags.resource_id = resources.resource_id
INNER JOIN `:dbstg`.`tags` AS tags
ON tags.tag_id = rtags.tag_id
WHERE tags.type = 1
AND resources.enabled = 1
AND tags.name IN ({$hostGroupPrepareKeys})
GROUP BY resources.resource_id
UNION
SELECT resources.resource_id
FROM `:dbstg`.`resources` AS resources
INNER JOIN `:dbstg`.`resources` AS parent_resource
ON parent_resource.id = resources.parent_id
INNER JOIN `:dbstg`.`resources_tags` AS rtags
ON rtags.resource_id = parent_resource.resource_id
INNER JOIN `:dbstg`.`tags` AS tags
ON tags.tag_id = rtags.tag_id
WHERE tags.type = 1
AND tags.name IN ({$hostGroupPrepareKeys})
AND resources.enabled = 1
AND parent_resource.enabled = 1
AND parent_resource.type = 1
GROUP BY resources.resource_id
)
SQL;
}
if ($filter->getHostCategoryNames() !== []) {
$cteToIntersect[] = 'host_categories';
$hostCategoriesKeys = [];
foreach ($filter->getHostCategoryNames() as $index => $hostCategoryName) {
$key = ":host_category_{$index}";
$queryParametersFromRequestParameter->add($key, QueryParameter::string($key, $hostCategoryName));
$hostCategoriesKeys[] = $key;
}
$hostCategoryPrepareKeys = implode(', ', $hostCategoriesKeys);
$nextHeaders();
$headers .= <<<SQL
host_categories AS (
SELECT resources.resource_id
FROM `:dbstg`.`resources` AS resources
INNER JOIN `:dbstg`.`resources_tags` AS rtags
ON rtags.resource_id = resources.resource_id
INNER JOIN `:dbstg`.`tags` AS tags
ON tags.tag_id = rtags.tag_id
WHERE tags.type = 3
AND resources.enabled = 1
AND tags.name IN ({$hostCategoryPrepareKeys})
GROUP BY resources.resource_id
UNION
SELECT resources.resource_id
FROM `:dbstg`.`resources` AS resources
INNER JOIN `:dbstg`.`resources` AS parent_resource
ON parent_resource.id = resources.parent_id
INNER JOIN `:dbstg`.`resources_tags` AS rtags
ON rtags.resource_id = parent_resource.resource_id
INNER JOIN `:dbstg`.`tags` AS tags
ON tags.tag_id = rtags.tag_id
WHERE tags.type = 3
AND tags.name IN ({$hostCategoryPrepareKeys})
AND resources.enabled = 1
AND parent_resource.enabled = 1
AND parent_resource.type = 1
GROUP BY resources.resource_id
)
SQL;
}
if ($filter->getServicegroupNames() !== []) {
$cteToIntersect[] = 'service_groups';
$serviceGroupKeys = [];
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Resources/Infrastructure/Repository/ExtraDataProviders/ExtraDataProviderInterface.php | centreon/src/Core/Resources/Infrastructure/Repository/ExtraDataProviders/ExtraDataProviderInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Infrastructure\Repository\ExtraDataProviders;
use Centreon\Domain\Monitoring\Resource as ResourceEntity;
use Centreon\Domain\Monitoring\ResourceFilter;
interface ExtraDataProviderInterface
{
/**
* @param ResourceFilter $filter
*
* @return string
*/
public function getSubFilter(ResourceFilter $filter): string;
/**
* @param ResourceFilter $filter
* @param ResourceEntity[] $resources
*
* @return mixed[]
*/
public function getExtraDataForResources(ResourceFilter $filter, array $resources): array;
/**
* @return string
*/
public function getExtraDataSourceName(): string;
/**
* Indicates regarding the data set in the ResourceFilter if the provider should add or not extra data to resources.
*
* @param ResourceFilter $filter
*
* @return bool
*/
public function supportsExtraData(ResourceFilter $filter): 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/Resources/Infrastructure/Repository/ResourceACLProviders/MetaServiceACLProvider.php | centreon/src/Core/Resources/Infrastructure/Repository/ResourceACLProviders/MetaServiceACLProvider.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Infrastructure\Repository\ResourceACLProviders;
use Core\Domain\RealTime\Model\ResourceTypes\MetaServiceResourceType;
class MetaServiceACLProvider implements ResourceACLProviderInterface
{
public function buildACLSubRequest(array $accessGroupIds): string
{
$requestPattern = 'EXISTS (
SELECT 1
FROM `:dbstg`.centreon_acl acl
WHERE
resources.type = %d
AND resources.parent_id = acl.host_id
AND resources.id = acl.service_id
AND acl.group_id IN (%s)
)';
return sprintf($requestPattern, MetaServiceResourceType::TYPE_ID, implode(', ', $accessGroupIds));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Resources/Infrastructure/Repository/ResourceACLProviders/HostACLProvider.php | centreon/src/Core/Resources/Infrastructure/Repository/ResourceACLProviders/HostACLProvider.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Infrastructure\Repository\ResourceACLProviders;
use Core\Domain\RealTime\Model\ResourceTypes\HostResourceType;
class HostACLProvider implements ResourceACLProviderInterface
{
public function buildACLSubRequest(array $accessGroupIds): string
{
$requestPattern = 'EXISTS (
SELECT 1
FROM `:dbstg`.centreon_acl acl
WHERE
resources.type = %d
AND resources.id = acl.host_id
AND acl.group_id IN (%s)
)';
return sprintf($requestPattern, HostResourceType::TYPE_ID, implode(', ', $accessGroupIds));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Resources/Infrastructure/Repository/ResourceACLProviders/ServiceACLProvider.php | centreon/src/Core/Resources/Infrastructure/Repository/ResourceACLProviders/ServiceACLProvider.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Infrastructure\Repository\ResourceACLProviders;
use Core\Domain\RealTime\Model\ResourceTypes\ServiceResourceType;
class ServiceACLProvider implements ResourceACLProviderInterface
{
public function buildACLSubRequest(array $accessGroupIds): string
{
$requestPattern = 'EXISTS (
SELECT 1
FROM `:dbstg`.centreon_acl acl
WHERE
resources.type = %d
AND resources.parent_id = acl.host_id
AND resources.id = acl.service_id
AND acl.group_id IN (%s)
)';
return sprintf($requestPattern, ServiceResourceType::TYPE_ID, implode(', ', $accessGroupIds));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Resources/Infrastructure/Repository/ResourceACLProviders/ResourceACLProviderInterface.php | centreon/src/Core/Resources/Infrastructure/Repository/ResourceACLProviders/ResourceACLProviderInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Infrastructure\Repository\ResourceACLProviders;
interface ResourceACLProviderInterface
{
/**
* Build ACL sub request regarding access groups IDs for the given resource type.
*
* @param int[] $accessGroupIds
*
* @return string
*/
public function buildACLSubRequest(array $accessGroupIds): 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/Resources/Infrastructure/API/ExtraDataNormalizer/ExtraDataNormalizerInterface.php | centreon/src/Core/Resources/Infrastructure/API/ExtraDataNormalizer/ExtraDataNormalizerInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Infrastructure\API\ExtraDataNormalizer;
interface ExtraDataNormalizerInterface
{
/**
* @param mixed $data
*
* @return mixed[]
*/
public function normalizeExtraDataForResource(mixed $data): array;
/**
* @return string
*/
public function getExtraDataSourceName(): string;
/**
* @param string $providerName
*
* @return bool
*/
public function isValidFor(string $providerName): 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/Resources/Infrastructure/API/CountResources/CountResourcesController.php | centreon/src/Core/Resources/Infrastructure/API/CountResources/CountResourcesController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Infrastructure\API\CountResources;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Monitoring\ResourceFilter;
use Core\Resources\Application\UseCase\CountResources\CountResources;
use Core\Resources\Application\UseCase\CountResources\CountResourcesRequest;
use Core\Resources\Infrastructure\API\FindResources\FindResourcesRequestValidator as RequestValidator;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\MapQueryString;
/**
* @phpstan-import-type _RequestParameters from RequestValidator
*/
final class CountResourcesController extends AbstractController
{
/**
* CountResourcesController constructor
*
* @param ContactInterface $contact
* @param RequestValidator $validator
*/
public function __construct(
private readonly ContactInterface $contact,
private readonly RequestValidator $validator,
) {
}
/**
* @param CountResources $useCase
* @param CountResourcesPresenterJson $presenter
* @param Request $request
* @param CountResourcesInput $input
*
* @return Response
*/
public function __invoke(
CountResources $useCase,
CountResourcesPresenterJson $presenter,
Request $request,
#[MapQueryString(validationFailedStatusCode: Response::HTTP_UNPROCESSABLE_ENTITY)]
CountResourcesInput $input,
): Response {
$useCaseRequest = $this->createCountRequest($request, $input);
$useCase($useCaseRequest, $presenter);
return $presenter->show();
}
// -------------------------------- PRIVATE METHODS --------------------------------
/**
* @param Request $request
* @param CountResourcesInput $input
*
* @return CountResourcesRequest
*/
private function createCountRequest(Request $request, CountResourcesInput $input): CountResourcesRequest
{
$filter = $this->validator->validateAndRetrieveRequestParameters($request->query->all(), true);
$resourceFilter = $this->createResourceFilter($filter);
return CountResourcesRequestTransformer::transform(
input: $input,
resourceFilter: $resourceFilter,
contact: $this->contact
);
}
/**
* @param _RequestParameters $filter
*
* @return ResourceFilter
*/
private function createResourceFilter(array $filter): ResourceFilter
{
return (new ResourceFilter())
->setTypes($filter[RequestValidator::PARAM_RESOURCE_TYPE])
->setStates($filter[RequestValidator::PARAM_STATES])
->setStatuses($filter[RequestValidator::PARAM_STATUSES])
->setStatusTypes($filter[RequestValidator::PARAM_STATUS_TYPES])
->setServicegroupNames($filter[RequestValidator::PARAM_SERVICEGROUP_NAMES])
->setServiceCategoryNames($filter[RequestValidator::PARAM_SERVICE_CATEGORY_NAMES])
->setServiceSeverityNames($filter[RequestValidator::PARAM_SERVICE_SEVERITY_NAMES])
->setServiceSeverityLevels($filter[RequestValidator::PARAM_SERVICE_SEVERITY_LEVELS])
->setHostgroupNames($filter[RequestValidator::PARAM_HOSTGROUP_NAMES])
->setHostCategoryNames($filter[RequestValidator::PARAM_HOST_CATEGORY_NAMES])
->setHostSeverityNames($filter[RequestValidator::PARAM_HOST_SEVERITY_NAMES])
->setMonitoringServerNames($filter[RequestValidator::PARAM_MONITORING_SERVER_NAMES])
->setHostSeverityLevels($filter[RequestValidator::PARAM_HOST_SEVERITY_LEVELS])
->setOnlyWithPerformanceData($filter[RequestValidator::PARAM_RESOURCES_ON_PERFORMANCE_DATA_AVAILABILITY])
->setOnlyWithTicketsOpened($filter[RequestValidator::PARAM_RESOURCES_WITH_OPENED_TICKETS])
->setRuleId($filter[RequestValidator::PARAM_OPEN_TICKET_RULE_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/Resources/Infrastructure/API/CountResources/CountResourcesRequestTransformer.php | centreon/src/Core/Resources/Infrastructure/API/CountResources/CountResourcesRequestTransformer.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Infrastructure\API\CountResources;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Monitoring\ResourceFilter;
use Core\Resources\Application\UseCase\CountResources\CountResourcesRequest;
/**
* Class
*
* @class CountResourcesRequestTransformer
* @package Core\Resources\Infrastructure\API\CountResources
*/
final readonly class CountResourcesRequestTransformer
{
/**
* @param CountResourcesInput $input
* @param ResourceFilter $resourceFilter
* @param ContactInterface $contact
*
* @return CountResourcesRequest
*/
public static function transform(
CountResourcesInput $input,
ResourceFilter $resourceFilter,
ContactInterface $contact,
): CountResourcesRequest {
return new CountResourcesRequest(
resourceFilter: $resourceFilter,
allPages: $input->allPages,
contactId: $contact->getId(),
isAdmin: $contact->isAdmin()
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Resources/Infrastructure/API/CountResources/CountResourcesInputDenormalizer.php | centreon/src/Core/Resources/Infrastructure/API/CountResources/CountResourcesInputDenormalizer.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Infrastructure\API\CountResources;
use Symfony\Component\Serializer\Exception\ExceptionInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
/**
* Class
*
* @class CountResourcesInputDenormalizer
* @package Core\Resources\Infrastructure\API\CountResources
*/
class CountResourcesInputDenormalizer implements DenormalizerInterface, DenormalizerAwareInterface
{
use DenormalizerAwareTrait;
private const ALREADY_CALL = self::class . 'already_called';
/**
* @param mixed $data
* @param string $type
* @param string|null $format
* @param array<string,mixed> $context
*
* @throws ExceptionInterface
* @return CountResourcesInput
*/
public function denormalize(
mixed $data,
string $type,
?string $format = null,
array $context = [],
): CountResourcesInput {
$context[self::ALREADY_CALL] = true;
if (isset($data['all_pages']) && $data['all_pages'] !== '') {
$data['all_pages']
= filter_var($data['all_pages'], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)
?? $data['all_pages'];
}
if (isset($data['page'])) {
$data['page']
= filter_var($data['page'], FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE)
?? $data['page'];
}
if (isset($data['limit'])) {
$data['limit']
= filter_var($data['limit'], FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE)
?? $data['limit'];
}
return $this->denormalizer->denormalize($data, $type, $format, $context);
}
/**
* @param mixed $data
* @param string $type
* @param string|null $format
* @param array<string,mixed> $context
*
* @return bool
*/
public function supportsDenormalization(
mixed $data,
string $type,
?string $format = null,
array $context = [],
): bool {
if ($context[self::ALREADY_CALL] ?? false) {
return false;
}
return $type === CountResourcesInput::class && is_array($data);
}
/**
* @param ?string $format
* @return array<class-string|'*'|'object'|string, bool|null>
*/
public function getSupportedTypes(?string $format): array
{
return [
CountResourcesInput::class => 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/Resources/Infrastructure/API/CountResources/CountResourcesPresenterJson.php | centreon/src/Core/Resources/Infrastructure/API/CountResources/CountResourcesPresenterJson.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Resources\Infrastructure\API\CountResources;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Domain\RequestParameters\RequestParameters;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Common\Infrastructure\ExceptionLogger\ExceptionLogger;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Resources\Application\UseCase\CountResources\CountResourcesPresenterInterface;
use Core\Resources\Application\UseCase\CountResources\CountResourcesResponse;
/**
* Class
*
* @class CountResourcesPresenterJson
* @package Core\Resources\Infrastructure\API\CountResources
*/
class CountResourcesPresenterJson extends AbstractPresenter implements CountResourcesPresenterInterface
{
/**
* CountResourcesPresenterJson constructor
*
* @param PresenterFormatterInterface $presenterFormatter
* @param RequestParametersInterface $requestParameters
* @param ExceptionLogger $exceptionLogger
*/
public function __construct(
PresenterFormatterInterface $presenterFormatter,
protected RequestParametersInterface $requestParameters,
private readonly ExceptionLogger $exceptionLogger,
) {
parent::__construct($presenterFormatter);
}
/**
* @param CountResourcesResponse|ResponseStatusInterface $response
*
* @return void
*/
public function presentResponse(CountResourcesResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
if ($response instanceof ErrorResponse && ! is_null($response->getException())) {
$this->exceptionLogger->log($response->getException());
}
$this->setResponseStatus($response);
return;
}
$search = $this->requestParameters->toArray()[RequestParameters::NAME_FOR_SEARCH] ?? [];
$this->present(
[
'count' => $response->getTotalFilteredResources(),
'meta' => [
'search' => $search,
'total' => $response->getTotalResources(),
],
]
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.