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/Domain/Common/AbstractHandler.php | centreon/src/Core/Domain/Common/AbstractHandler.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\Common;
/**
* Implements the chain of responsibility pattern.
*/
class AbstractHandler implements HandlerInterface
{
private ?HandlerInterface $nextHandle = null;
/**
* @param string|object $message
*
* @return string|object|null
*/
public function handle(mixed $message): mixed
{
return $this->nextHandle ? $this->nextHandle->handle($message) : $message;
}
/**
* @param HandlerInterface $nextHandler
*
* @return HandlerInterface
*/
public function setNext(HandlerInterface $nextHandler): HandlerInterface
{
return $this->nextHandle = $nextHandler;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Domain/Common/HandlerInterface.php | centreon/src/Core/Domain/Common/HandlerInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\Common;
interface HandlerInterface
{
/**
* @param HandlerInterface $nextHandler
*
* @return HandlerInterface
*/
public function setNext(self $nextHandler): self;
/**
* @param string|object $message
*
* @return string|object|null
*/
public function handle(mixed $message): mixed;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Domain/Exception/InvalidGeoCoordException.php | centreon/src/Core/Domain/Exception/InvalidGeoCoordException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\Exception;
use Centreon\Domain\Common\Assertion\AssertionException;
final class InvalidGeoCoordException extends AssertionException
{
/**
* @return static
*/
public static function invalidValues(): self
{
return new self(_('Invalid coordinates values specified'));
}
/**
* @return static
*/
public static function invalidFormat(): self
{
return new self(_('Invalid coordinates format specified'));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Domain/Engine/Model/EngineCommandGenerator.php | centreon/src/Core/Domain/Engine/Model/EngineCommandGenerator.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\Engine\Model;
use Core\Domain\Common\HandlerInterface;
class EngineCommandGenerator
{
/** @var HandlerInterface[] */
private array $handlers = [];
/**
* @param \Traversable<HandlerInterface> $handlers
*/
public function __construct(\Traversable $handlers)
{
foreach ($handlers as $handler) {
$this->addHandler($handler);
}
}
/**
* Add a new command handler.
*
* @param HandlerInterface $handler
*/
public function addHandler(HandlerInterface $handler): void
{
if ($this->handlers === []) {
$this->handlers[] = $handler;
} else {
$lastHandler = $this->handlers[array_key_last($this->handlers)];
$this->handlers[] = $lastHandler->setNext($handler);
}
}
/**
* Gets the Engine command according to the different handlers who might want to modify it.
*
* @param string $command
*
* @return string
*/
public function getEngineCommand(string $command): string
{
if ($this->handlers === []) {
return $command;
}
/** @var string|null $result */
$result = $this->handlers[0]->handle($command);
return (string) $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Broker/Application/UseCase/AddBrokerInputOutput/BrokerInputOutputValidator.php | centreon/src/Core/Broker/Application/UseCase/AddBrokerInputOutput/BrokerInputOutputValidator.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Broker\Application\UseCase\AddBrokerInputOutput;
use Core\Broker\Application\Exception\BrokerException;
use Core\Broker\Application\Repository\ReadBrokerRepositoryInterface;
use Core\Broker\Domain\Model\BrokerInputOutputField;
class BrokerInputOutputValidator
{
public function __construct(
private readonly ReadBrokerRepositoryInterface $readBrokerRepository,
) {
}
public function brokerIsValidOrFail(int $brokerId): void
{
if (! ($this->readBrokerRepository->exists($brokerId))) {
throw BrokerException::notFound($brokerId);
}
}
/**
* @param array<string,BrokerInputOutputField|array<string,BrokerInputOutputField>> $fields
* @param array<string,mixed> $values
*
* @throws BrokerException
*/
public function validateParameters(array $fields, array $values): void
{
foreach ($fields as $fieldName => $fieldInfo) {
if (is_array($fieldInfo)) {
if (($subField = current($fieldInfo)) && $subField->getType() === 'multiselect') {
// multiselect Field
$composedName = "{$fieldName}_{$subField->getName()}";
if (! array_key_exists($composedName, $values)) {
throw BrokerException::missingParameter($composedName);
}
if (! is_array($values[$composedName])) {
throw BrokerException::invalidParameterType($composedName, $values[$composedName]);
}
foreach ($values[$composedName] as $subValue) {
if (! is_string($subValue)) {
throw BrokerException::invalidParameterType($composedName, $subValue);
}
if (! in_array($subValue, $subField->getListValues(), true)) {
throw BrokerException::invalidParameter($composedName, $subValue);
}
}
} else {
// grouped fields
if (! array_key_exists($fieldName, $values)) {
throw BrokerException::missingParameter($fieldName);
}
if (! is_array($values[$fieldName])) {
throw BrokerException::invalidParameterType(
"{$fieldName}",
$values[$fieldName]
);
}
foreach ($values[$fieldName] as $groupedValues) {
foreach ($fieldInfo as $groupedFieldName => $groupFieldInfo) {
if (! array_key_exists($groupedFieldName, $groupedValues)) {
throw BrokerException::missingParameter("{$fieldName}[].{$groupedFieldName}");
}
$this->validateFieldOrFail(
name: "{$fieldName}[].{$groupedFieldName}",
value: $groupedValues[$groupedFieldName],
field: $groupFieldInfo
);
}
}
}
} else {
// simple field
if (! array_key_exists($fieldName, $values)) {
throw BrokerException::missingParameter($fieldName);
}
$this->validateFieldOrFail($fieldName, $values[$fieldName], $fieldInfo);
}
}
}
/**
* @param string $name
* @param mixed $value
* @param BrokerInputOutputField $field
*
* @throws BrokerException
*/
private function validateFieldOrFail(string $name, mixed $value, BrokerInputOutputField $field): void
{
if ($field->isRequired() && (! isset($value) || $value === '')) {
throw BrokerException::missingParameter($name);
}
$isValid = match ($field->getType()) {
'int' => $value === null || is_int($value),
'text', 'password' => $value === null || is_string($value),
'select', 'radio' => in_array($value, $field->getListValues(), true),
default => false,
};
if ($isValid === false) {
throw BrokerException::invalidParameter($name, $value);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Broker/Application/UseCase/AddBrokerInputOutput/AddBrokerInputOutputPresenterInterface.php | centreon/src/Core/Broker/Application/UseCase/AddBrokerInputOutput/AddBrokerInputOutputPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Broker\Application\UseCase\AddBrokerInputOutput;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface AddBrokerInputOutputPresenterInterface
{
public function presentResponse(AddBrokerInputOutputResponse|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/Broker/Application/UseCase/AddBrokerInputOutput/AddBrokerInputOutputResponse.php | centreon/src/Core/Broker/Application/UseCase/AddBrokerInputOutput/AddBrokerInputOutputResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Broker\Application\UseCase\AddBrokerInputOutput;
/**
* @phpstan-import-type _BrokerInputOutputParameter from \Core\Broker\Domain\Model\BrokerInputOutput
*/
final class AddBrokerInputOutputResponse
{
/**
* @param int $id
* @param int $brokerId
* @param string $name
* @param TypeDto $type
* @param _BrokerInputOutputParameter[] $parameters
*/
public function __construct(
public int $id = 0,
public int $brokerId = 0,
public string $name = '',
public TypeDto $type = new TypeDto(),
public array $parameters = [],
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Broker/Application/UseCase/AddBrokerInputOutput/AddBrokerInputOutput.php | centreon/src/Core/Broker/Application/UseCase/AddBrokerInputOutput/AddBrokerInputOutput.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Broker\Application\UseCase\AddBrokerInputOutput;
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\Broker\Application\Exception\BrokerException;
use Core\Broker\Application\Repository\ReadBrokerInputOutputRepositoryInterface;
use Core\Broker\Application\Repository\WriteBrokerInputOutputRepositoryInterface;
use Core\Broker\Domain\Model\BrokerInputOutput;
use Core\Broker\Domain\Model\BrokerInputOutputField;
use Core\Broker\Domain\Model\NewBrokerInputOutput;
use Core\Common\Application\Repository\WriteVaultRepositoryInterface;
use Core\Common\Application\UseCase\VaultTrait;
use Core\Common\Infrastructure\FeatureFlags;
use Core\Common\Infrastructure\Repository\AbstractVaultRepository;
/**
* @phpstan-import-type _BrokerInputOutputParameter from \Core\Broker\Domain\Model\BrokerInputOutput
*/
final class AddBrokerInputOutput
{
use LoggerTrait;
use VaultTrait;
public function __construct(
private readonly WriteBrokerInputOutputRepositoryInterface $writeOutputRepository,
private readonly ReadBrokerInputOutputRepositoryInterface $readOutputRepository,
private readonly ContactInterface $user,
private readonly BrokerInputOutputValidator $validator,
private readonly WriteVaultRepositoryInterface $writeVaultRepository,
private readonly FeatureFlags $flags,
) {
$this->writeVaultRepository->setCustomPath(AbstractVaultRepository::BROKER_VAULT_PATH);
}
/**
* @param AddBrokerInputOutputRequest $request
* @param AddBrokerInputOutputPresenterInterface $presenter
*/
public function __invoke(AddBrokerInputOutputRequest $request, AddBrokerInputOutputPresenterInterface $presenter): void
{
try {
if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_BROKER_RW)) {
$this->error(
"User doesn't have sufficient rights to add a broker output",
['user_id' => $this->user->getId()]
);
$presenter->presentResponse(
new ForbiddenResponse(BrokerException::editNotAllowed()->getMessage())
);
return;
}
$this->validator->brokerIsValidOrFail($request->brokerId);
if (
null === ($type = $this->readOutputRepository->findType($request->tag, $request->type))
|| [] === ($outputFields = $this->readOutputRepository->findParametersByType($request->type))
) {
throw BrokerException::idDoesNotExist('type', $request->type);
}
$this->validator->validateParameters($outputFields, $request->parameters);
/** @var _BrokerInputOutputParameter[] $validatedParameters */
$validatedParameters = $request->parameters;
$newOutput = new NewBrokerInputOutput(
tag: $request->tag,
type: $type,
name: $request->name,
parameters: $validatedParameters
);
if ($this->flags->isEnabled('vault_broker') && $this->writeVaultRepository->isVaultConfigured() === true) {
$this->uuid = $this->getBrokerVaultUuid($request->brokerId);
$newOutput = $this->saveInVault($newOutput, $outputFields);
}
$outputId = $this->writeOutputRepository->add(
$newOutput,
$request->brokerId,
$outputFields
);
if (! ($output = $this->readOutputRepository->findByIdAndBrokerId(
$request->tag,
$outputId,
$request->brokerId
))) {
throw BrokerException::inputOutputNotFound($request->brokerId, $outputId);
}
$presenter->presentResponse(
$this->createResponse($output, $request->brokerId)
);
} catch (AssertionFailedException $ex) {
$presenter->presentResponse(new InvalidArgumentResponse($ex));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (BrokerException $ex) {
$presenter->presentResponse(
match ($ex->getCode()) {
BrokerException::CODE_CONFLICT => new ConflictResponse($ex),
BrokerException::CODE_INVALID => new InvalidArgumentResponse($ex),
default => new ErrorResponse($ex),
}
);
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (\Throwable $ex) {
$presenter->presentResponse(
new ErrorResponse(BrokerException::addBrokerInputOutput())
);
$this->error((string) $ex);
}
}
private function createResponse(BrokerInputOutput $output, int $brokerId): AddBrokerInputOutputResponse
{
return new AddBrokerInputOutputResponse(
id: $output->getId(),
brokerId: $brokerId,
name: $output->getName(),
type: new TypeDto($output->getType()->id, $output->getType()->name),
parameters: $output->getParameters()
);
}
private function getBrokerVaultUuid(int $configId): ?string
{
$vaultPath = $this->readOutputRepository->findVaultPathByBrokerId($configId);
if ($vaultPath === null) {
return null;
}
return $this->getUuidFromPath($vaultPath);
}
/**
* @param NewBrokerInputOutput $inputOutput
* @param array<string,BrokerInputOutputField|array<string,BrokerInputOutputField>> $inputOutputFields
*
* @return NewBrokerInputOutput
*/
private function saveInVault(NewBrokerInputOutput $inputOutput, array $inputOutputFields): NewBrokerInputOutput
{
$updatedParameters = $inputOutput->getParameters();
foreach ($updatedParameters as $paramName => $paramValue) {
if (is_array($inputOutputFields[$paramName])) {
if (! is_array($paramValue)) {
// for phpstan, should not happen.
continue;
}
foreach ($paramValue as $groupIndex => $groupedParams) {
if (isset($groupedParams['type']) && $groupedParams['type'] === 'password') {
/** @var array{type:string,name:string,value:string|int} $groupedParams */
$vaultKey = implode('_', [$inputOutput->getName(), $paramName, $groupedParams['name']]);
$vaultPaths = $this->writeVaultRepository->upsert(
$this->uuid,
[$vaultKey => $groupedParams['value']],
[]
);
$vaultPath = $vaultPaths[$vaultKey];
$this->uuid ??= $this->getUuidFromPath($vaultPath);
/** @var array<array<array{value:string}>> $updatedParameters */
$updatedParameters[$paramName][$groupIndex]['value'] = $vaultPath;
}
}
} elseif (
array_key_exists($paramName, $inputOutputFields)
&& $inputOutputFields[$paramName]->getType() === 'password'
) {
if (! is_string($paramValue) && ! is_int($paramValue)) {
// for phpstan, should not happen.
continue;
}
$vaultKey = implode('_', [$inputOutput->getName(), $paramName]);
$vaultPaths = $this->writeVaultRepository->upsert($this->uuid, [$vaultKey => $paramValue], []);
$vaultPath = $vaultPaths[$vaultKey];
$this->uuid ??= $this->getUuidFromPath($vaultPath);
$updatedParameters[$paramName] = $vaultPath;
}
}
return new NewBrokerInputOutput(
tag: $inputOutput->getTag(),
type: $inputOutput->getType(),
name: $inputOutput->getName(),
parameters: $updatedParameters,
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Broker/Application/UseCase/AddBrokerInputOutput/AddBrokerInputOutputRequest.php | centreon/src/Core/Broker/Application/UseCase/AddBrokerInputOutput/AddBrokerInputOutputRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Broker\Application\UseCase\AddBrokerInputOutput;
final class AddBrokerInputOutputRequest
{
public int $brokerId = 0;
public string $tag = 'output';
public string $name = '';
public int $type = 0;
/** @var array<string,mixed> */
public array $parameters = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Broker/Application/UseCase/AddBrokerInputOutput/TypeDto.php | centreon/src/Core/Broker/Application/UseCase/AddBrokerInputOutput/TypeDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Broker\Application\UseCase\AddBrokerInputOutput;
final class TypeDto
{
public function __construct(
public int $id = 0,
public string $name = '',
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Broker/Application/UseCase/UpdateStreamConnectorFile/UpdateStreamConnectorFileResponse.php | centreon/src/Core/Broker/Application/UseCase/UpdateStreamConnectorFile/UpdateStreamConnectorFileResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Broker\Application\UseCase\UpdateStreamConnectorFile;
final class UpdateStreamConnectorFileResponse
{
/**
* @param string $path
*/
public function __construct(
public string $path = '',
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Broker/Application/UseCase/UpdateStreamConnectorFile/UpdateStreamConnectorFilePresenterInterface.php | centreon/src/Core/Broker/Application/UseCase/UpdateStreamConnectorFile/UpdateStreamConnectorFilePresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Broker\Application\UseCase\UpdateStreamConnectorFile;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface UpdateStreamConnectorFilePresenterInterface
{
public function presentResponse(UpdateStreamConnectorFileResponse|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/Broker/Application/UseCase/UpdateStreamConnectorFile/UpdateStreamConnectorFileRequest.php | centreon/src/Core/Broker/Application/UseCase/UpdateStreamConnectorFile/UpdateStreamConnectorFileRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Broker\Application\UseCase\UpdateStreamConnectorFile;
final class UpdateStreamConnectorFileRequest
{
public int $brokerId = 0;
public int $outputId = 0;
public string $fileContent = '';
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Broker/Application/UseCase/UpdateStreamConnectorFile/UpdateStreamConnectorFile.php | centreon/src/Core/Broker/Application/UseCase/UpdateStreamConnectorFile/UpdateStreamConnectorFile.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Broker\Application\UseCase\UpdateStreamConnectorFile;
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\Broker\Application\Exception\BrokerException;
use Core\Broker\Application\Repository\ReadBrokerInputOutputRepositoryInterface;
use Core\Broker\Application\Repository\WriteBrokerInputOutputRepositoryInterface;
use Core\Broker\Application\Repository\WriteBrokerRepositoryInterface;
use Core\Broker\Domain\Model\BrokerInputOutput;
final class UpdateStreamConnectorFile
{
use LoggerTrait;
public function __construct(
private readonly WriteBrokerInputOutputRepositoryInterface $writeOutputRepository,
private readonly ReadBrokerInputOutputRepositoryInterface $readOutputRepository,
private readonly WriteBrokerRepositoryInterface $fileRepository,
private readonly ContactInterface $user,
) {
}
/**
* @param UpdateStreamConnectorFileRequest $request
* @param UpdateStreamConnectorFilePresenterInterface $presenter
*/
public function __invoke(UpdateStreamConnectorFileRequest $request, UpdateStreamConnectorFilePresenterInterface $presenter): void
{
try {
if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_BROKER_RW)) {
$this->error(
"User doesn't have sufficient rights to edit a broker output",
['user_id' => $this->user->getId()]
);
$presenter->presentResponse(
new ForbiddenResponse(BrokerException::editNotAllowed()->getMessage())
);
return;
}
if (! ($output = $this->readOutputRepository->findByIdAndBrokerId('output', $request->outputId, $request->brokerId))) {
throw BrokerException::inputOutputNotFound($request->brokerId, $request->outputId);
}
if ($output->getType()->name !== 'lua') {
throw BrokerException::outputTypeInvalidForThisAction($output->getType()->name);
}
if (! \json_decode($request->fileContent)) {
throw BrokerException::invalidJsonContent();
}
$filePath = $this->createFile($request->fileContent);
$this->deletePreviousFile($output);
$this->updateOutput($request->brokerId, $output, $filePath);
$presenter->presentResponse(
new UpdateStreamConnectorFileResponse($filePath)
);
} catch (AssertionFailedException $ex) {
$presenter->presentResponse(new InvalidArgumentResponse($ex));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (BrokerException $ex) {
$presenter->presentResponse(
match ($ex->getCode()) {
BrokerException::CODE_CONFLICT => new ConflictResponse($ex),
default => new ErrorResponse($ex),
}
);
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (\Throwable $ex) {
$presenter->presentResponse(
new ErrorResponse(BrokerException::updateBrokerInputOutput())
);
$this->error((string) $ex);
}
}
private function createFile(string $content): string
{
$timestamp = time();
$filePath = "/var/lib/centreon/stream_connector_{$timestamp}.json";
try {
$this->fileRepository->create($filePath, $content);
} catch (\Throwable $ex) {
$this->error((string) $ex);
throw BrokerException::errorWhenCreatingFile($filePath);
}
return $filePath;
}
private function deletePreviousFile(BrokerInputOutput $output): void
{
$pathParameter = $output->getParameters()['path'] ?? null;
if ($pathParameter && is_string($pathParameter)) {
try {
$this->fileRepository->delete($pathParameter);
} catch (\Throwable $ex) {
$this->info('Could not delete file', ['file_path' => $pathParameter, 'message' => (string) $ex]);
}
}
}
private function updateOutput(int $brokerId, BrokerInputOutput $output, string $filePath): void
{
$parameters = $output->getParameters();
$parameters['path'] = $filePath;
$output->setParameters($parameters);
$fields = $this->readOutputRepository->findParametersByType($output->getType()->id);
$this->writeOutputRepository->update($output, $brokerId, $fields);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Broker/Application/Exception/BrokerException.php | centreon/src/Core/Broker/Application/Exception/BrokerException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Broker\Application\Exception;
class BrokerException extends \Exception
{
public const CODE_CONFLICT = 1;
public const CODE_INVALID = 2;
/**
* @return self
*/
public static function addBrokerInputOutput(): self
{
return new self(_('Error while adding a Broker input/output'));
}
/**
* @return self
*/
public static function updateBrokerInputOutput(): self
{
return new self(_('Error while updating a Broker input/output'));
}
/**
* @return self
*/
public static function editNotAllowed(): self
{
return new self(_('You are not allowed to edit a broker configuration'));
}
/**
* @param int $brokerId
*
* @return self
*/
public static function notFound(int $brokerId): self
{
return new self(sprintf(_('Broker configuration #%d not found'), $brokerId));
}
/**
* @param string $propertyName
* @param int $propertyValue
*
* @return self
*/
public static function idDoesNotExist(string $propertyName, int $propertyValue): self
{
return new self(
sprintf(_("The %s with value '%d' does not exist"), $propertyName, $propertyValue),
self::CODE_CONFLICT
);
}
/**
* @param string $propertyName
*
* @return self
*/
public static function missingParameter(string $propertyName): self
{
return new self(
sprintf(_('Missing input/output parameter: %s'), $propertyName),
self::CODE_INVALID
);
}
/**
* @param string $propertyName
* @param mixed $propertyValue
*
* @return self
*/
public static function invalidParameter(string $propertyName, mixed $propertyValue): self
{
return new self(
sprintf(
_("Parameter '%s' (%s) is invalid"),
$propertyName,
is_scalar($propertyValue) ? $propertyValue : gettype($propertyValue)
),
self::CODE_INVALID
);
}
/**
* @param string $propertyName
* @param mixed $propertyValue
*
* @return self
*/
public static function invalidParameterType(string $propertyName, mixed $propertyValue): self
{
return new self(
sprintf(_("Parameter '%s' of type %s is invalid"), $propertyName, gettype($propertyValue)),
self::CODE_INVALID
);
}
/**
* @param int $brokerId
* @param int $outputId
*
* @return self
*/
public static function inputOutputNotFound(int $brokerId, int $outputId): self
{
return new self(sprintf(_('Input/Output #%d not found for Broker configuration #%d'), $outputId, $brokerId));
}
/**
* @param string $outputType
*
* @return self
*/
public static function outputTypeInvalidForThisAction(string $outputType): self
{
return new self(sprintf(_("Action not permitted for output of type '%s'"), $outputType));
}
/**
* @return self
*/
public static function invalidJsonContent(): self
{
return new self(_('Content is not a valid JSON string'));
}
/**
* @param string $filePath
*
* @return self
*/
public static function errorWhenCreatingFile(string $filePath): self
{
return new self(sprintf(_("An error occurred while creating the file '%s'"), $filePath));
}
/**
* @param string $filePath
*
* @return self
*/
public static function errorWhenDeletingFile(string $filePath): self
{
return new self(sprintf(_("An error occurred while deleting the file '%s'"), $filePath));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Broker/Application/Repository/WriteBrokerRepositoryInterface.php | centreon/src/Core/Broker/Application/Repository/WriteBrokerRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Broker\Application\Repository;
interface WriteBrokerRepositoryInterface
{
/**
* Create a file with defined content.
*
* @param string $filename
* @param string $content
*
* @throws \Throwable
*/
public function create(string $filename, string $content): void;
/**
* Delete a file.
*
* @param string $filename
*
* @throws \Throwable
*/
public function delete(string $filename): 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/Broker/Application/Repository/ReadBrokerInputOutputRepositoryInterface.php | centreon/src/Core/Broker/Application/Repository/ReadBrokerInputOutputRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Broker\Application\Repository;
use Core\Broker\Domain\Model\BrokerInputOutput;
use Core\Broker\Domain\Model\BrokerInputOutputField;
use Core\Broker\Domain\Model\Type;
interface ReadBrokerInputOutputRepositoryInterface
{
/**
* Find parameters of an input or output by type.
* Result key is the parameter fieldname, in case of grouped fields the groupname is used as a key.
*
* @param int $typeId
*
* @throws \Throwable
*
* @return array<string,BrokerInputOutputField|array<string,BrokerInputOutputField>>
*/
public function findParametersByType(int $typeId): array;
/**
* Find an input or output stream type by its ID.
*
* @param string $tag
* @param int $typeId
*
* @throws \Throwable
*
* @return ?Type
*/
public function findType(string $tag, int $typeId): ?Type;
/**
* Find a broker input or output configuration by its ID and its broker ID.
*
* @param string $tag
* @param int $outputId
* @param int $brokerId
*
* @throws \Throwable
*
* @return null|BrokerInputOutput
*/
public function findByIdAndBrokerId(string $tag, int $outputId, int $brokerId): ?BrokerInputOutput;
/**
* Return the vault path corresponding to a broker configuration ID.
*
* @param int $brokerId
*
* @throws \Throwable
*
* @return string|null
*/
public function findVaultPathByBrokerId(int $brokerId): ?string;
/**
* Return all the broker inputs and outputs ordered by broker configuration ID.
*
* @throws \Throwable
*
* @return array<int,BrokerInputOutput[]>
*/
public function findAll(): array;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Broker/Application/Repository/ReadBrokerRepositoryInterface.php | centreon/src/Core/Broker/Application/Repository/ReadBrokerRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Broker\Application\Repository;
use Core\Broker\Domain\Model\Broker;
interface ReadBrokerRepositoryInterface
{
/**
* Determine if a broker conf ID exits.
*
* @param int $id
*
* @throws \Throwable
*/
public function exists(int $id): 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/Broker/Application/Repository/WriteBrokerInputOutputRepositoryInterface.php | centreon/src/Core/Broker/Application/Repository/WriteBrokerInputOutputRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Broker\Application\Repository;
use Core\Broker\Domain\Model\BrokerInputOutput;
use Core\Broker\Domain\Model\BrokerInputOutputField;
use Core\Broker\Domain\Model\NewBrokerInputOutput;
interface WriteBrokerInputOutputRepositoryInterface
{
/**
* Add an input or output to a broker configuration.
*
* @param NewBrokerInputOutput $inputOutput
* @param int $brokerId
* @param array<string,BrokerInputOutputField|array<string,BrokerInputOutputField>> $parameters
*
* @throws \Throwable
*
* @return int
*/
public function add(NewBrokerInputOutput $inputOutput, int $brokerId, array $parameters): int;
/**
* Delete a broker input or output configuration.
*
* @param int $brokerId
* @param string $tag
* @param int $inputOutputId
*
* @throws \Throwable
*/
public function delete(int $brokerId, string $tag, int $inputOutputId): void;
/**
* Update a broker input or output configuration.
*
* @param BrokerInputOutput $inputOutput
* @param int $brokerId
* @param array<string,BrokerInputOutputField|array<string,BrokerInputOutputField>> $fields
*
* @throws \Throwable
*/
public function update(BrokerInputOutput $inputOutput, int $brokerId, array $fields): 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/Broker/Domain/Model/Type.php | centreon/src/Core/Broker/Domain/Model/Type.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Broker\Domain\Model;
/**
* Minimalist object that contains output or input type id and name.
*/
class Type
{
/**
* @param int $id
* @param string $name
*/
public function __construct(
public readonly int $id,
public readonly string $name,
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Broker/Domain/Model/BrokerInputOutputField.php | centreon/src/Core/Broker/Domain/Model/BrokerInputOutputField.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Broker\Domain\Model;
class BrokerInputOutputField
{
/**
* @param int $id
* @param string $name
* @param string $type
* @param null|int $groupId
* @param null|string $groupName
* @param bool $isRequired
* @param bool $isMultiple
* @param null|string $listDefault
* @param string[] $listValues
*/
public function __construct(
private readonly int $id,
private readonly string $name,
private readonly string $type,
private readonly ?int $groupId,
private readonly ?string $groupName,
private readonly bool $isRequired,
private readonly bool $isMultiple,
private readonly ?string $listDefault,
private readonly array $listValues,
) {
}
public function getId(): int
{
return $this->id;
}
public function getName(): string
{
return $this->name;
}
public function getType(): string
{
return $this->type;
}
public function getGroupId(): ?int
{
return $this->groupId;
}
public function getGroupName(): ?string
{
return $this->groupName;
}
public function isRequired(): bool
{
return $this->isRequired;
}
public function isMultiple(): bool
{
return $this->isMultiple;
}
public function getListDefault(): ?string
{
return $this->listDefault;
}
/**
* @return string[]
*/
public function getListValues(): array
{
return $this->listValues;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Broker/Domain/Model/NewBrokerInputOutput.php | centreon/src/Core/Broker/Domain/Model/NewBrokerInputOutput.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Broker\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
/**
* @phpstan-import-type _BrokerInputOutputParameter from BrokerInputOutput
*/
class NewBrokerInputOutput
{
/**
* @param string $tag
* @param Type $type
* @param string $name
* @param _BrokerInputOutputParameter[] $parameters
*
* @throws AssertionFailedException
*/
public function __construct(
private string $tag,
private Type $type,
private string $name,
private array $parameters,
) {
Assertion::inArray($tag, ['input', 'output'], 'NewBrokerInputOutput::tag');
$this->name = trim($name);
Assertion::notEmptyString($this->name, 'NewBrokerInputOutput::name');
Assertion::maxLength($this->name, BrokerInputOutput::NAME_MAX_LENGTH, 'NewBrokerInputOutput::name');
}
public function getTag(): string
{
return $this->tag;
}
public function getType(): Type
{
return $this->type;
}
public function getName(): string
{
return $this->name;
}
/**
* @return _BrokerInputOutputParameter[]
*/
public function getParameters(): array
{
return $this->parameters;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Broker/Domain/Model/BrokerInputOutput.php | centreon/src/Core/Broker/Domain/Model/BrokerInputOutput.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Broker\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
/**
* @phpstan-type _BrokerInputOutputParameter int|string|string[]|array<array<int|string>>
*/
class BrokerInputOutput
{
public const NAME_MAX_LENGTH = 255;
/**
* @param int $id
* @param string $tag
* @param Type $type
* @param string $name
* @param _BrokerInputOutputParameter[] $parameters
*
* @throws AssertionFailedException
*/
public function __construct(
private readonly int $id,
private readonly string $tag,
private readonly Type $type,
private string $name,
private array $parameters,
) {
Assertion::min($id, 0, 'BrokerInputOutput::id');
Assertion::inArray($tag, ['input', 'output'], 'BrokerInputOutput::tag');
$this->name = trim($name);
Assertion::notEmptyString($this->name, 'BrokerInputOutput::name');
Assertion::maxLength($this->name, self::NAME_MAX_LENGTH, 'BrokerInputOutput::name');
}
public function getId(): int
{
return $this->id;
}
public function getTag(): string
{
return $this->tag;
}
public function getType(): Type
{
return $this->type;
}
public function getName(): string
{
return $this->name;
}
/**
* @return _BrokerInputOutputParameter[]
*/
public function getParameters(): array
{
return $this->parameters;
}
/**
* @param _BrokerInputOutputParameter[] $parameters
*/
public function setParameters(array $parameters): void
{
$this->parameters = $parameters;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Broker/Infrastructure/Repository/DbReadBrokerRepository.php | centreon/src/Core/Broker/Infrastructure/Repository/DbReadBrokerRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Broker\Infrastructure\Repository;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Broker\Application\Repository\ReadBrokerRepositoryInterface;
use Core\Broker\Domain\Model\Type;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
/**
* @phpstan-type _Broker array{
* id:int,
* name:string,
* }
*/
class DbReadBrokerRepository extends AbstractRepositoryRDB implements ReadBrokerRepositoryInterface
{
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function exists(int $id): bool
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
SELECT 1 FROM `:db`.`cfg_centreonbroker`
WHERE config_id = :brokerId
SQL
));
$statement->bindValue(':brokerId', $id, \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/Broker/Infrastructure/Repository/DbWriteBrokerInputOutputRepository.php | centreon/src/Core/Broker/Infrastructure/Repository/DbWriteBrokerInputOutputRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Broker\Infrastructure\Repository;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Broker\Application\Repository\WriteBrokerInputOutputRepositoryInterface;
use Core\Broker\Domain\Model\BrokerInputOutput;
use Core\Broker\Domain\Model\BrokerInputOutputField;
use Core\Broker\Domain\Model\NewBrokerInputOutput;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
/**
* @phpstan-import-type _BrokerInputOutputParameter from \Core\Broker\Domain\Model\BrokerInputOutput
*/
class DbWriteBrokerInputOutputRepository extends AbstractRepositoryRDB implements WriteBrokerInputOutputRepositoryInterface
{
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function add(NewBrokerInputOutput $inputOutput, int $brokerId, array $fields): int
{
$inputOutputId = $this->getNextOutputId($brokerId, $inputOutput->getTag());
$this->addOutput($brokerId, $inputOutputId, $inputOutput, $fields);
return $inputOutputId;
}
/**
* @inheritDoc
*/
public function update(BrokerInputOutput $inputOutput, int $brokerId, array $fields): void
{
$this->delete($brokerId, $inputOutput->getTag(), $inputOutput->getId());
$this->addOutput($brokerId, $inputOutput->getId(), $inputOutput, $fields);
}
/**
* @inheritDoc
*/
public function delete(int $brokerId, string $tag, int $inputOutputId): void
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
DELETE FROM cfg_centreonbroker_info
WHERE config_id = :brokerId
AND config_group_id = :outputId
AND config_group = :tag
SQL
));
$statement->bindValue(':outputId', $inputOutputId, \PDO::PARAM_INT);
$statement->bindValue(':brokerId', $brokerId, \PDO::PARAM_INT);
$statement->bindValue(':tag', $tag, \PDO::PARAM_STR);
$statement->execute();
}
/**
* @param int $brokerId
* @param int $inputOutputId
* @param BrokerInputOutput|NewBrokerInputOutput $inputOutput
* @param array<string,BrokerInputOutputField|array<string,BrokerInputOutputField>> $fields
*
* @throws \Throwable
*/
private function addOutput(
int $brokerId,
int $inputOutputId,
BrokerInputOutput|NewBrokerInputOutput $inputOutput,
array $fields,
): void {
$query = <<<'SQL'
INSERT INTO `:db`.`cfg_centreonbroker_info` (
config_id,
config_key,
config_value,
config_group,
config_group_id,
grp_level,
subgrp_id,
parent_grp_id,
fieldIndex
) VALUES
SQL;
$inserts = [];
$inserts[] = <<<'SQL'
(:brokerId, 'type', :typeName, :tag, :inputOutputId, 0, null, null, null)
SQL;
$inserts[] = <<<'SQL'
(:brokerId, 'name', :name, :tag, :inputOutputId, 0, null, null, null)
SQL;
$inserts[] = <<<'SQL'
(:brokerId, 'blockId', :blockId, :tag, :inputOutputId, 0, null, null, null)
SQL;
[$paramInserts, $bindValues] = $this->getInsertQueries($fields, $inputOutput->getParameters());
$inserts = [...$inserts, ...$paramInserts];
$request = $query . ' ' . implode(',', $inserts);
$statement = $this->db->prepare($this->translateDbName($request));
$statement->bindValue(':inputOutputId', $inputOutputId, \PDO::PARAM_INT);
$statement->bindValue(':brokerId', $brokerId, \PDO::PARAM_INT);
$statement->bindValue(':typeName', $inputOutput->getType()->name, \PDO::PARAM_STR);
$statement->bindValue(':tag', $inputOutput->getTag(), \PDO::PARAM_STR);
$statement->bindValue(':name', $inputOutput->getName(), \PDO::PARAM_STR);
$blockId = ($inputOutput->getTag() === 'input' ? '2' : '1') . "_{$inputOutput->getType()->id}";
$statement->bindValue(':blockId', $blockId, \PDO::PARAM_STR);
foreach ($bindValues as $key => $value) {
if (str_starts_with($key, ':key_') || str_starts_with($key, ':value_')) {
$statement->bindValue($key, $value, \PDO::PARAM_STR);
} else {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
}
$statement->execute();
}
/**
* Build the insert elements of the add input/output query.
* Return an array containing :
* - an array of the query elements
* - an array of all the values to bind.
*
* @param array<string,BrokerInputOutputField|array<string,BrokerInputOutputField>> $fields expected fields informations for the input/output
* @param _BrokerInputOutputParameter[] $values input/output parameter values
*
* @return array{string[],array<int|string|null>}
*/
private function getInsertQueries(
array $fields,
array $values,
): array {
$inserts = [];
$bindValues = [];
$index = 0;
foreach ($fields as $fieldName => $fieldInfo) {
if (is_array($fieldInfo)) {
if (($subField = current($fieldInfo)) && $subField->getType() === 'multiselect') {
// multiselect field
$composedName = "{$fieldName}_{$subField->getName()}";
if (
! isset($values[$composedName])
|| ! is_array($values[$composedName])
|| $values[$composedName] === []
) {
// multiselect values not provided, skip field.
continue;
}
$multiselectInserts = [];
$multiselectBindValues = [];
$multiselectInserts[] = <<<SQL
(:brokerId, :key_{$index}, :value_{$index}, :tag, :inputOutputId, 0, 1, null, null)
SQL;
$multiselectBindValues[":key_{$index}"] = $fieldName;
$multiselectBindValues[":value_{$index}"] = '';
foreach ($values[$composedName] as $subIndex => $subValue) {
if (! is_string($subValue) || $subValue === '') {
// multiselect value not provied, skip value.
continue;
}
$composedIndex = "{$index}_{$subIndex}";
$multiselectInserts[] = <<<SQL
(
:brokerId,
:key_{$composedIndex},
:value_{$composedIndex},
:tag,
:inputOutputId,
1,
null,
1,
null
)
SQL;
$multiselectBindValues[":key_{$composedIndex}"] = $subField->getName();
$multiselectBindValues[":value_{$composedIndex}"] = $subValue;
}
if (count($multiselectInserts) <= 1) {
// no values for multiselect, skip multiselect field.
continue;
}
$inserts = [...$inserts, ...$multiselectInserts];
$bindValues = [...$bindValues, ...$multiselectBindValues];
} else {
// grouped fields
if (! isset($values[$fieldName]) || ! is_array($values[$fieldName]) || $values[$fieldName] === []) {
// group not provided, skip grouped fields.
continue;
}
foreach ($values[$fieldName] as $groupIndex => $groupedValues) {
if (! is_array($groupedValues)) {
// grouped values not provided, skip group.
continue;
}
$groupedInserts = [];
$groupedBindValues = [];
$empty = [];
$groupedFieldIndex = 0;
foreach ($fieldInfo as $groupedFieldName => $groupFieldInfo) {
if (
! isset($groupedValues[$groupedFieldName])
|| ! is_string($groupedValues[$groupedFieldName])
|| $groupedValues[$groupedFieldName] === ''
) {
if ($groupFieldInfo->getListDefault()) {
// value not provided, setting to default.
$groupedValues[$groupedFieldName] = $groupFieldInfo->getListDefault();
} else {
// value not provided, no default value, setting to empty string.
$empty[] = $groupedFieldName;
$groupedValues[$groupedFieldName] = '';
}
}
$composedIndex = "{$index}_{$groupIndex}_{$groupedFieldIndex}";
$groupedInserts[] = <<<SQL
(
:brokerId,
:key_{$composedIndex},
:value_{$composedIndex},
:tag,
:inputOutputId,
0,
null,
null,
:fieldIndex_{$composedIndex}
)
SQL;
$groupedBindValues[":key_{$composedIndex}"] = "{$fieldName}__{$groupedFieldName}";
$groupedBindValues[":value_{$composedIndex}"] = $groupedValues[$groupedFieldName];
$groupedBindValues[":fieldIndex_{$composedIndex}"] = $groupIndex;
++$groupedFieldIndex;
}
if (array_diff(['value', 'name'], $empty) === []) {
// both values 'name' and 'value' not provided or empty, skip group.
continue;
}
$inserts = [...$inserts, ...$groupedInserts];
$bindValues = [...$bindValues, ...$groupedBindValues];
}
}
} else {
if (! isset($values[$fieldName]) || ! is_scalar($values[$fieldName]) || $values[$fieldName] === '') {
if ($fieldInfo->getListDefault()) {
// value not provided, setting to default.
$values[$fieldName] = $fieldInfo->getListDefault();
} else {
$values[$fieldName] = '';
// value not provided, no default value, setting to empty string.
}
}
// simple field
$inserts[] = <<<SQL
(:brokerId, :key_{$index}, :value_{$index}, :tag, :inputOutputId, 0, null, null, null)
SQL;
$bindValues[":key_{$index}"] = $fieldName;
$bindValues[":value_{$index}"] = $values[$fieldName];
}
++$index;
}
return [$inserts, $bindValues];
}
private function getNextOutputId(int $brokerId, string $tag): int
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
SELECT MAX(config_group_id)
FROM `:db`.`cfg_centreonbroker_info`
WHERE config_id = :brokerId && config_group = :tag
SQL
));
$statement->bindValue(':brokerId', $brokerId, \PDO::PARAM_INT);
$statement->bindValue(':tag', $tag, \PDO::PARAM_STR);
$statement->execute();
return ((int) $statement->fetchColumn()) + 1;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Broker/Infrastructure/Repository/FileBrokerRepository.php | centreon/src/Core/Broker/Infrastructure/Repository/FileBrokerRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Broker\Infrastructure\Repository;
use Core\Broker\Application\Repository\WriteBrokerRepositoryInterface;
class FileBrokerRepository implements WriteBrokerRepositoryInterface
{
/**
* @inheritDoc
*/
public function create(string $filename, string $content): void
{
if (\file_put_contents($filename, $content) === false) {
$error = error_get_last();
$errorMessage = (isset($error) && $error['message'] !== '')
? $error['message'] : 'Error while creating file.';
throw new \Exception($errorMessage);
}
}
/**
* @inheritDoc
*/
public function delete(string $filename): void
{
if (\unlink($filename) === false) {
$error = error_get_last();
$errorMessage = (isset($error) && $error['message'] !== '')
? $error['message'] : 'Error while deleting file.';
throw new \Exception($errorMessage);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Broker/Infrastructure/Repository/DbReadBrokerInputOutputRepository.php | centreon/src/Core/Broker/Infrastructure/Repository/DbReadBrokerInputOutputRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Broker\Infrastructure\Repository;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Broker\Application\Repository\ReadBrokerInputOutputRepositoryInterface;
use Core\Broker\Domain\Model\BrokerInputOutput;
use Core\Broker\Domain\Model\BrokerInputOutputField;
use Core\Broker\Domain\Model\Type;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
/**
* @phpstan-type _InputOutput array{
* config_group_id:int,
* config_key:string,
* config_value:string,
* subgrp_id:null|int,
* parent_grp_id:null|int,
* fieldIndex:null|int
* }
* @phpstan-type _ExtendedInputOutput array{
* config_id:int,
* config_group:string,
* config_group_id:int,
* config_key:string,
* config_value:string,
* subgrp_id:null|int,
* parent_grp_id:null|int,
* fieldIndex:null|int
* }
*/
class DbReadBrokerInputOutputRepository extends AbstractRepositoryRDB implements ReadBrokerInputOutputRepositoryInterface
{
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function findParametersByType(int $typeId): array
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
SELECT
field.cb_field_id,
field.fieldname,
field.fieldtype,
field.cb_fieldgroup_id,
rel.is_required,
grp.groupname,
grp.multiple,
list.list_default,
list.list_values
FROM `:db`.`cb_field` field
INNER JOIN `:db`.`cb_type_field_relation` rel
ON rel.cb_field_id = field.cb_field_id
LEFT JOIN `:db`.`cb_fieldgroup` grp
ON grp.cb_fieldgroup_id = field.cb_fieldgroup_id
LEFT JOIN (
SELECT
list.cb_field_id,
list.default_value as list_default,
GROUP_CONCAT(list_val.value_value) as list_values
FROM `:db`.`cb_list` as list
INNER JOIN `:db`.`cb_list_values` list_val
ON list.cb_list_id = list_val.cb_list_id
GROUP BY list.cb_field_id, list.cb_list_id
) AS list
ON list.cb_field_id = field.cb_field_id
WHERE cb_type_id = :typeId
SQL
));
$statement->bindValue(':typeId', $typeId, \PDO::PARAM_INT);
$statement->execute();
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$groupedParameters = [];
$simpleParameters = [];
/**
* @var array{
* cb_field_id:int,
* fieldname:string,
* fieldtype: string,
* cb_fieldgroup_id: null|int,
* is_required: int,
* groupname: null|string,
* multiple: null|int,
* list_default: null|string,
* list_values: null|string
* } $result
*/
foreach ($statement as $result) {
$field = new BrokerInputOutputField(
id: $result['cb_field_id'],
name: $result['fieldname'],
type: $result['fieldtype'],
groupId: $result['cb_fieldgroup_id'],
groupName: $result['groupname'],
isRequired: (bool) $result['is_required'],
isMultiple: (bool) $result['multiple'],
listDefault: $result['list_default'],
listValues: $result['list_values'] ? explode(',', $result['list_values']) : [],
);
if ($result['groupname'] !== null) {
$groupedParameters[$result['groupname']][$result['fieldname']] = $field;
} else {
$simpleParameters[$result['fieldname']] = $field;
}
}
return [...$simpleParameters, ...$groupedParameters];
}
/**
* @inheritDoc
*/
public function findType(string $tag, int $typeId): ?Type
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
SELECT
type.cb_type_id as id,
type.type_shortname as name
FROM `:db`.`cb_type` `type`
INNER JOIN `:db`.`cb_tag_type_relation` rel
ON type.cb_type_id = rel.cb_type_id
INNER JOIN `:db`.`cb_tag` tag
ON tag.cb_tag_id = rel.cb_tag_id
WHERE tag.tagname = :tag AND type.cb_type_id = :typeId
SQL
));
$statement->bindValue(':typeId', $typeId, \PDO::PARAM_INT);
$statement->bindValue(':tag', $tag, \PDO::PARAM_STR);
$statement->execute();
if (! ($result = $statement->fetch(\PDO::FETCH_ASSOC))) {
return null;
}
/** @var array{id:int,name:string} $result */
return new Type($result['id'], $result['name']);
}
/**
* @inheritDoc
*/
public function findByIdAndBrokerId(string $tag, int $inputOutputId, int $brokerId): ?BrokerInputOutput
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
SELECT
cfg.config_group_id,
cfg.config_key,
cfg.config_value,
cfg.subgrp_id,
cfg.parent_grp_id,
cfg.fieldIndex
FROM `:db`.`cfg_centreonbroker_info` cfg
WHERE cfg.config_group = :tag
AND cfg.config_id = :brokerId
AND cfg.config_group_id = :inputOutputId
SQL
));
$statement->bindValue(':tag', $tag, \PDO::PARAM_STR);
$statement->bindValue(':brokerId', $brokerId, \PDO::PARAM_INT);
$statement->bindValue(':inputOutputId', $inputOutputId, \PDO::PARAM_INT);
$statement->execute();
if (! ($result = $statement->fetchAll(\PDO::FETCH_ASSOC))) {
return null;
}
/** @var _InputOutput[] $result */
return $this->createFromArray($result, $tag);
}
/**
* @inheritDoc
*/
public function findVaultPathByBrokerId(int $brokerId): ?string
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
SELECT
cfg.config_value
FROM `:db`.`cfg_centreonbroker_info` cfg
WHERE cfg.config_id = :brokerId
AND cfg.config_value LIKE 'secret::%'
LIMIT 1
SQL
));
$statement->bindValue(':brokerId', $brokerId, \PDO::PARAM_INT);
$statement->execute();
$result = $statement->fetchColumn();
/** @var string|null|false $result */
return $result !== false ? $result : null;
}
/**
* @inheritDoc
*/
public function findAll(): array
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
SELECT
cfg.config_id,
cfg.config_group,
cfg.config_group_id,
cfg.config_key,
cfg.config_value,
cfg.subgrp_id,
cfg.parent_grp_id,
cfg.fieldIndex
FROM `:db`.`cfg_centreonbroker_info` cfg
SQL
));
$statement->execute();
$data = [];
while (($row = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
/** @var _ExtendedInputOutput $row */
$data[$row['config_id'] . '_' . $row['config_group'] . '_' . $row['config_group_id']][] = $row;
}
$results = [];
foreach ($data as $values) {
$firstElem = current($values);
/** @var _ExtendedInputOutput[] $values */
$inputOutput = $this->createFromArray($values, $firstElem['config_group'], true);
if ($inputOutput !== null) {
$results[$firstElem['config_id']][] = $inputOutput;
}
}
return $results;
}
/**
* @param _InputOutput[] $result
* @param string $tag
* @param bool $withPasswords
*
* @return BrokerInputOutput|null
*/
private function createFromArray(array $result, string $tag, bool $withPasswords = false): ?BrokerInputOutput
{
$parameters = [];
$groupedFields = [];
foreach ($result as $row) {
$id ??= $row['config_group_id'];
if ($row['config_key'] === 'name') {
$outputName = $row['config_value'];
continue;
}
if ($row['config_key'] === 'blockId') {
$typeId = (int) str_replace(['1_', '2_'], '', $row['config_value']);
continue;
}
if ($row['config_key'] === 'type') {
$typeName = $row['config_value'];
continue;
}
if ($row['fieldIndex'] !== null) {
// is part of a group field
$grpNames = explode('__', $row['config_key']);
$groupedFields[$grpNames[0]] = 1;
$parameters[$grpNames[0]][$row['fieldIndex']][$grpNames[1]] = $row['config_value'];
continue;
}
if ($row['subgrp_id'] !== null) {
// is part of a multiselect
$multiselectName = $row['config_key'];
continue;
}
if ($row['parent_grp_id'] !== null) {
// is part of a multiselect
continue;
}
$parameters[$row['config_key']] = $row['config_value'];
}
// regrouping multiselect
if (isset($multiselectName)) {
foreach ($result as $row) {
if ($row['parent_grp_id'] !== null) {
$parameters["{$multiselectName}_{$row['config_key']}"][] = $row['config_value'];
}
}
}
if ($withPasswords === false) {
// removing password values
foreach (array_keys($groupedFields) as $groupedFieldName) {
$parameters[$groupedFieldName] = array_map(
$this->removePasswordValue(...),
array_values($parameters[$groupedFieldName])
);
}
}
// for phpstan, should never happen
if (! isset($id, $typeId, $typeName, $outputName)) {
return null;
}
return new BrokerInputOutput(
$id,
$tag,
new Type($typeId, $typeName),
$outputName,
$parameters
);
}
/**
* @param array{type?:string,value?:string} $groupedField
*
* @return array<string,int|string|null>
*/
private function removePasswordValue(array $groupedField): array
{
if (isset($groupedField['value'], $groupedField['type']) && $groupedField['type'] === 'password') {
$groupedField['value'] = null;
}
return $groupedField;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Broker/Infrastructure/API/AddBrokerInputOutput/AddBrokerInputOutputPresenter.php | centreon/src/Core/Broker/Infrastructure/API/AddBrokerInputOutput/AddBrokerInputOutputPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Broker\Infrastructure\API\AddBrokerInputOutput;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\CreatedResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Broker\Application\UseCase\AddBrokerInputOutput\AddBrokerInputOutputPresenterInterface;
use Core\Broker\Application\UseCase\AddBrokerInputOutput\AddBrokerInputOutputResponse;
use Core\Infrastructure\Common\Presenter\PresenterTrait;
class AddBrokerInputOutputPresenter extends AbstractPresenter implements AddBrokerInputOutputPresenterInterface
{
use PresenterTrait;
/**
* @inheritDoc
*/
public function presentResponse(AddBrokerInputOutputResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
$this->present(
new CreatedResponse(
$response->id,
[
'id' => $response->id,
'broker_id' => $response->brokerId,
'name' => $response->name,
'type' => [
'id' => $response->type->id,
'name' => $response->type->name,
],
'parameters' => (object) $response->parameters,
]
)
);
// NOT setting location as required route does not currently exist
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Broker/Infrastructure/API/AddBrokerInputOutput/AddBrokerInputOutputController.php | centreon/src/Core/Broker/Infrastructure/API/AddBrokerInputOutput/AddBrokerInputOutputController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Broker\Infrastructure\API\AddBrokerInputOutput;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Broker\Application\Exception\BrokerException;
use Core\Broker\Application\UseCase\AddBrokerInputOutput\AddBrokerInputOutput;
use Core\Broker\Application\UseCase\AddBrokerInputOutput\AddBrokerInputOutputRequest;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class AddBrokerInputOutputController extends AbstractController
{
use LoggerTrait;
/**
* @param int $brokerId
* @param string $tag
* @param Request $request
* @param AddBrokerInputOutput $useCase
* @param AddBrokerInputOutputPresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
int $brokerId,
string $tag,
Request $request,
AddBrokerInputOutput $useCase,
AddBrokerInputOutputPresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
$dto = new AddBrokerInputOutputRequest();
try {
/**
* @var array{
* name: string,
* type: int,
* parameters: array<string,mixed>
* } $data
*/
$data = $this->validateAndRetrieveDataSent($request, __DIR__ . '/AddBrokerInputOutputSchema.json');
$dto->brokerId = $brokerId;
$dto->tag = $tag === 'inputs' ? 'input' : 'output';
$dto->name = $data['name'];
$dto->type = $data['type'];
$dto->parameters = $data['parameters'];
} catch (\InvalidArgumentException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
return $presenter->show();
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(new ErrorResponse(BrokerException::addBrokerInputOutput()));
return $presenter->show();
}
$useCase($dto, $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/Broker/Infrastructure/API/UpdateStreamConnectorFile/UpdateStreamConnectorFilePresenter.php | centreon/src/Core/Broker/Infrastructure/API/UpdateStreamConnectorFile/UpdateStreamConnectorFilePresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Broker\Infrastructure\API\UpdateStreamConnectorFile;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\CreatedResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Broker\Application\UseCase\UpdateStreamConnectorFile\UpdateStreamConnectorFilePresenterInterface;
use Core\Broker\Application\UseCase\UpdateStreamConnectorFile\UpdateStreamConnectorFileResponse;
use Core\Infrastructure\Common\Presenter\PresenterTrait;
class UpdateStreamConnectorFilePresenter extends AbstractPresenter implements UpdateStreamConnectorFilePresenterInterface
{
use PresenterTrait;
/**
* @inheritDoc
*/
public function presentResponse(UpdateStreamConnectorFileResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
$this->present(
new CreatedResponse(
$response->path,
[
'path' => $response->path,
]
)
);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Broker/Infrastructure/API/UpdateStreamConnectorFile/UpdateStreamConnectorFileController.php | centreon/src/Core/Broker/Infrastructure/API/UpdateStreamConnectorFile/UpdateStreamConnectorFileController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Broker\Infrastructure\API\UpdateStreamConnectorFile;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Broker\Application\Exception\BrokerException;
use Core\Broker\Application\UseCase\UpdateStreamConnectorFile\UpdateStreamConnectorFile;
use Core\Broker\Application\UseCase\UpdateStreamConnectorFile\UpdateStreamConnectorFileRequest;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class UpdateStreamConnectorFileController extends AbstractController
{
use LoggerTrait;
/**
* @param int $brokerId
* @param int $outputId
* @param Request $request
* @param UpdateStreamConnectorFile $useCase
* @param UpdateStreamConnectorFilePresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
int $brokerId,
int $outputId,
Request $request,
UpdateStreamConnectorFile $useCase,
UpdateStreamConnectorFilePresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
try {
/**
* @var array{
* file_content: string
* } $data
*/
$data = $this->validateAndRetrieveDataSent($request, __DIR__ . '/UpdateStreamConnectorFileSchema.json');
$dto = new UpdateStreamConnectorFileRequest();
$dto->brokerId = $brokerId;
$dto->outputId = $outputId;
$dto->fileContent = $data['file_content'];
$useCase($dto, $presenter);
} catch (\InvalidArgumentException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(new ErrorResponse(BrokerException::updateBrokerInputOutput()));
}
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/ServiceTemplate/Application/Model/NotificationTypeConverter.php | centreon/src/Core/ServiceTemplate/Application/Model/NotificationTypeConverter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Application\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Core\ServiceTemplate\Domain\Model\NotificationType;
class NotificationTypeConverter
{
public const NONE_AS_BIT = 0b000000;
public const WARNING_AS_BIT = 0b000001;
public const UNKNOWN_AS_BIT = 0b000010;
public const CRITICAL_AS_BIT = 0b000100;
public const RECOVERY_AS_BIT = 0b001000;
public const FLAPPING_AS_BIT = 0b010000;
public const DOWNTIME_SCHEDULED_AS_BIT = 0b100000;
public const ALL_TYPE = 0b111111;
/**
* @param int $bitFlag
*
* @throws AssertionFailedException
*
* @return list<NotificationType>
*/
public static function fromBits(int $bitFlag): array
{
Assertion::range($bitFlag, 0, self::ALL_TYPE);
if ($bitFlag === self::NONE_AS_BIT) {
return [NotificationType::None];
}
$notificationTypes = [];
foreach (NotificationType::cases() as $notificationType) {
if ($bitFlag & self::toBit($notificationType)) {
$notificationTypes[] = $notificationType;
}
}
return $notificationTypes;
}
/**
* @param NotificationType $notificationType
*
* @return int
*/
private static function toBit(NotificationType $notificationType): int
{
return match ($notificationType) {
NotificationType::Warning => self::WARNING_AS_BIT,
NotificationType::Unknown => self::UNKNOWN_AS_BIT,
NotificationType::Critical => self::CRITICAL_AS_BIT,
NotificationType::Recovery => self::RECOVERY_AS_BIT,
NotificationType::Flapping => self::FLAPPING_AS_BIT,
NotificationType::DowntimeScheduled => self::DOWNTIME_SCHEDULED_AS_BIT,
NotificationType::None => self::NONE_AS_BIT,
};
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Application/Model/YesNoDefaultConverter.php | centreon/src/Core/ServiceTemplate/Application/Model/YesNoDefaultConverter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Application\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Common\Domain\YesNoDefault;
class YesNoDefaultConverter
{
/**
* @param int $yesNoDefault
*
* @throws \Assert\AssertionFailedException
*
* @return YesNoDefault
*/
public static function fromInt(int $yesNoDefault): YesNoDefault
{
return match ($yesNoDefault) {
0 => YesNoDefault::No,
1 => YesNoDefault::Yes,
2 => YesNoDefault::Default,
default => throw AssertionException::range($yesNoDefault, 0, 2),
};
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Application/UseCase/PartialUpdateServiceTemplate/ServiceGroupDto.php | centreon/src/Core/ServiceTemplate/Application/UseCase/PartialUpdateServiceTemplate/ServiceGroupDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Application\UseCase\PartialUpdateServiceTemplate;
class ServiceGroupDto
{
public function __construct(
public int $hostTemplateId,
public int $serviceGroupId,
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Application/UseCase/PartialUpdateServiceTemplate/MacroDto.php | centreon/src/Core/ServiceTemplate/Application/UseCase/PartialUpdateServiceTemplate/MacroDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Application\UseCase\PartialUpdateServiceTemplate;
class MacroDto
{
public function __construct(
public string $name,
public ?string $value,
public bool $isPassword,
public ?string $description,
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Application/UseCase/PartialUpdateServiceTemplate/MacroFactory.php | centreon/src/Core/ServiceTemplate/Application/UseCase/PartialUpdateServiceTemplate/MacroFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Application\UseCase\PartialUpdateServiceTemplate;
use Assert\AssertionFailedException;
use Core\Macro\Domain\Model\Macro;
final class MacroFactory
{
/**
* Create macros object from the request data.
* Use direct and inherited macros to retrieve value of macro with isPassword when not provided in dto.
*
* @param MacroDto $dto
* @param int $serviceTemplateId
* @param array<string,Macro> $directMacros
* @param array<string,Macro> $inheritedMacros
*
* @throws AssertionFailedException
*
* @return Macro
*/
public static function create(
MacroDto $dto,
int $serviceTemplateId,
array $directMacros,
array $inheritedMacros,
): Macro {
$macroName = mb_strtoupper($dto->name);
$macroValue = $dto->value ?? '';
$passwordHasNotChanged = ($dto->value === null) && $dto->isPassword;
// Note: do not handle vault storage at the moment
if ($passwordHasNotChanged) {
$macroValue = match (true) {
// retrieve actual password value
isset($directMacros[$macroName]) => $directMacros[$macroName]->getValue(),
isset($inheritedMacros[$macroName]) => $inheritedMacros[$macroName]->getValue(),
default => $macroValue,
};
}
$macro = new Macro(
null,
$serviceTemplateId,
$dto->name,
$macroValue,
);
$macro->setIsPassword($dto->isPassword);
$macro->setDescription($dto->description ?? '');
return $macro;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Application/UseCase/PartialUpdateServiceTemplate/PartialUpdateServiceTemplate.php | centreon/src/Core/ServiceTemplate/Application/UseCase/PartialUpdateServiceTemplate/PartialUpdateServiceTemplate.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Application\UseCase\PartialUpdateServiceTemplate;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Option\OptionService;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Core\Application\Common\UseCase\ConflictResponse;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Application\Common\UseCase\PresenterInterface;
use Core\CommandMacro\Application\Repository\ReadCommandMacroRepositoryInterface;
use Core\CommandMacro\Domain\Model\CommandMacro;
use Core\CommandMacro\Domain\Model\CommandMacroType;
use Core\Common\Application\Repository\ReadVaultRepositoryInterface;
use Core\Common\Application\Repository\WriteVaultRepositoryInterface;
use Core\Common\Application\Type\NoValue;
use Core\Common\Application\UseCase\VaultTrait;
use Core\Common\Infrastructure\Repository\AbstractVaultRepository;
use Core\HostTemplate\Application\Exception\HostTemplateException;
use Core\Macro\Application\Repository\ReadServiceMacroRepositoryInterface;
use Core\Macro\Application\Repository\WriteServiceMacroRepositoryInterface;
use Core\Macro\Domain\Model\Macro;
use Core\Macro\Domain\Model\MacroDifference;
use Core\Macro\Domain\Model\MacroManager;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Core\ServiceCategory\Application\Repository\ReadServiceCategoryRepositoryInterface;
use Core\ServiceCategory\Application\Repository\WriteServiceCategoryRepositoryInterface;
use Core\ServiceCategory\Domain\Model\ServiceCategory;
use Core\ServiceGroup\Application\Repository\ReadServiceGroupRepositoryInterface;
use Core\ServiceGroup\Application\Repository\WriteServiceGroupRepositoryInterface;
use Core\ServiceGroup\Domain\Model\ServiceGroupRelation;
use Core\ServiceTemplate\Application\Exception\ServiceTemplateException;
use Core\ServiceTemplate\Application\Model\NotificationTypeConverter;
use Core\ServiceTemplate\Application\Model\YesNoDefaultConverter;
use Core\ServiceTemplate\Application\Repository\ReadServiceTemplateRepositoryInterface;
use Core\ServiceTemplate\Application\Repository\WriteServiceTemplateRepositoryInterface;
use Core\ServiceTemplate\Domain\Model\ServiceTemplate;
use Core\ServiceTemplate\Domain\Model\ServiceTemplateInheritance;
use Utility\Difference\BasicDifference;
final class PartialUpdateServiceTemplate
{
use LoggerTrait;
use VaultTrait;
/** @var AccessGroup[] */
private array $accessGroups = [];
public function __construct(
private readonly WriteServiceTemplateRepositoryInterface $writeRepository,
private readonly ReadServiceCategoryRepositoryInterface $readServiceCategoryRepository,
private readonly WriteServiceCategoryRepositoryInterface $writeServiceCategoryRepository,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly ReadServiceTemplateRepositoryInterface $readServiceTemplateRepository,
private readonly ReadServiceMacroRepositoryInterface $readServiceMacroRepository,
private readonly WriteServiceMacroRepositoryInterface $writeServiceMacroRepository,
private readonly ReadCommandMacroRepositoryInterface $readCommandMacroRepository,
private readonly WriteServiceGroupRepositoryInterface $writeServiceGroupRepository,
private readonly ReadServiceGroupRepositoryInterface $readServiceGroupRepository,
private readonly ParametersValidation $validation,
private readonly ContactInterface $user,
private readonly DataStorageEngineInterface $storageEngine,
private readonly OptionService $optionService,
private readonly WriteVaultRepositoryInterface $writeVaultRepository,
private readonly ReadVaultRepositoryInterface $readVaultRepository,
) {
$this->writeVaultRepository->setCustomPath(AbstractVaultRepository::SERVICE_VAULT_PATH);
}
public function __invoke(
PartialUpdateServiceTemplateRequest $request,
PresenterInterface $presenter,
): void {
try {
$this->info('Update the service template', ['request' => $request]);
if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE)) {
$this->error(
"User doesn't have sufficient rights to update a service template",
['user_id' => $this->user->getId()]
);
$presenter->setResponseStatus(
new ForbiddenResponse(ServiceTemplateException::updateNotAllowed())
);
return;
}
if (! $this->user->isAdmin()) {
$this->accessGroups = $this->readAccessGroupRepository->findByContact($this->user);
$serviceTemplate = $this->readServiceTemplateRepository->findByIdAndAccessGroups(
$request->id,
$this->accessGroups
);
} else {
$serviceTemplate = $this->readServiceTemplateRepository->findById($request->id);
}
if ($serviceTemplate === null) {
$this->error('Service template not found', ['service_template_id' => $request->id]);
$presenter->setResponseStatus(new NotFoundResponse('Service template'));
return;
}
$this->updatePropertiesInTransaction($request, $serviceTemplate);
$presenter->setResponseStatus(new NoContentResponse());
} catch (ServiceTemplateException $ex) {
$presenter->setResponseStatus(
match ($ex->getCode()) {
ServiceTemplateException::CODE_CONFLICT => new ConflictResponse($ex),
default => new ErrorResponse($ex),
}
);
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (\Throwable $ex) {
$presenter->setResponseStatus(new ErrorResponse(ServiceTemplateException::errorWhileUpdating()));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
}
}
/**
* @param PartialUpdateServiceTemplateRequest $request
*
* @throws \Throwable
*/
private function linkServiceTemplateToHostTemplates(PartialUpdateServiceTemplateRequest $request): void
{
if (! is_array($request->hostTemplates)) {
return;
}
$this->validation->assertHostTemplateIds($request->hostTemplates);
$this->info('Unlink existing host templates from service template', [
'service_template_id' => $request->id,
'host_templates' => $request->hostTemplates,
]);
$this->writeRepository->unlinkHosts($request->id);
$this->info('Link host templates to service template', [
'service_template_id' => $request->id,
'host_templates' => $request->hostTemplates,
]);
$this->writeRepository->linkToHosts($request->id, $request->hostTemplates);
}
/**
* @param PartialUpdateServiceTemplateRequest $request
*
* @throws \Throwable
*/
private function linkServiceTemplateToServiceCategories(PartialUpdateServiceTemplateRequest $request): void
{
if (! is_array($request->serviceCategories)) {
return;
}
$this->validation->assertServiceCategories($request->serviceCategories, $this->user, $this->accessGroups);
if ($this->user->isAdmin()) {
$originalServiceCategories = $this->readServiceCategoryRepository->findByService($request->id);
} else {
$originalServiceCategories = $this->readServiceCategoryRepository->findByServiceAndAccessGroups(
$request->id,
$this->accessGroups
);
}
$this->info('Original service categories found', ['service_categories' => $originalServiceCategories]);
$originalServiceCategoriesIds = array_map(
static fn (ServiceCategory $serviceCategory): int => $serviceCategory->getId(),
$originalServiceCategories
);
$serviceCategoryDifferences = new BasicDifference(
$originalServiceCategoriesIds,
array_unique($request->serviceCategories)
);
$serviceCategoriesToAdd = $serviceCategoryDifferences->getAdded();
$serviceCategoriesToRemove = $serviceCategoryDifferences->getRemoved();
$this->info(
'Unlink existing service categories from service',
['service_categories' => $serviceCategoriesToRemove]
);
$this->writeServiceCategoryRepository->unlinkFromService($request->id, $serviceCategoriesToRemove);
$this->info(
'Link existing service categories to service',
['service_categories' => $serviceCategoriesToAdd]
);
$this->writeServiceCategoryRepository->linkToService($request->id, $serviceCategoriesToAdd);
}
/**
* @param PartialUpdateServiceTemplateRequest $request
*
* @throws \Throwable
*/
private function linkServiceTemplateToServiceGroups(PartialUpdateServiceTemplateRequest $request): void
{
if (! is_array($request->serviceGroups)) {
return;
}
$this->info(
'Link existing service groups to service template',
['service_template_id' => $request->id, 'service_groups' => $request->serviceGroups]
);
$this->validation->assertServiceGroups($request->serviceGroups, $request->id, $this->user, $this->accessGroups);
$serviceGroupRelations = [];
$serviceGroupDtos = $this->removeDuplicatesServiceGroups($request->serviceGroups);
foreach ($serviceGroupDtos as $serviceGroup) {
$serviceGroupRelations[] = new ServiceGroupRelation(
serviceGroupId: $serviceGroup->serviceGroupId,
serviceId: $request->id,
hostId: $serviceGroup->hostTemplateId
);
}
if ($this->user->isAdmin()) {
$originalGroups = $this->readServiceGroupRepository->findByService($request->id);
} else {
$originalGroups = $this->readServiceGroupRepository->findByServiceAndAccessGroups(
$request->id,
$this->accessGroups
);
}
$this->info('Delete existing service groups relations');
$this->writeServiceGroupRepository->unlink(array_column($originalGroups, 'relation'));
$this->info('Create new service groups relations');
$this->writeServiceGroupRepository->link($serviceGroupRelations);
}
/**
* @param PartialUpdateServiceTemplateRequest $request
* @param ServiceTemplate $serviceTemplate
*
* @throws ServiceTemplateException
* @throws \Throwable
*/
private function updatePropertiesInTransaction(
PartialUpdateServiceTemplateRequest $request,
ServiceTemplate $serviceTemplate,
): void {
$this->debug('Start transaction');
$this->storageEngine->startTransaction();
try {
if ($this->writeVaultRepository->isVaultConfigured()) {
$this->retrieveServiceUuidFromVault($serviceTemplate->getId());
}
$this->updateServiceTemplate($serviceTemplate, $request);
$this->linkServiceTemplateToHostTemplates($request);
$this->linkServiceTemplateToServiceCategories($request);
$this->linkServiceTemplateToServiceGroups($request);
$this->updateMacros($request, $serviceTemplate);
$this->debug('Commit transaction');
$this->storageEngine->commitTransaction();
} catch (\Throwable $ex) {
$this->debug('Rollback transaction');
$this->storageEngine->rollbackTransaction();
throw $ex;
}
}
/**
* @param PartialUpdateServiceTemplateRequest $request
* @param ServiceTemplate $serviceTemplate
*
* @throws AssertionFailedException
* @throws \Throwable
*/
private function updateMacros(PartialUpdateServiceTemplateRequest $request, ServiceTemplate $serviceTemplate): void
{
if (! is_array($request->macros)) {
return;
}
$this->info('Add macros', ['service_template_id' => $request->id]);
/**
* @var array<string,Macro> $inheritedMacros
* @var array<string,CommandMacro> $commandMacros
*/
[$directMacros, $inheritedMacros, $commandMacros] = $this->findAllMacros(
$request->id,
$serviceTemplate->getCommandId()
);
$macros = [];
foreach ($request->macros as $macro) {
$macro = MacroFactory::create($macro, $request->id, $directMacros, $inheritedMacros);
$macros[$macro->getName()] = $macro;
}
$macrosDiff = new MacroDifference();
$macrosDiff->compute($directMacros, $inheritedMacros, $commandMacros, $macros);
MacroManager::setOrder($macrosDiff, $macros, []);
foreach ($macrosDiff->removedMacros as $macro) {
$this->info('Delete the macro ' . $macro->getName());
$this->updateMacroInVault($macro, 'DELETE');
$this->writeServiceMacroRepository->delete($macro);
}
foreach ($macrosDiff->updatedMacros as $macro) {
$this->info('Update the macro ' . $macro->getName());
$macro = $this->updateMacroInVault($macro, 'INSERT');
$this->writeServiceMacroRepository->update($macro);
}
foreach ($macrosDiff->addedMacros as $macro) {
if ($macro->getDescription() === '') {
$macro->setDescription(
isset($commandMacros[$macro->getName()])
? $commandMacros[$macro->getName()]->getDescription()
: ''
);
}
$this->info('Add the macro ' . $macro->getName());
$macro = $this->updateMacroInVault($macro, 'INSERT');
$this->writeServiceMacroRepository->add($macro);
}
}
/**
* @param int $serviceTemplateId
* @param int|null $checkCommandId
*
* @throws \Throwable
*
* @return array{
* array<string,Macro>,
* array<string,Macro>,
* array<string,CommandMacro>
* }
*/
private function findAllMacros(int $serviceTemplateId, ?int $checkCommandId): array
{
$serviceTemplateInheritances = $this->readServiceTemplateRepository->findParents($serviceTemplateId);
$inheritanceLine = ServiceTemplateInheritance::createInheritanceLine(
$serviceTemplateId,
$serviceTemplateInheritances
);
$existingMacros = $this->readServiceMacroRepository->findByServiceIds($serviceTemplateId, ...$inheritanceLine);
[$directMacros, $inheritedMacros] = Macro::resolveInheritance(
$existingMacros,
$inheritanceLine,
$serviceTemplateId
);
/** @var array<string,CommandMacro> $commandMacros */
$commandMacros = [];
if ($checkCommandId !== null) {
$existingCommandMacros = $this->readCommandMacroRepository->findByCommandIdAndType(
$checkCommandId,
CommandMacroType::Service
);
$commandMacros = MacroManager::resolveInheritanceForCommandMacro($existingCommandMacros);
}
return [
$this->writeVaultRepository->isVaultConfigured()
? $this->retrieveMacrosVaultValues($directMacros)
: $directMacros,
$this->writeVaultRepository->isVaultConfigured()
? $this->retrieveMacrosVaultValues($inheritedMacros)
: $inheritedMacros,
$commandMacros,
];
}
/**
* @param ServiceTemplate $serviceTemplate
* @param PartialUpdateServiceTemplateRequest $request
*
* @throws \Throwable
* @throws HostTemplateException
*/
private function updateServiceTemplate(
ServiceTemplate $serviceTemplate,
PartialUpdateServiceTemplateRequest $request,
): void {
$inheritanceMode = $this->optionService->findSelectedOptions(['inheritance_mode']);
$inheritanceMode = isset($inheritanceMode[0])
? (int) $inheritanceMode[0]->getValue()
: 0;
if (! $request->name instanceof NoValue) {
$this->validation->assertIsValidName($serviceTemplate->getName(), $request->name);
$serviceTemplate->setName($request->name);
}
if (! $request->alias instanceof NoValue) {
$serviceTemplate->setAlias($request->alias);
}
if (! $request->commandArguments instanceof NoValue) {
$serviceTemplate->setCommandArguments($request->commandArguments);
}
if (! $request->eventHandlerArguments instanceof NoValue) {
$serviceTemplate->setEventHandlerArguments($request->eventHandlerArguments);
}
if (! $request->notificationTypes instanceof NoValue) {
$serviceTemplate->resetNotificationTypes();
foreach (NotificationTypeConverter::fromBits($request->notificationTypes) as $notificationType) {
$serviceTemplate->addNotificationType($notificationType);
}
}
if (! $request->isContactAdditiveInheritance instanceof NoValue) {
$serviceTemplate->setContactAdditiveInheritance(($inheritanceMode === 1) ? $request->isContactAdditiveInheritance : false);
}
if (! $request->isContactGroupAdditiveInheritance instanceof NoValue) {
$serviceTemplate->setContactGroupAdditiveInheritance(($inheritanceMode === 1) ? $request->isContactGroupAdditiveInheritance : false);
}
if (! $request->activeChecksEnabled instanceof NoValue) {
$serviceTemplate->setActiveChecks(YesNoDefaultConverter::fromInt($request->activeChecksEnabled));
}
if (! $request->passiveCheckEnabled instanceof NoValue) {
$serviceTemplate->setPassiveCheck(YesNoDefaultConverter::fromInt($request->passiveCheckEnabled));
}
if (! $request->volatility instanceof NoValue) {
$serviceTemplate->setVolatility(YesNoDefaultConverter::fromInt($request->volatility));
}
if (! $request->checkFreshness instanceof NoValue) {
$serviceTemplate->setCheckFreshness(YesNoDefaultConverter::fromInt($request->checkFreshness));
}
if (! $request->eventHandlerEnabled instanceof NoValue) {
$serviceTemplate->setEventHandlerEnabled(YesNoDefaultConverter::fromInt($request->eventHandlerEnabled));
}
if (! $request->flapDetectionEnabled instanceof NoValue) {
$serviceTemplate->setFlapDetectionEnabled(YesNoDefaultConverter::fromInt($request->flapDetectionEnabled));
}
if (! $request->notificationsEnabled instanceof NoValue) {
$serviceTemplate->setNotificationsEnabled(YesNoDefaultConverter::fromInt($request->notificationsEnabled));
}
if (! $request->comment instanceof NoValue) {
$serviceTemplate->setComment($request->comment);
}
if (! $request->note instanceof NoValue) {
$serviceTemplate->setNote($request->note);
}
if (! $request->noteUrl instanceof NoValue) {
$serviceTemplate->setNoteUrl($request->noteUrl);
}
if (! $request->actionUrl instanceof NoValue) {
$serviceTemplate->setActionUrl($request->actionUrl);
}
if (! $request->iconAlternativeText instanceof NoValue) {
$serviceTemplate->setIconAlternativeText($request->iconAlternativeText);
}
if (! $request->graphTemplateId instanceof NoValue) {
$this->validation->assertIsValidPerformanceGraph($request->graphTemplateId);
$serviceTemplate->setGraphTemplateId($request->graphTemplateId);
}
if (! $request->serviceTemplateParentId instanceof NoValue) {
$this->validation->assertIsValidServiceTemplate(
$serviceTemplate->getId(),
$request->serviceTemplateParentId
);
$serviceTemplate->setServiceTemplateParentId($request->serviceTemplateParentId);
}
if (! $request->commandId instanceof NoValue) {
$this->validation->assertIsValidCommand($request->commandId);
$serviceTemplate->setCommandId($request->commandId);
}
if (! $request->eventHandlerId instanceof NoValue) {
$this->validation->assertIsValidEventHandler($request->eventHandlerId);
$serviceTemplate->setEventHandlerId($request->eventHandlerId);
}
if (! $request->notificationTimePeriodId instanceof NoValue) {
$this->validation->assertIsValidNotificationTimePeriod($request->notificationTimePeriodId);
$serviceTemplate->setNotificationTimePeriodId($request->notificationTimePeriodId);
}
if (! $request->checkTimePeriodId instanceof NoValue) {
$this->validation->assertIsValidTimePeriod($request->checkTimePeriodId);
$serviceTemplate->setCheckTimePeriodId($request->checkTimePeriodId);
}
if (! $request->iconId instanceof NoValue) {
$this->validation->assertIsValidIcon($request->iconId);
$serviceTemplate->setIconId($request->iconId);
}
if (! $request->severityId instanceof NoValue) {
$this->validation->assertIsValidSeverity($request->severityId);
$serviceTemplate->setSeverityId($request->severityId);
}
if (! $request->maxCheckAttempts instanceof NoValue) {
$serviceTemplate->setMaxCheckAttempts($request->maxCheckAttempts);
}
if (! $request->normalCheckInterval instanceof NoValue) {
$serviceTemplate->setNormalCheckInterval($request->normalCheckInterval);
}
if (! $request->retryCheckInterval instanceof NoValue) {
$serviceTemplate->setRetryCheckInterval($request->retryCheckInterval);
}
if (! $request->freshnessThreshold instanceof NoValue) {
$serviceTemplate->setFreshnessThreshold($request->freshnessThreshold);
}
if (! $request->lowFlapThreshold instanceof NoValue) {
$serviceTemplate->setLowFlapThreshold($request->lowFlapThreshold);
}
if (! $request->highFlapThreshold instanceof NoValue) {
$serviceTemplate->setHighFlapThreshold($request->highFlapThreshold);
}
if (! $request->notificationInterval instanceof NoValue) {
$serviceTemplate->setNotificationInterval($request->notificationInterval);
}
if (! $request->recoveryNotificationDelay instanceof NoValue) {
$serviceTemplate->setRecoveryNotificationDelay($request->recoveryNotificationDelay);
}
if (! $request->firstNotificationDelay instanceof NoValue) {
$serviceTemplate->setFirstNotificationDelay($request->firstNotificationDelay);
}
if (! $request->acknowledgementTimeout instanceof NoValue) {
$serviceTemplate->setAcknowledgementTimeout($request->acknowledgementTimeout);
}
$this->writeRepository->update($serviceTemplate);
}
/**
* @param ServiceGroupDto[] $serviceGroupDtos
*
* @return ServiceGroupDto[]
*/
private function removeDuplicatesServiceGroups(array $serviceGroupDtos): array
{
$uniqueList = [];
foreach ($serviceGroupDtos as $item) {
$uniqueList[$item->serviceGroupId . '_' . $item->hostTemplateId] = $item;
}
return array_values($uniqueList);
}
/**
* @param int $serviceTemplateId
*
* @throws \Throwable
*/
private function retrieveServiceUuidFromVault(int $serviceTemplateId): void
{
$macros = $this->readServiceMacroRepository->findByServiceIds($serviceTemplateId);
foreach ($macros as $macro) {
if (
$macro->isPassword() === true
&& null !== ($this->uuid = $this->getUuidFromPath($macro->getValue()))
) {
break;
}
}
}
/**
* Upsert or delete macro for vault storage and return macro with updated value (aka vaultPath).
*
* @param Macro $macro
* @param string $action
*
* @throws \Throwable
*
* @return Macro
*/
private function updateMacroInVault(Macro $macro, string $action): Macro
{
if ($this->writeVaultRepository->isVaultConfigured() && $macro->isPassword() === true) {
$macroPrefixName = '_SERVICE' . $macro->getName();
$vaultPaths = $this->writeVaultRepository->upsert(
$this->uuid ?? null,
$action === 'INSERT' ? [$macroPrefixName => $macro->getValue()] : [],
$action === 'DELETE' ? [$macroPrefixName => $macro->getValue()] : [],
);
$vaultPath = $vaultPaths[$macroPrefixName];
$this->uuid ??= $this->getUuidFromPath($vaultPath);
$inVaultMacro = new Macro($macro->getId(), $macro->getOwnerId(), $macro->getName(), $vaultPath);
$inVaultMacro->setDescription($macro->getDescription());
$inVaultMacro->setIsPassword($macro->isPassword());
$inVaultMacro->setOrder($macro->getOrder());
return $inVaultMacro;
}
return $macro;
}
/**
* @param array<string,Macro> $macros
*
* @throws \Throwable
*
* @return array<string,Macro>
*/
private function retrieveMacrosVaultValues(array $macros): array
{
$updatedMacros = [];
foreach ($macros as $key => $macro) {
if ($macro->isPassword() === false) {
$updatedMacros[$key] = $macro;
continue;
}
$vaultData = $this->readVaultRepository->findFromPath($macro->getValue());
$vaultKey = '_SERVICE' . $macro->getName();
if (isset($vaultData[$vaultKey])) {
$inVaultMacro = new Macro($macro->getId(), $macro->getOwnerId(), $macro->getName(), $vaultData[$vaultKey]);
$inVaultMacro->setDescription($macro->getDescription());
$inVaultMacro->setIsPassword($macro->isPassword());
$inVaultMacro->setOrder($macro->getOrder());
$updatedMacros[$key] = $inVaultMacro;
}
}
return $updatedMacros;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Application/UseCase/PartialUpdateServiceTemplate/ParametersValidation.php | centreon/src/Core/ServiceTemplate/Application/UseCase/PartialUpdateServiceTemplate/ParametersValidation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Application\UseCase\PartialUpdateServiceTemplate;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Command\Application\Repository\ReadCommandRepositoryInterface;
use Core\Command\Domain\Model\CommandType;
use Core\Common\Domain\TrimmedString;
use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface;
use Core\PerformanceGraph\Application\Repository\ReadPerformanceGraphRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Core\ServiceCategory\Application\Repository\ReadServiceCategoryRepositoryInterface;
use Core\ServiceGroup\Application\Repository\ReadServiceGroupRepositoryInterface;
use Core\ServiceSeverity\Application\Repository\ReadServiceSeverityRepositoryInterface;
use Core\ServiceTemplate\Application\Exception\ServiceTemplateException;
use Core\ServiceTemplate\Application\Repository\ReadServiceTemplateRepositoryInterface;
use Core\ServiceTemplate\Domain\Model\ServiceTemplate;
use Core\ServiceTemplate\Domain\Model\ServiceTemplateInheritance;
use Core\TimePeriod\Application\Repository\ReadTimePeriodRepositoryInterface;
use Core\ViewImg\Application\Repository\ReadViewImgRepositoryInterface;
class ParametersValidation
{
use LoggerTrait;
public function __construct(
private readonly ReadServiceTemplateRepositoryInterface $readServiceTemplateRepository,
private readonly ReadCommandRepositoryInterface $commandRepository,
private readonly ReadTimePeriodRepositoryInterface $timePeriodRepository,
private readonly ReadServiceSeverityRepositoryInterface $serviceSeverityRepository,
private readonly ReadPerformanceGraphRepositoryInterface $performanceGraphRepository,
private readonly ReadViewImgRepositoryInterface $imageRepository,
private readonly ReadHostTemplateRepositoryInterface $readHostTemplateRepository,
private readonly ReadServiceCategoryRepositoryInterface $readServiceCategoryRepository,
private readonly ReadServiceGroupRepositoryInterface $readServiceGroupRepository,
) {
}
/**
* Assert name is not already used.
*
* @param string $currentName
* @param string $newName
*
* @throws ServiceTemplateException
* @throws \Throwable
*/
public function assertIsValidName(string $currentName, string $newName): void
{
$formattedName = ServiceTemplate::formatName($newName) ?? '';
if (
$formattedName !== ''
&& $currentName !== $formattedName
&& $this->readServiceTemplateRepository->existsByName(
new TrimmedString($formattedName)
)
) {
$this->error('Service template name already exists', ['name' => $newName]);
throw ServiceTemplateException::nameAlreadyExists($formattedName);
}
}
/**
* @param int $id
* @param int|null $serviceTemplateId
*
* @throws ServiceTemplateException
* @throws \Throwable
*/
public function assertIsValidServiceTemplate(int $id, ?int $serviceTemplateId): void
{
if ($serviceTemplateId === null) {
return;
}
if ($id === $serviceTemplateId) {
$this->error('Service template cannot inherit from itself', ['service_template_id' => $serviceTemplateId]);
throw ServiceTemplateException::circularTemplateInheritance();
}
if (! $this->readServiceTemplateRepository->exists($serviceTemplateId)) {
$this->error('Service template does not exist', ['service_template_id' => $serviceTemplateId]);
throw ServiceTemplateException::idDoesNotExist('service_template_id', $serviceTemplateId);
}
// check circular inheritance
$inheritanceArray = $this->readServiceTemplateRepository->findParents($serviceTemplateId);
$parentsIds = array_map(
static fn (ServiceTemplateInheritance $inheritancePair): int => $inheritancePair->getParentId(),
$inheritanceArray
);
if (in_array($id, $parentsIds, true)) {
$this->error(
'Service template cannot inherit from a template that inherits from it',
['service_template_id' => $serviceTemplateId]
);
throw ServiceTemplateException::circularTemplateInheritance();
}
}
/**
* @param int|null $commandId
*
* @throws ServiceTemplateException
*/
public function assertIsValidCommand(?int $commandId): void
{
if (
$commandId !== null
&& ! $this->commandRepository->existsByIdAndCommandType($commandId, CommandType::Check)
) {
$this->error('Check command does not exist', ['check_command_id' => $commandId]);
throw ServiceTemplateException::idDoesNotExist('check_command_id', $commandId);
}
}
/**
* @param int|null $eventHandlerId
*
* @throws ServiceTemplateException
*/
public function assertIsValidEventHandler(?int $eventHandlerId): void
{
if ($eventHandlerId !== null && ! $this->commandRepository->exists($eventHandlerId)) {
$this->error('Event handler command does not exist', ['event_handler_command_id' => $eventHandlerId]);
throw ServiceTemplateException::idDoesNotExist('event_handler_command_id', $eventHandlerId);
}
}
/**
* @param int|null $timePeriodId
*
* @throws ServiceTemplateException
* @throws \Throwable
*/
public function assertIsValidTimePeriod(?int $timePeriodId): void
{
if ($timePeriodId !== null && ! $this->timePeriodRepository->exists($timePeriodId)) {
$this->error('Time period does not exist', ['check_timeperiod_id' => $timePeriodId]);
throw ServiceTemplateException::idDoesNotExist('check_timeperiod_id', $timePeriodId);
}
}
/**
* @param int|null $severityId
*
* @throws ServiceTemplateException
* @throws \Throwable
*/
public function assertIsValidSeverity(?int $severityId): void
{
if ($severityId !== null && ! $this->serviceSeverityRepository->exists($severityId)) {
$this->error('Service severity does not exist', ['severity_id' => $severityId]);
throw ServiceTemplateException::idDoesNotExist('severity_id', $severityId);
}
}
/**
* @param int|null $graphTemplateId
*
* @throws ServiceTemplateException
* @throws \Throwable
*/
public function assertIsValidPerformanceGraph(?int $graphTemplateId): void
{
if ($graphTemplateId !== null && ! $this->performanceGraphRepository->exists($graphTemplateId)) {
$this->error('Performance graph does not exist', ['graph_template_id' => $graphTemplateId]);
throw ServiceTemplateException::idDoesNotExist('graph_template_id', $graphTemplateId);
}
}
/**
* @param int|null $notificationTimePeriodId
*
* @throws ServiceTemplateException
* @throws \Throwable
*/
public function assertIsValidNotificationTimePeriod(?int $notificationTimePeriodId): void
{
if ($notificationTimePeriodId !== null && ! $this->timePeriodRepository->exists($notificationTimePeriodId)) {
$this->error(
'Notification time period does not exist',
['notification_timeperiod_id' => $notificationTimePeriodId]
);
throw ServiceTemplateException::idDoesNotExist('notification_timeperiod_id', $notificationTimePeriodId);
}
}
/**
* @param int|null $iconId
*
* @throws ServiceTemplateException
* @throws \Throwable
*/
public function assertIsValidIcon(?int $iconId): void
{
if ($iconId !== null && ! $this->imageRepository->existsOne($iconId)) {
$this->error('Icon does not exist', ['icon_id' => $iconId]);
throw ServiceTemplateException::idDoesNotExist('icon_id', $iconId);
}
}
/**
* Check if all host template ids exist.
*
* @param list<int> $hostTemplatesIds
*
* @throws ServiceTemplateException
*/
public function assertHostTemplateIds(array $hostTemplatesIds): void
{
$hostTemplateIds = array_unique($hostTemplatesIds);
$hostTemplateIdsFound = $this->readHostTemplateRepository->findAllExistingIds($hostTemplateIds);
if ([] !== ($idsNotFound = array_diff($hostTemplateIds, $hostTemplateIdsFound))) {
throw ServiceTemplateException::idsDoNotExist('host_templates', $idsNotFound);
}
}
/**
* @param list<int> $serviceCategoriesIds
* @param ContactInterface $contact
* @param AccessGroup[] $accessGroups
*
* @throws ServiceTemplateException
* @throws \Throwable
*/
public function assertServiceCategories(
array $serviceCategoriesIds,
ContactInterface $contact,
array $accessGroups,
): void {
if ($contact->isAdmin()) {
$serviceCategoriesIdsFound = $this->readServiceCategoryRepository->findAllExistingIds(
$serviceCategoriesIds
);
} else {
$serviceCategoriesIdsFound = $this->readServiceCategoryRepository->findAllExistingIdsByAccessGroups(
$serviceCategoriesIds,
$accessGroups
);
}
if ([] !== ($idsNotFound = array_diff($serviceCategoriesIds, $serviceCategoriesIdsFound))) {
throw ServiceTemplateException::idsDoNotExist('service_categories', $idsNotFound);
}
}
/**
* @param ServiceGroupDto[] $serviceGroupDtos
* @param int $serviceTemplateId,
* @param ContactInterface $contact
* @param AccessGroup[] $accessGroups
*
* @throws ServiceTemplateException
* @throws \Throwable
*/
public function assertServiceGroups(
array $serviceGroupDtos,
int $serviceTemplateId,
ContactInterface $contact,
array $accessGroups,
): void {
if ($serviceGroupDtos === []) {
return;
}
$serviceGroupIds = array_map(
fn (ServiceGroupDto $serviceGroup) => $serviceGroup->serviceGroupId,
$serviceGroupDtos
);
$serviceGroupIds = array_unique($serviceGroupIds);
if ($contact->isAdmin()) {
$serviceGroupIdsFound = $this->readServiceGroupRepository->exist($serviceGroupIds);
} else {
$serviceGroupIdsFound = $this->readServiceGroupRepository->existByAccessGroups(
$serviceGroupIds,
$accessGroups
);
}
if ([] !== ($idsNotFound = array_diff($serviceGroupIds, $serviceGroupIdsFound))) {
throw ServiceTemplateException::idsDoNotExist('service_groups', $idsNotFound);
}
$hostTemplateIdsFromServiceGroupRelations = array_map(
fn (ServiceGroupDto $serviceGroup) => $serviceGroup->hostTemplateId,
$serviceGroupDtos
);
$serviceTemplate = $this->readServiceTemplateRepository->findById($serviceTemplateId);
if ($serviceTemplate !== null) {
$idsNotFound = array_diff($hostTemplateIdsFromServiceGroupRelations, $serviceTemplate->getHostTemplateIds());
if ($idsNotFound !== []) {
throw ServiceTemplateException::invalidServiceGroupAssociation();
}
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Application/UseCase/PartialUpdateServiceTemplate/PartialUpdateServiceTemplateRequest.php | centreon/src/Core/ServiceTemplate/Application/UseCase/PartialUpdateServiceTemplate/PartialUpdateServiceTemplateRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Application\UseCase\PartialUpdateServiceTemplate;
use Core\Common\Application\Type\NoValue;
final class PartialUpdateServiceTemplateRequest
{
public string|NoValue $name;
public string|NoValue $alias;
/** @var list<string> */
public array|NoValue $commandArguments;
/** @var list<string> */
public array|NoValue $eventHandlerArguments;
public int|NoValue $notificationTypes;
public bool|NoValue $isContactAdditiveInheritance;
public bool|NoValue $isContactGroupAdditiveInheritance;
public int|NoValue $activeChecksEnabled;
public int|NoValue $passiveCheckEnabled;
public int|NoValue $volatility;
public int|NoValue $checkFreshness;
public int|NoValue $eventHandlerEnabled;
public int|NoValue $flapDetectionEnabled;
public int|NoValue $notificationsEnabled;
public string|null|NoValue $comment;
public string|null|NoValue $note;
public string|null|NoValue $noteUrl;
public string|null|NoValue $actionUrl;
public string|null|NoValue $iconAlternativeText;
public int|null|NoValue $graphTemplateId;
public int|null|NoValue $serviceTemplateParentId;
public int|null|NoValue $commandId;
public int|null|NoValue $eventHandlerId;
public int|NoValue $notificationTimePeriodId;
public int|NoValue $checkTimePeriodId;
public int|null|NoValue $iconId;
public int|null|NoValue $severityId;
public int|null|NoValue $maxCheckAttempts;
public int|null|NoValue $normalCheckInterval;
public int|null|NoValue $retryCheckInterval;
public int|null|NoValue $freshnessThreshold;
public int|null|NoValue $lowFlapThreshold;
public int|null|NoValue $highFlapThreshold;
public int|null|NoValue $notificationInterval;
public int|null|NoValue $recoveryNotificationDelay;
public int|null|NoValue $firstNotificationDelay;
public int|null|NoValue $acknowledgementTimeout;
/** @var array<int>|NoValue */
public array|NoValue $hostTemplates;
/** @var array<int>|NoValue */
public array|NoValue $serviceCategories;
/** @var MacroDto[]|NoValue */
public array|NoValue $macros;
/** @var ServiceGroupDto[] */
public array|NoValue $serviceGroups;
public function __construct(public int $id)
{
$this->name = new NoValue();
$this->alias = new NoValue();
$this->commandArguments = new NoValue();
$this->eventHandlerArguments = new NoValue();
$this->notificationTypes = new NoValue();
$this->isContactAdditiveInheritance = new NoValue();
$this->isContactGroupAdditiveInheritance = new NoValue();
$this->activeChecksEnabled = new NoValue();
$this->passiveCheckEnabled = new NoValue();
$this->volatility = new NoValue();
$this->checkFreshness = new NoValue();
$this->eventHandlerEnabled = new NoValue();
$this->flapDetectionEnabled = new NoValue();
$this->notificationsEnabled = new NoValue();
$this->comment = new NoValue();
$this->note = new NoValue();
$this->noteUrl = new NoValue();
$this->actionUrl = new NoValue();
$this->iconAlternativeText = new NoValue();
$this->graphTemplateId = new NoValue();
$this->serviceTemplateParentId = new NoValue();
$this->commandId = new NoValue();
$this->eventHandlerId = new NoValue();
$this->notificationTimePeriodId = new NoValue();
$this->checkTimePeriodId = new NoValue();
$this->iconId = new NoValue();
$this->severityId = new NoValue();
$this->maxCheckAttempts = new NoValue();
$this->normalCheckInterval = new NoValue();
$this->retryCheckInterval = new NoValue();
$this->freshnessThreshold = new NoValue();
$this->lowFlapThreshold = new NoValue();
$this->highFlapThreshold = new NoValue();
$this->notificationInterval = new NoValue();
$this->recoveryNotificationDelay = new NoValue();
$this->firstNotificationDelay = new NoValue();
$this->acknowledgementTimeout = new NoValue();
$this->hostTemplates = new NoValue();
$this->serviceCategories = new NoValue();
$this->macros = new NoValue();
$this->serviceGroups = new NoValue();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Application/UseCase/AddServiceTemplate/AddServiceTemplate.php | centreon/src/Core/ServiceTemplate/Application/UseCase/AddServiceTemplate/AddServiceTemplate.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Application\UseCase\AddServiceTemplate;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Option\OptionService;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Core\Application\Common\UseCase\ConflictResponse;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\CommandMacro\Application\Repository\ReadCommandMacroRepositoryInterface;
use Core\CommandMacro\Domain\Model\CommandMacro;
use Core\CommandMacro\Domain\Model\CommandMacroType;
use Core\Common\Application\Repository\ReadVaultRepositoryInterface;
use Core\Common\Application\Repository\WriteVaultRepositoryInterface;
use Core\Common\Application\UseCase\VaultTrait;
use Core\Common\Domain\TrimmedString;
use Core\Common\Infrastructure\Repository\AbstractVaultRepository;
use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface;
use Core\Macro\Application\Repository\ReadServiceMacroRepositoryInterface;
use Core\Macro\Application\Repository\WriteServiceMacroRepositoryInterface;
use Core\Macro\Domain\Model\Macro;
use Core\Macro\Domain\Model\MacroDifference;
use Core\Macro\Domain\Model\MacroManager;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Core\ServiceCategory\Application\Repository\ReadServiceCategoryRepositoryInterface;
use Core\ServiceCategory\Application\Repository\WriteServiceCategoryRepositoryInterface;
use Core\ServiceCategory\Domain\Model\ServiceCategory;
use Core\ServiceGroup\Application\Repository\ReadServiceGroupRepositoryInterface;
use Core\ServiceGroup\Application\Repository\WriteServiceGroupRepositoryInterface;
use Core\ServiceGroup\Domain\Model\ServiceGroup;
use Core\ServiceGroup\Domain\Model\ServiceGroupRelation;
use Core\ServiceTemplate\Application\Exception\ServiceTemplateException;
use Core\ServiceTemplate\Application\Repository\ReadServiceTemplateRepositoryInterface;
use Core\ServiceTemplate\Application\Repository\WriteServiceTemplateRepositoryInterface;
use Core\ServiceTemplate\Domain\Model\NewServiceTemplate;
use Core\ServiceTemplate\Domain\Model\ServiceTemplate;
use Core\ServiceTemplate\Domain\Model\ServiceTemplateInheritance;
final class AddServiceTemplate
{
use LoggerTrait;
use VaultTrait;
/** @var AccessGroup[] */
private array $accessGroups;
public function __construct(
private readonly ReadHostTemplateRepositoryInterface $readHostTemplateRepository,
private readonly ReadServiceTemplateRepositoryInterface $readServiceTemplateRepository,
private readonly WriteServiceTemplateRepositoryInterface $writeServiceTemplateRepository,
private readonly ReadServiceMacroRepositoryInterface $readServiceMacroRepository,
private readonly ReadCommandMacroRepositoryInterface $readCommandMacroRepository,
private readonly WriteServiceMacroRepositoryInterface $writeServiceMacroRepository,
private readonly DataStorageEngineInterface $storageEngine,
private readonly ReadServiceCategoryRepositoryInterface $readServiceCategoryRepository,
private readonly WriteServiceCategoryRepositoryInterface $writeServiceCategoryRepository,
private readonly ReadServiceGroupRepositoryInterface $readServiceGroupRepository,
private readonly WriteServiceGroupRepositoryInterface $writeServiceGroupRepository,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly AddServiceTemplateValidation $validation,
private readonly OptionService $optionService,
private readonly ContactInterface $user,
private readonly WriteVaultRepositoryInterface $writeVaultRepository,
private readonly ReadVaultRepositoryInterface $readVaultRepository,
) {
$this->writeVaultRepository->setCustomPath(AbstractVaultRepository::SERVICE_VAULT_PATH);
}
/**
* @param AddServiceTemplateRequest $request
* @param AddServiceTemplatePresenterInterface $presenter
*/
public function __invoke(AddServiceTemplateRequest $request, AddServiceTemplatePresenterInterface $presenter): void
{
try {
if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE)) {
$this->error(
"User doesn't have sufficient rights to add a service template",
['user_id' => $this->user->getId()]
);
$presenter->presentResponse(
new ForbiddenResponse(ServiceTemplateException::addNotAllowed())
);
return;
}
if (! $this->user->isAdmin()) {
$this->accessGroups = $this->readAccessGroupRepository->findByContact($this->user);
$this->validation->accessGroups = $this->accessGroups;
}
$formattedName = ServiceTemplate::formatName($request->name);
if ($formattedName !== null) {
$nameToCheck = new TrimmedString($formattedName);
if ($this->readServiceTemplateRepository->existsByName($nameToCheck)) {
$presenter->presentResponse(
new ConflictResponse(ServiceTemplateException::nameAlreadyExists((string) $nameToCheck))
);
return;
}
}
$this->assertParameters($request);
$newServiceTemplateId = $this->createServiceTemplate($request);
$this->info('New service template created', ['service_template_id' => $newServiceTemplateId]);
$serviceTemplate = $this->readServiceTemplateRepository->findById($newServiceTemplateId);
if (! $serviceTemplate) {
$presenter->presentResponse(
new ErrorResponse(ServiceTemplateException::errorWhileRetrieving())
);
return;
}
if ($this->user->isAdmin()) {
$serviceCategories = $this->readServiceCategoryRepository->findByService($newServiceTemplateId);
$serviceGroups = $this->readServiceGroupRepository->findByService($newServiceTemplateId);
} else {
$serviceCategories = $this->readServiceCategoryRepository->findByServiceAndAccessGroups(
$newServiceTemplateId,
$this->accessGroups
);
$serviceGroups = $this->readServiceGroupRepository->findByServiceAndAccessGroups(
$newServiceTemplateId,
$this->accessGroups
);
}
$presenter->presentResponse($this->createResponse($serviceTemplate, $serviceCategories, $serviceGroups));
} catch (AssertionFailedException $ex) {
$presenter->presentResponse(new InvalidArgumentResponse($ex));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (ServiceTemplateException $ex) {
$presenter->presentResponse(
match ($ex->getCode()) {
ServiceTemplateException::CODE_CONFLICT => new ConflictResponse($ex),
default => new ErrorResponse($ex),
}
);
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (\Throwable $ex) {
$presenter->presentResponse(new ErrorResponse(ServiceTemplateException::errorWhileAdding($ex)));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
}
}
/**
* @param int $serviceTemplateId
* @param AddServiceTemplateRequest $request
*
* @throws AssertionFailedException
* @throws \Throwable
*/
private function addMacros(int $serviceTemplateId, AddServiceTemplateRequest $request): void
{
$this->info('Add macros', ['service_template_id' => $serviceTemplateId]);
/**
* @var array<string,Macro> $inheritedMacros
* @var array<string,CommandMacro> $commandMacros
*/
[$inheritedMacros, $commandMacros] = $this->findAllInheritedMacros($serviceTemplateId, $request->commandId);
$macros = [];
foreach ($request->macros as $macro) {
$macro = MacroFactory::create($macro, $serviceTemplateId, $inheritedMacros);
$macros[$macro->getName()] = $macro;
}
$macrosDiff = new MacroDifference();
$macrosDiff->compute([], $inheritedMacros, $commandMacros, $macros);
MacroManager::setOrder($macrosDiff, $macros, []);
foreach ($macrosDiff->addedMacros as $macro) {
if ($macro->getDescription() === '') {
$macro->setDescription(
isset($commandMacros[$macro->getName()])
? $commandMacros[$macro->getName()]->getDescription()
: ''
);
}
$this->info('Add the macro ' . $macro->getName());
if ($this->writeVaultRepository->isVaultConfigured() === true && $macro->isPassword() === true) {
$vaultPaths = $this->writeVaultRepository->upsert(
$this->uuid ?? null,
['_SERVICE' . $macro->getName() => $macro->getValue()],
);
$vaultPath = $vaultPaths['_SERVICE' . $macro->getName()];
$this->uuid ??= $this->getUuidFromPath($vaultPath);
$inVaultMacro = new Macro($macro->getId(), $macro->getOwnerId(), $macro->getName(), $vaultPath);
$inVaultMacro->setDescription($macro->getDescription());
$inVaultMacro->setIsPassword($macro->isPassword());
$inVaultMacro->setOrder($macro->getOrder());
$macro = $inVaultMacro;
}
$this->writeServiceMacroRepository->add($macro);
}
}
/**
* @param AddServiceTemplateRequest $request
*
* @throws \Exception
* @throws AssertionFailedException
*
* @return NewServiceTemplate
*/
private function createNewServiceTemplate(AddServiceTemplateRequest $request): NewServiceTemplate
{
$inheritanceMode = $this->optionService->findSelectedOptions(['inheritance_mode']);
$inheritanceMode = isset($inheritanceMode[0])
? (int) $inheritanceMode[0]->getValue()
: 0;
return NewServiceTemplateFactory::create((int) $inheritanceMode, $request);
}
/**
* @param int $serviceTemplateId
* @param AddServiceTemplateRequest $request
*
* @throws \Throwable
*/
private function linkServiceTemplateToServiceCategories(int $serviceTemplateId, AddServiceTemplateRequest $request): void
{
if ($request->serviceCategories === []) {
return;
}
$this->info(
'Link existing service categories to service',
['service_categories' => $request->serviceCategories]
);
$this->writeServiceCategoryRepository->linkToService($serviceTemplateId, $request->serviceCategories);
}
/**
* @param int $serviceTemplateId
* @param AddServiceTemplateRequest $request
*
* @throws \Throwable
*/
private function linkServiceTemplateToServiceGroups(int $serviceTemplateId, AddServiceTemplateRequest $request): void
{
if ($request->serviceGroups === []) {
return;
}
$this->info(
'Link existing service groups to service',
['service_groups' => $request->serviceGroups]
);
$serviceGroupRelations = [];
$serviceGroupDtos = $this->removeDuplicates($request->serviceGroups);
foreach ($serviceGroupDtos as $serviceGroup) {
$serviceGroupRelations[] = new ServiceGroupRelation(
serviceGroupId: $serviceGroup->serviceGroupId,
serviceId: $serviceTemplateId,
hostId: $serviceGroup->hostTemplateId
);
}
$this->writeServiceGroupRepository->link($serviceGroupRelations);
}
/**
* @param ServiceGroupDto[] $serviceGroupList
*
* @return ServiceGroupDto[]
*/
private function removeDuplicates(array $serviceGroupList): array
{
$uniqueList = [];
foreach ($serviceGroupList as $item) {
$uniqueList[$item->serviceGroupId . '_' . $item->hostTemplateId] = $item;
}
return array_values($uniqueList);
}
/**
* @param ServiceTemplate $serviceTemplate
* @param ServiceCategory[] $serviceCategories
* @param array<array{relation:ServiceGroupRelation,serviceGroup:ServiceGroup}> $serviceGroups
*
* @throws \Throwable
*
* @return AddServiceTemplateResponse
*/
private function createResponse(ServiceTemplate $serviceTemplate, array $serviceCategories, array $serviceGroups): AddServiceTemplateResponse
{
$macros = $this->readServiceMacroRepository->findByServiceIds($serviceTemplate->getId());
$response = new AddServiceTemplateResponse();
$response->id = $serviceTemplate->getId();
$response->name = $serviceTemplate->getName();
$response->alias = $serviceTemplate->getAlias();
$response->commandArguments = $serviceTemplate->getCommandArguments();
$response->eventHandlerArguments = $serviceTemplate->getEventHandlerArguments();
$response->notificationTypes = $serviceTemplate->getNotificationTypes();
$response->isContactAdditiveInheritance = $serviceTemplate->isContactAdditiveInheritance();
$response->isContactGroupAdditiveInheritance = $serviceTemplate->isContactGroupAdditiveInheritance();
$response->isLocked = $serviceTemplate->isLocked();
$response->activeChecks = $serviceTemplate->getActiveChecks();
$response->passiveCheck = $serviceTemplate->getPassiveCheck();
$response->volatility = $serviceTemplate->getVolatility();
$response->checkFreshness = $serviceTemplate->getCheckFreshness();
$response->eventHandlerEnabled = $serviceTemplate->getEventHandlerEnabled();
$response->flapDetectionEnabled = $serviceTemplate->getFlapDetectionEnabled();
$response->notificationsEnabled = $serviceTemplate->getNotificationsEnabled();
$response->comment = $serviceTemplate->getComment();
$response->note = $serviceTemplate->getNote();
$response->noteUrl = $serviceTemplate->getNoteUrl();
$response->actionUrl = $serviceTemplate->getActionUrl();
$response->iconAlternativeText = $serviceTemplate->getIconAlternativeText();
$response->graphTemplateId = $serviceTemplate->getGraphTemplateId();
$response->serviceTemplateId = $serviceTemplate->getServiceTemplateParentId();
$response->commandId = $serviceTemplate->getCommandId();
$response->eventHandlerId = $serviceTemplate->getEventHandlerId();
$response->notificationTimePeriodId = $serviceTemplate->getNotificationTimePeriodId();
$response->checkTimePeriodId = $serviceTemplate->getCheckTimePeriodId();
$response->iconId = $serviceTemplate->getIconId();
$response->severityId = $serviceTemplate->getSeverityId();
$response->hostTemplateIds = $serviceTemplate->getHostTemplateIds();
$response->maxCheckAttempts = $serviceTemplate->getMaxCheckAttempts();
$response->normalCheckInterval = $serviceTemplate->getNormalCheckInterval();
$response->retryCheckInterval = $serviceTemplate->getRetryCheckInterval();
$response->freshnessThreshold = $serviceTemplate->getFreshnessThreshold();
$response->lowFlapThreshold = $serviceTemplate->getLowFlapThreshold();
$response->highFlapThreshold = $serviceTemplate->getHighFlapThreshold();
$response->notificationInterval = $serviceTemplate->getNotificationInterval();
$response->recoveryNotificationDelay = $serviceTemplate->getRecoveryNotificationDelay();
$response->firstNotificationDelay = $serviceTemplate->getFirstNotificationDelay();
$response->acknowledgementTimeout = $serviceTemplate->getAcknowledgementTimeout();
$response->macros = array_map(
fn (Macro $macro): MacroDto => new MacroDto(
$macro->getName(),
$macro->getValue(),
$macro->isPassword(),
$macro->getDescription()
),
$macros
);
$response->categories = array_map(
fn (ServiceCategory $category) => ['id' => $category->getId(), 'name' => $category->getName()],
$serviceCategories
);
$hostTemplateNames = $this->readHostTemplateRepository->findNamesByIds(array_map(
fn (array $group): int => (int) $group['relation']->getHostId(),
$serviceGroups
));
$response->groups = array_map(
fn (array $group) => [
'serviceGroupId' => $group['serviceGroup']->getId(),
'serviceGroupName' => $group['serviceGroup']->getName(),
'hostTemplateId' => (int) $group['relation']->getHostId(),
'hostTemplateName' => $hostTemplateNames[(int) $group['relation']->getHostId()],
],
$serviceGroups,
);
return $response;
}
/**
* @param AddServiceTemplateRequest $request
*
* @throws ServiceTemplateException
* @throws \Throwable
*/
private function assertParameters(AddServiceTemplateRequest $request): void
{
$this->validation->assertIsValidSeverity($request->severityId);
$this->validation->assertIsValidPerformanceGraph($request->graphTemplateId);
$this->validation->assertIsValidServiceTemplate($request->serviceTemplateParentId);
$this->validation->assertIsValidCommand($request->commandId);
$this->validation->assertIsValidEventHandler($request->eventHandlerId);
$this->validation->assertIsValidTimePeriod($request->checkTimePeriodId);
$this->validation->assertIsValidNotificationTimePeriod($request->notificationTimePeriodId);
$this->validation->assertIsValidIcon($request->iconId);
$this->validation->assertIsValidHostTemplates($request->hostTemplateIds);
$this->validation->assertIsValidServiceCategories($request->serviceCategories);
$this->validation->assertIsValidServiceGroups($request->serviceGroups, $request->hostTemplateIds);
}
/**
* @param AddServiceTemplateRequest $request
*
* @throws AssertionFailedException
* @throws ServiceTemplateException
* @throws \Throwable
*
* @return int
*/
private function createServiceTemplate(AddServiceTemplateRequest $request): int
{
$newServiceTemplate = $this->createNewServiceTemplate($request);
$this->storageEngine->startTransaction();
try {
$newServiceTemplateId = $this->writeServiceTemplateRepository->add($newServiceTemplate);
$this->addMacros($newServiceTemplateId, $request);
$this->linkServiceTemplateToServiceCategories($newServiceTemplateId, $request);
$this->linkServiceTemplateToServiceGroups($newServiceTemplateId, $request);
$this->storageEngine->commitTransaction();
return $newServiceTemplateId;
} catch (\Throwable $ex) {
$this->error("Rollback of 'Add Service Template' transaction.");
$this->storageEngine->rollbackTransaction();
throw $ex;
}
}
/**
* @param int $serviceTemplateId
* @param int|null $checkCommandId
*
* @throws \Throwable
*
* @return array{
* array<string,Macro>,
* array<string,CommandMacro>
* }
*/
private function findAllInheritedMacros(int $serviceTemplateId, ?int $checkCommandId): array
{
$serviceTemplateInheritances = $this->readServiceTemplateRepository->findParents($serviceTemplateId);
$inheritanceLine = ServiceTemplateInheritance::createInheritanceLine(
$serviceTemplateId,
$serviceTemplateInheritances
);
$existingMacros = $this->readServiceMacroRepository->findByServiceIds(...$inheritanceLine);
[, $inheritedMacros] = Macro::resolveInheritance($existingMacros, $inheritanceLine, $serviceTemplateId);
/** @var array<string,CommandMacro> $commandMacros */
$commandMacros = [];
if ($checkCommandId !== null) {
$existingCommandMacros = $this->readCommandMacroRepository->findByCommandIdAndType(
$checkCommandId,
CommandMacroType::Service
);
$commandMacros = MacroManager::resolveInheritanceForCommandMacro($existingCommandMacros);
}
return [
$this->writeVaultRepository->isVaultConfigured()
? $this->retrieveMacrosVaultValues($inheritedMacros)
: $inheritedMacros,
$commandMacros,
];
}
/**
* @param array<string,Macro> $macros
*
* @throws \Throwable
*
* @return array<string,Macro>
*/
private function retrieveMacrosVaultValues(array $macros): array
{
$updatedMacros = [];
foreach ($macros as $key => $macro) {
if ($macro->isPassword() === false) {
$updatedMacros[$key] = $macro;
continue;
}
$vaultData = $this->readVaultRepository->findFromPath($macro->getValue());
$vaultKey = '_SERVICE' . $macro->getName();
if (isset($vaultData[$vaultKey])) {
$inVaultMacro = new Macro($macro->getId(), $macro->getOwnerId(), $macro->getName(), $vaultData[$vaultKey]);
$inVaultMacro->setDescription($macro->getDescription());
$inVaultMacro->setIsPassword($macro->isPassword());
$inVaultMacro->setOrder($macro->getOrder());
$updatedMacros[$key] = $inVaultMacro;
}
}
return $updatedMacros;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Application/UseCase/AddServiceTemplate/AddServiceTemplatePresenterInterface.php | centreon/src/Core/ServiceTemplate/Application/UseCase/AddServiceTemplate/AddServiceTemplatePresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Application\UseCase\AddServiceTemplate;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface AddServiceTemplatePresenterInterface
{
public function presentResponse(AddServiceTemplateResponse|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/ServiceTemplate/Application/UseCase/AddServiceTemplate/AddServiceTemplateRequest.php | centreon/src/Core/ServiceTemplate/Application/UseCase/AddServiceTemplate/AddServiceTemplateRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Application\UseCase\AddServiceTemplate;
final class AddServiceTemplateRequest
{
public string $name = '';
public string $alias = '';
/** @var list<string> */
public array $commandArguments = [];
/** @var list<string> */
public array $eventHandlerArguments = [];
/** @var list<int> */
public array $hostTemplateIds = [];
/** @var list<int> */
public array $serviceCategories = [];
/** @var ServiceGroupDto[] */
public array $serviceGroups = [];
public int|null $notificationTypes = null;
public bool $isContactAdditiveInheritance = false;
public bool $isContactGroupAdditiveInheritance = false;
public int $activeChecks = 0;
public int $passiveCheck = 0;
public int $volatility = 0;
public int $checkFreshness = 0;
public int $eventHandlerEnabled = 0;
public int $flapDetectionEnabled = 0;
public int $notificationsEnabled = 0;
public string|null $comment = null;
public string|null $note = null;
public string|null $noteUrl = null;
public string|null $actionUrl = null;
public string|null $iconAlternativeText = null;
public int|null $graphTemplateId = null;
public int|null $serviceTemplateParentId = null;
public int|null $commandId = null;
public int|null $eventHandlerId = null;
public int|null $notificationTimePeriodId = null;
public int|null $checkTimePeriodId = null;
public int|null $iconId = null;
public int|null $severityId = null;
public int|null $maxCheckAttempts = null;
public int|null $normalCheckInterval = null;
public int|null $retryCheckInterval = null;
public int|null $freshnessThreshold = null;
public int|null $lowFlapThreshold = null;
public int|null $highFlapThreshold = null;
public int|null $notificationInterval = null;
public int|null $recoveryNotificationDelay = null;
public int|null $firstNotificationDelay = null;
public int|null $acknowledgementTimeout = null;
/** @var MacroDto[] */
public array $macros = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Application/UseCase/AddServiceTemplate/NewServiceTemplateFactory.php | centreon/src/Core/ServiceTemplate/Application/UseCase/AddServiceTemplate/NewServiceTemplateFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Application\UseCase\AddServiceTemplate;
use Assert\AssertionFailedException;
use Core\ServiceTemplate\Application\Model\NotificationTypeConverter;
use Core\ServiceTemplate\Application\Model\YesNoDefaultConverter;
use Core\ServiceTemplate\Domain\Model\NewServiceTemplate;
class NewServiceTemplateFactory
{
/**
* @param int $inheritanceMode
* @param AddServiceTemplateRequest $request
*
* @throws AssertionFailedException
*
* @return NewServiceTemplate
*/
public static function create(int $inheritanceMode, AddServiceTemplateRequest $request): NewServiceTemplate
{
$serviceTemplate = new NewServiceTemplate($request->name, $request->alias);
foreach ($request->commandArguments as $argument) {
$serviceTemplate->addCommandArgument($argument);
}
foreach ($request->eventHandlerArguments as $argument) {
$serviceTemplate->addEventHandlerArgument($argument);
}
if ($request->notificationTypes !== null) {
foreach (NotificationTypeConverter::fromBits($request->notificationTypes) as $notificationType) {
$serviceTemplate->addNotificationType($notificationType);
}
}
$serviceTemplate->setContactAdditiveInheritance(
($inheritanceMode === 1) ? $request->isContactAdditiveInheritance : false
);
$serviceTemplate->setContactGroupAdditiveInheritance(
($inheritanceMode === 1) ? $request->isContactGroupAdditiveInheritance : false
);
$serviceTemplate->setLocked(false);
$serviceTemplate->setActiveChecks(YesNoDefaultConverter::fromInt($request->activeChecks));
$serviceTemplate->setPassiveCheck(YesNoDefaultConverter::fromInt($request->passiveCheck));
$serviceTemplate->setVolatility(YesNoDefaultConverter::fromInt($request->volatility));
$serviceTemplate->setCheckFreshness(YesNoDefaultConverter::fromInt($request->checkFreshness));
$serviceTemplate->setEventHandlerEnabled(YesNoDefaultConverter::fromInt($request->eventHandlerEnabled));
$serviceTemplate->setFlapDetectionEnabled(YesNoDefaultConverter::fromInt($request->flapDetectionEnabled));
$serviceTemplate->setNotificationsEnabled(YesNoDefaultConverter::fromInt($request->notificationsEnabled));
$serviceTemplate->setComment($request->comment);
$serviceTemplate->setNote($request->note);
$serviceTemplate->setNoteUrl($request->noteUrl);
$serviceTemplate->setActionUrl($request->actionUrl);
$serviceTemplate->setIconAlternativeText($request->iconAlternativeText);
$serviceTemplate->setGraphTemplateId($request->graphTemplateId);
$serviceTemplate->setServiceTemplateParentId($request->serviceTemplateParentId);
$serviceTemplate->setCommandId($request->commandId);
$serviceTemplate->setEventHandlerId($request->eventHandlerId);
$serviceTemplate->setNotificationTimePeriodId($request->notificationTimePeriodId);
$serviceTemplate->setCheckTimePeriodId($request->checkTimePeriodId);
$serviceTemplate->setIconId($request->iconId);
$serviceTemplate->setSeverityId($request->severityId);
$serviceTemplate->setMaxCheckAttempts($request->maxCheckAttempts);
$serviceTemplate->setNormalCheckInterval($request->normalCheckInterval);
$serviceTemplate->setRetryCheckInterval($request->retryCheckInterval);
$serviceTemplate->setFreshnessThreshold($request->freshnessThreshold);
$serviceTemplate->setLowFlapThreshold($request->lowFlapThreshold);
$serviceTemplate->setHighFlapThreshold($request->highFlapThreshold);
$serviceTemplate->setNotificationInterval($request->notificationInterval);
$serviceTemplate->setRecoveryNotificationDelay($request->recoveryNotificationDelay);
$serviceTemplate->setFirstNotificationDelay($request->firstNotificationDelay);
$serviceTemplate->setAcknowledgementTimeout($request->acknowledgementTimeout);
$serviceTemplate->setHostTemplateIds($request->hostTemplateIds);
return $serviceTemplate;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Application/UseCase/AddServiceTemplate/AddServiceTemplateValidation.php | centreon/src/Core/ServiceTemplate/Application/UseCase/AddServiceTemplate/AddServiceTemplateValidation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Application\UseCase\AddServiceTemplate;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Command\Application\Repository\ReadCommandRepositoryInterface;
use Core\Command\Domain\Model\CommandType;
use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface;
use Core\PerformanceGraph\Application\Repository\ReadPerformanceGraphRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Core\ServiceCategory\Application\Repository\ReadServiceCategoryRepositoryInterface;
use Core\ServiceGroup\Application\Repository\ReadServiceGroupRepositoryInterface;
use Core\ServiceSeverity\Application\Repository\ReadServiceSeverityRepositoryInterface;
use Core\ServiceTemplate\Application\Exception\ServiceTemplateException;
use Core\ServiceTemplate\Application\Repository\ReadServiceTemplateRepositoryInterface;
use Core\TimePeriod\Application\Repository\ReadTimePeriodRepositoryInterface;
use Core\ViewImg\Application\Repository\ReadViewImgRepositoryInterface;
class AddServiceTemplateValidation
{
use LoggerTrait;
/**
* @param ReadServiceTemplateRepositoryInterface $readServiceTemplateRepository
* @param ReadServiceSeverityRepositoryInterface $serviceSeverityRepository
* @param ReadPerformanceGraphRepositoryInterface $performanceGraphRepository
* @param ReadCommandRepositoryInterface $commandRepository
* @param ReadTimePeriodRepositoryInterface $timePeriodRepository
* @param ReadViewImgRepositoryInterface $imageRepository
* @param ReadHostTemplateRepositoryInterface $readHostTemplateRepository
* @param ReadServiceCategoryRepositoryInterface $readServiceCategoryRepository
* @param ReadServiceGroupRepositoryInterface $readServiceGroupRepository
* @param ContactInterface $user
* @param AccessGroup[] $accessGroups
*/
public function __construct(
private readonly ReadServiceTemplateRepositoryInterface $readServiceTemplateRepository,
private readonly ReadServiceSeverityRepositoryInterface $serviceSeverityRepository,
private readonly ReadPerformanceGraphRepositoryInterface $performanceGraphRepository,
private readonly ReadCommandRepositoryInterface $commandRepository,
private readonly ReadTimePeriodRepositoryInterface $timePeriodRepository,
private readonly ReadViewImgRepositoryInterface $imageRepository,
private readonly ReadHostTemplateRepositoryInterface $readHostTemplateRepository,
private readonly ReadServiceCategoryRepositoryInterface $readServiceCategoryRepository,
private readonly ReadServiceGroupRepositoryInterface $readServiceGroupRepository,
private readonly ContactInterface $user,
public array $accessGroups = [],
) {
}
/**
* @param int|null $serviceTemplateId
*
* @throws ServiceTemplateException
* @throws \Throwable
*/
public function assertIsValidServiceTemplate(?int $serviceTemplateId): void
{
if ($serviceTemplateId !== null && ! $this->readServiceTemplateRepository->exists($serviceTemplateId)) {
$this->error('Service template does not exist', ['service_template_id' => $serviceTemplateId]);
throw ServiceTemplateException::idDoesNotExist('service_template_id', $serviceTemplateId);
}
}
/**
* @param int|null $commandId
*
* @throws ServiceTemplateException
*/
public function assertIsValidCommand(?int $commandId): void
{
if (
$commandId !== null
&& ! $this->commandRepository->existsByIdAndCommandType($commandId, CommandType::Check)
) {
$this->error('Check command does not exist', ['check_command_id' => $commandId]);
throw ServiceTemplateException::idDoesNotExist('check_command_id', $commandId);
}
}
/**
* @param int|null $eventHandlerId
*
* @throws ServiceTemplateException
*/
public function assertIsValidEventHandler(?int $eventHandlerId): void
{
if ($eventHandlerId !== null && ! $this->commandRepository->exists($eventHandlerId)) {
$this->error('Event handler command does not exist', ['event_handler_command_id' => $eventHandlerId]);
throw ServiceTemplateException::idDoesNotExist('event_handler_command_id', $eventHandlerId);
}
}
/**
* @param int|null $timePeriodId
*
* @throws ServiceTemplateException
* @throws \Throwable
*/
public function assertIsValidTimePeriod(?int $timePeriodId): void
{
if ($timePeriodId !== null && ! $this->timePeriodRepository->exists($timePeriodId)) {
$this->error('Time period does not exist', ['check_timeperiod_id' => $timePeriodId]);
throw ServiceTemplateException::idDoesNotExist('check_timeperiod_id', $timePeriodId);
}
}
/**
* @param int|null $iconId
*
* @throws ServiceTemplateException
* @throws \Throwable
*/
public function assertIsValidIcon(?int $iconId): void
{
if ($iconId !== null && ! $this->imageRepository->existsOne($iconId)) {
$this->error('Icon does not exist', ['icon_id' => $iconId]);
throw ServiceTemplateException::idDoesNotExist('icon_id', $iconId);
}
}
/**
* @param int|null $notificationTimePeriodId
*
* @throws ServiceTemplateException
* @throws \Throwable
*/
public function assertIsValidNotificationTimePeriod(?int $notificationTimePeriodId): void
{
if ($notificationTimePeriodId !== null && ! $this->timePeriodRepository->exists($notificationTimePeriodId)) {
$this->error(
'Notification time period does not exist',
['notification_timeperiod_id' => $notificationTimePeriodId]
);
throw ServiceTemplateException::idDoesNotExist('notification_timeperiod_id', $notificationTimePeriodId);
}
}
/**
* @param int|null $severityId
*
* @throws ServiceTemplateException
* @throws \Throwable
*/
public function assertIsValidSeverity(?int $severityId): void
{
if ($severityId !== null) {
$exists = ($this->accessGroups === [])
? $this->serviceSeverityRepository->exists($severityId)
: $this->serviceSeverityRepository->existsByAccessGroups($severityId, $this->accessGroups);
if (! $exists) {
$this->error('Service severity does not exist', ['severity_id' => $severityId]);
throw ServiceTemplateException::idDoesNotExist('severity_id', $severityId);
}
}
}
/**
* @param int|null $graphTemplateId
*
* @throws ServiceTemplateException
* @throws \Throwable
*/
public function assertIsValidPerformanceGraph(?int $graphTemplateId): void
{
if ($graphTemplateId !== null && ! $this->performanceGraphRepository->exists($graphTemplateId)) {
$this->error('Performance graph does not exist', ['graph_template_id' => $graphTemplateId]);
throw ServiceTemplateException::idDoesNotExist('graph_template_id', $graphTemplateId);
}
}
/**
* @param list<int> $hostTemplateIds
*
* @throws ServiceTemplateException
*/
public function assertIsValidHostTemplates(array $hostTemplateIds): void
{
if ($hostTemplateIds !== []) {
$hostTemplateIds = array_unique($hostTemplateIds);
$hostTemplateIdsFound = $this->readHostTemplateRepository->findAllExistingIds($hostTemplateIds);
if ([] !== ($diff = array_diff($hostTemplateIds, $hostTemplateIdsFound))) {
throw ServiceTemplateException::idsDoNotExist('host_templates', $diff);
}
}
}
/**
* @param int[] $serviceCategoriesIds
*
* @throws ServiceTemplateException
* @throws \Throwable
*/
public function assertIsValidServiceCategories(array $serviceCategoriesIds): void
{
if ($serviceCategoriesIds === []) {
return;
}
if ($this->user->isAdmin()) {
$serviceCategoriesIdsFound = $this->readServiceCategoryRepository->findAllExistingIds(
$serviceCategoriesIds
);
} else {
$serviceCategoriesIdsFound = $this->readServiceCategoryRepository->findAllExistingIdsByAccessGroups(
$serviceCategoriesIds,
$this->accessGroups
);
}
if ([] !== ($idsNotFound = array_diff($serviceCategoriesIds, $serviceCategoriesIdsFound))) {
throw ServiceTemplateException::idsDoNotExist('service_categories', $idsNotFound);
}
}
/**
* @param ServiceGroupDto[] $serviceGroups
* @param int[] $hostTemplateIds
*
* @throws ServiceTemplateException
* @throws \Throwable
*/
public function assertIsValidServiceGroups(array $serviceGroups, array $hostTemplateIds): void
{
if ($serviceGroups === []) {
return;
}
$serviceGroupIds = [];
foreach ($serviceGroups as $serviceGroup) {
if (in_array($serviceGroup->hostTemplateId, $hostTemplateIds, true) === false) {
throw ServiceTemplateException::invalidServiceGroupAssociation();
}
$serviceGroupIds[] = $serviceGroup->serviceGroupId;
}
if ($this->user->isAdmin()) {
$serviceGroupIdsFound = $this->readServiceGroupRepository->exist($serviceGroupIds);
} else {
$serviceGroupIdsFound = $this->readServiceGroupRepository->existByAccessGroups(
$serviceGroupIds,
$this->accessGroups
);
}
if ([] !== ($idsNotFound = array_diff($serviceGroupIds, $serviceGroupIdsFound))) {
throw ServiceTemplateException::idsDoNotExist('service_groups', $idsNotFound);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Application/UseCase/AddServiceTemplate/ServiceGroupDto.php | centreon/src/Core/ServiceTemplate/Application/UseCase/AddServiceTemplate/ServiceGroupDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Application\UseCase\AddServiceTemplate;
class ServiceGroupDto
{
public function __construct(
public int $hostTemplateId,
public int $serviceGroupId,
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Application/UseCase/AddServiceTemplate/AddServiceTemplateResponse.php | centreon/src/Core/ServiceTemplate/Application/UseCase/AddServiceTemplate/AddServiceTemplateResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Application\UseCase\AddServiceTemplate;
use Core\Common\Domain\YesNoDefault;
use Core\ServiceTemplate\Domain\Model\NotificationType;
final class AddServiceTemplateResponse
{
public int $id = 0;
public string $name = '';
public string $alias = '';
public string|null $comment = null;
public int|null $acknowledgementTimeout = null;
public string|null $actionUrl = null;
public bool $isContactAdditiveInheritance = false;
public bool $isContactGroupAdditiveInheritance = false;
public int|null $commandId = null;
/** @var string[] */
public array $commandArguments = [];
public int|null $eventHandlerId = null;
/** @var string[] */
public array $eventHandlerArguments = [];
public int|null $checkTimePeriodId = null;
public int|null $firstNotificationDelay = null;
public int|null $freshnessThreshold = null;
public int|null $graphTemplateId = null;
public int|null $lowFlapThreshold = null;
public int|null $highFlapThreshold = null;
public int|null $iconId = null;
public string|null $iconAlternativeText = null;
public bool $isLocked = false;
public YesNoDefault $activeChecks = YesNoDefault::Default;
public YesNoDefault $eventHandlerEnabled = YesNoDefault::Default;
public YesNoDefault $flapDetectionEnabled = YesNoDefault::Default;
public YesNoDefault $checkFreshness = YesNoDefault::Default;
public YesNoDefault $notificationsEnabled = YesNoDefault::Default;
public YesNoDefault $passiveCheck = YesNoDefault::Default;
public YesNoDefault $volatility = YesNoDefault::Default;
public int|null $maxCheckAttempts = null;
public int|null $normalCheckInterval = null;
public string|null $note = null;
public string|null $noteUrl = null;
public int|null $notificationInterval = null;
public int|null $notificationTimePeriodId = null;
/** @var NotificationType[] */
public array $notificationTypes = [];
/** @var list<int> */
public array $hostTemplateIds = [];
public int|null $recoveryNotificationDelay = null;
public int|null $retryCheckInterval = null;
public int|null $serviceTemplateId = null;
public int|null $severityId = null;
/** @var MacroDto[] */
public array $macros = [];
/** @var array<array{id:int,name:string}> */
public array $categories = [];
/** @var array<array{serviceGroupId:int,serviceGroupName:string,hostTemplateId:int,hostTemplateName:string}> */
public array $groups = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Application/UseCase/AddServiceTemplate/MacroDto.php | centreon/src/Core/ServiceTemplate/Application/UseCase/AddServiceTemplate/MacroDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Application\UseCase\AddServiceTemplate;
class MacroDto
{
public function __construct(
public string $name,
public ?string $value,
public bool $isPassword,
public ?string $description,
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Application/UseCase/AddServiceTemplate/MacroFactory.php | centreon/src/Core/ServiceTemplate/Application/UseCase/AddServiceTemplate/MacroFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Application\UseCase\AddServiceTemplate;
use Assert\AssertionFailedException;
use Core\Macro\Domain\Model\Macro;
final class MacroFactory
{
/**
* Create macros object from the request data.
* Use direct and inherited macros to retrieve value of macro with isPassword when not provided in dto.
*
* @param MacroDto $dto
* @param int $serviceTemplateId
* @param array<string,Macro> $inheritedMacros
*
* @throws \Throwable
* @throws AssertionFailedException
*
* @return Macro
*/
public static function create(
MacroDto $dto,
int $serviceTemplateId,
array $inheritedMacros,
): Macro {
$macroName = mb_strtoupper($dto->name);
$macroValue = $dto->value ?? '';
$passwordHasNotChanged = ($dto->value === null) && $dto->isPassword;
// Note: do not handle vault storage at the moment
if ($passwordHasNotChanged) {
$macroValue = match (true) {
// retrieve actual password value
isset($inheritedMacros[$macroName]) => $inheritedMacros[$macroName]->getValue(),
default => $macroValue,
};
}
$macro = new Macro(
null,
$serviceTemplateId,
$dto->name,
$macroValue,
);
$macro->setIsPassword($dto->isPassword);
$macro->setDescription($dto->description ?? '');
return $macro;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Application/UseCase/DeleteServiceTemplate/DeleteServiceTemplate.php | centreon/src/Core/ServiceTemplate/Application/UseCase/DeleteServiceTemplate/DeleteServiceTemplate.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Application\UseCase\DeleteServiceTemplate;
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\Common\Application\Repository\WriteVaultRepositoryInterface;
use Core\Common\Application\UseCase\VaultTrait;
use Core\Common\Infrastructure\Repository\AbstractVaultRepository;
use Core\Macro\Application\Repository\ReadServiceMacroRepositoryInterface;
use Core\ServiceTemplate\Application\Exception\ServiceTemplateException;
use Core\ServiceTemplate\Application\Repository\ReadServiceTemplateRepositoryInterface;
use Core\ServiceTemplate\Application\Repository\WriteServiceTemplateRepositoryInterface;
final class DeleteServiceTemplate
{
use LoggerTrait;
use VaultTrait;
/**
* @param ReadServiceTemplateRepositoryInterface $readRepository
* @param WriteServiceTemplateRepositoryInterface $writeRepository
* @param ContactInterface $user
* @param WriteVaultRepositoryInterface $writeVaultRepository
* @param ReadServiceMacroRepositoryInterface $readServiceMacroRepository
*/
public function __construct(
private readonly ReadServiceTemplateRepositoryInterface $readRepository,
private readonly WriteServiceTemplateRepositoryInterface $writeRepository,
private readonly ContactInterface $user,
private readonly WriteVaultRepositoryInterface $writeVaultRepository,
private readonly ReadServiceMacroRepositoryInterface $readServiceMacroRepository,
) {
$this->writeVaultRepository->setCustomPath(AbstractVaultRepository::SERVICE_VAULT_PATH);
}
/**
* @param int $serviceTemplateId
* @param PresenterInterface $presenter
*/
public function __invoke(int $serviceTemplateId, PresenterInterface $presenter): void
{
try {
if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE)) {
$this->error(
"User doesn't have sufficient rights to delete a service template",
['user_id' => $this->user->getId(), 'service_template_id' => $serviceTemplateId]
);
$presenter->setResponseStatus(
new ForbiddenResponse(ServiceTemplateException::deleteNotAllowed())
);
return;
}
if (($serviceTemplate = $this->readRepository->findById($serviceTemplateId)) === null) {
$this->error('Service template not found', ['service_template_id' => $serviceTemplateId]);
$presenter->setResponseStatus(new NotFoundResponse('Service template'));
return;
}
if ($serviceTemplate->isLocked()) {
$this->error(
'The service template is locked and cannot be delete',
['service_template_id' => $serviceTemplateId]
);
$presenter->setResponseStatus(
new ErrorResponse(
ServiceTemplateException::cannotBeDelete($serviceTemplate->getName())->getMessage()
)
);
return;
}
if ($this->writeVaultRepository->isVaultConfigured()) {
$this->retrieveServiceUuidFromVault($serviceTemplateId);
if ($this->uuid !== null) {
$this->writeVaultRepository->delete($this->uuid);
}
}
$this->writeRepository->deleteById($serviceTemplateId);
$presenter->setResponseStatus(new NoContentResponse());
$this->info(
'Service template deleted',
[
'service_template_id' => $serviceTemplateId,
'user_id' => $this->user->getId(),
]
);
} catch (\Throwable $ex) {
$presenter->setResponseStatus(new ErrorResponse(ServiceTemplateException::errorWhileDeleting($ex)));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
}
}
/**
* @param int $serviceTemplateId
*
* @throws \Throwable
*/
private function retrieveServiceUuidFromVault(int $serviceTemplateId): void
{
$macros = $this->readServiceMacroRepository->findByServiceIds($serviceTemplateId);
foreach ($macros as $macro) {
if (
$macro->isPassword() === true
&& null !== ($this->uuid = $this->getUuidFromPath($macro->getValue()))
) {
break;
}
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Application/UseCase/FindServiceTemplates/FindServiceTemplates.php | centreon/src/Core/ServiceTemplate/Application/UseCase/FindServiceTemplates/FindServiceTemplates.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Application\UseCase\FindServiceTemplates;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Infrastructure\RequestParameters\RequestParametersTranslatorException;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\ServiceTemplate\Application\Exception\ServiceTemplateException;
use Core\ServiceTemplate\Application\Repository\ReadServiceTemplateRepositoryInterface;
use Core\ServiceTemplate\Domain\Model\ServiceTemplate;
final class FindServiceTemplates
{
use LoggerTrait;
public function __construct(
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly ReadServiceTemplateRepositoryInterface $repository,
private readonly RequestParametersInterface $requestParameters,
private readonly ContactInterface $user,
) {
}
/**
* @param FindServiceTemplatesPresenterInterface $presenter
*/
public function __invoke(FindServiceTemplatesPresenterInterface $presenter): void
{
try {
if (
! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ)
&& ! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE)
) {
$this->error(
"User doesn't have sufficient rights to see service templates",
['user_id' => $this->user->getId()]
);
$presenter->presentResponse(
new ForbiddenResponse(ServiceTemplateException::accessNotAllowed())
);
return;
}
if ($this->user->isAdmin()) {
$serviceTemplates = $this->repository->findByRequestParameter($this->requestParameters);
} else {
$accessGroups = $this->readAccessGroupRepository->findByContact($this->user);
$serviceTemplates = $this->repository->findByRequestParametersAndAccessGroups(
$this->requestParameters,
$accessGroups
);
}
$presenter->presentResponse($this->createResponse($serviceTemplates));
} catch (RequestParametersTranslatorException $ex) {
$presenter->presentResponse(new ErrorResponse($ex->getMessage()));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (\Throwable $ex) {
$presenter->presentResponse(new ErrorResponse(ServiceTemplateException::errorWhileSearching($ex)));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
}
}
/**
* @param ServiceTemplate[] $serviceTemplates
*
* @return FindServiceTemplateResponse
*/
private function createResponse(array $serviceTemplates): FindServiceTemplateResponse
{
$response = new FindServiceTemplateResponse();
foreach ($serviceTemplates as $serviceTemplate) {
$dto = new ServiceTemplateDto();
$dto->id = $serviceTemplate->getId();
$dto->name = $serviceTemplate->getName();
$dto->alias = $serviceTemplate->getAlias();
$dto->comment = $serviceTemplate->getComment();
$dto->acknowledgementTimeout = $serviceTemplate->getAcknowledgementTimeout();
$dto->actionUrl = $serviceTemplate->getActionUrl();
$dto->isContactAdditiveInheritance = $serviceTemplate->isContactAdditiveInheritance();
$dto->isContactGroupAdditiveInheritance = $serviceTemplate->isContactGroupAdditiveInheritance();
$dto->commandArguments = $serviceTemplate->getCommandArguments();
$dto->commandId = $serviceTemplate->getCommandId();
$dto->checkTimePeriodId = $serviceTemplate->getCheckTimePeriodId();
$dto->eventHandlerId = $serviceTemplate->getEventHandlerId();
$dto->eventHandlerArguments = $serviceTemplate->getEventHandlerArguments();
$dto->firstNotificationDelay = $serviceTemplate->getFirstNotificationDelay();
$dto->freshnessThreshold = $serviceTemplate->getFreshnessThreshold();
$dto->graphTemplateId = $serviceTemplate->getGraphTemplateId();
$dto->flapDetectionEnabled = $serviceTemplate->getFlapDetectionEnabled();
$dto->lowFlapThreshold = $serviceTemplate->getLowFlapThreshold();
$dto->highFlapThreshold = $serviceTemplate->getHighFlapThreshold();
$dto->iconId = $serviceTemplate->getIconId();
$dto->iconAlternativeText = $serviceTemplate->getIconAlternativeText();
$dto->isLocked = $serviceTemplate->isLocked();
$dto->activeChecks = $serviceTemplate->getActiveChecks();
$dto->eventHandlerEnabled = $serviceTemplate->getEventHandlerEnabled();
$dto->checkFreshness = $serviceTemplate->getCheckFreshness();
$dto->notificationsEnabled = $serviceTemplate->getNotificationsEnabled();
$dto->passiveCheck = $serviceTemplate->getPassiveCheck();
$dto->volatility = $serviceTemplate->getVolatility();
$dto->maxCheckAttempts = $serviceTemplate->getMaxCheckAttempts();
$dto->normalCheckInterval = $serviceTemplate->getNormalCheckInterval();
$dto->note = $serviceTemplate->getNote();
$dto->noteUrl = $serviceTemplate->getNoteUrl();
$dto->notificationInterval = $serviceTemplate->getNotificationInterval();
$dto->notificationTimePeriodId = $serviceTemplate->getNotificationTimePeriodId();
$dto->notificationTypes = $serviceTemplate->getNotificationTypes();
$dto->recoveryNotificationDelay = $serviceTemplate->getRecoveryNotificationDelay();
$dto->retryCheckInterval = $serviceTemplate->getRetryCheckInterval();
$dto->serviceTemplateId = $serviceTemplate->getServiceTemplateParentId();
$dto->severityId = $serviceTemplate->getSeverityId();
$dto->hostTemplateIds = $serviceTemplate->getHostTemplateIds();
$response->serviceTemplates[] = $dto;
}
return $response;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Application/UseCase/FindServiceTemplates/ServiceTemplateDto.php | centreon/src/Core/ServiceTemplate/Application/UseCase/FindServiceTemplates/ServiceTemplateDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Application\UseCase\FindServiceTemplates;
use Core\Common\Domain\YesNoDefault;
use Core\ServiceTemplate\Domain\Model\NotificationType;
final class ServiceTemplateDto
{
public int $id = 0;
public string $name = '';
public string $alias = '';
public string|null $comment = null;
public int|null $acknowledgementTimeout = null;
public string|null $actionUrl = null;
public bool $isContactAdditiveInheritance = false;
public bool $isContactGroupAdditiveInheritance = false;
public int|null $commandId = null;
/** @var string[] */
public array $commandArguments = [];
public int|null $eventHandlerId = null;
/** @var string[] */
public array $eventHandlerArguments = [];
public int|null $checkTimePeriodId = null;
public int|null $firstNotificationDelay = null;
public int|null $freshnessThreshold = null;
public int|null $graphTemplateId = null;
public int|null $lowFlapThreshold = null;
public int|null $highFlapThreshold = null;
public int|null $iconId = null;
public string|null $iconAlternativeText = null;
public bool $isLocked = false;
public YesNoDefault $activeChecks = YesNoDefault::Default;
public YesNoDefault $eventHandlerEnabled = YesNoDefault::Default;
public YesNoDefault $flapDetectionEnabled = YesNoDefault::Default;
public YesNoDefault $checkFreshness = YesNoDefault::Default;
public YesNoDefault $notificationsEnabled = YesNoDefault::Default;
public YesNoDefault $passiveCheck = YesNoDefault::Default;
public YesNoDefault $volatility = YesNoDefault::Default;
public int|null $maxCheckAttempts = null;
public int|null $normalCheckInterval = null;
public string|null $note = null;
public string|null $noteUrl = null;
public int|null $notificationInterval = null;
public int|null $notificationTimePeriodId = null;
/** @var NotificationType[] */
public array $notificationTypes = [];
/** @var list<int> */
public array $hostTemplateIds = [];
public int|null $recoveryNotificationDelay = null;
public int|null $retryCheckInterval = null;
public int|null $serviceTemplateId = null;
public int|null $severityId = 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/ServiceTemplate/Application/UseCase/FindServiceTemplates/FindServiceTemplatesPresenterInterface.php | centreon/src/Core/ServiceTemplate/Application/UseCase/FindServiceTemplates/FindServiceTemplatesPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Application\UseCase\FindServiceTemplates;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface FindServiceTemplatesPresenterInterface
{
public function presentResponse(FindServiceTemplateResponse|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/ServiceTemplate/Application/UseCase/FindServiceTemplates/FindServiceTemplateResponse.php | centreon/src/Core/ServiceTemplate/Application/UseCase/FindServiceTemplates/FindServiceTemplateResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Application\UseCase\FindServiceTemplates;
final class FindServiceTemplateResponse
{
/** @var ServiceTemplateDto[] */
public array $serviceTemplates = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Application/Exception/ServiceTemplateException.php | centreon/src/Core/ServiceTemplate/Application/Exception/ServiceTemplateException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Application\Exception;
class ServiceTemplateException extends \Exception
{
public const CODE_CONFLICT = 1;
/**
* @return self
*/
public static function accessNotAllowed(): self
{
return new self(_('You are not allowed to access service templates'));
}
/**
* @return self
*/
public static function addNotAllowed(): self
{
return new self(_('You are not allowed to add a service template'));
}
/**
* @param string $serviceTemplateName
*
* @return self
*/
public static function cannotBeDelete(string $serviceTemplateName): self
{
return new self(
sprintf(
_('The service template \'%s\' is locked and cannot be deleted'),
$serviceTemplateName
)
);
}
/**
* @return self
*/
public static function deleteNotAllowed(): self
{
return new self(_('You are not allowed to delete a service template'));
}
/**
* @param \Throwable $ex
*
* @return self
*/
public static function errorWhileAdding(\Throwable $ex): self
{
return new self(_('Error while adding the service template'), 0, $ex);
}
/**
* @param \Throwable $ex
*
* @return self
*/
public static function errorWhileDeleting(\Throwable $ex): self
{
return new self(_('Error while deleting the service template'), 0, $ex);
}
/**
* @return self
*/
public static function errorWhileRetrieving(): self
{
return new self(_('Error while retrieving a service template'));
}
/**
* @return self
*/
public static function errorWhileUpdating(): self
{
return new self(_('Error while updating a service template'));
}
/**
* @param \Throwable $ex
*
* @return self
*/
public static function errorWhileSearching(\Throwable $ex): self
{
return new self(_('Error while searching for service templates'), 0, $ex);
}
/**
* @param string $propertyName
* @param int $propertyValue
*
* @return self
*/
public static function idDoesNotExist(string $propertyName, int $propertyValue): self
{
return new self(
sprintf(
_("The %s with value '%d' does not exist"),
$propertyName,
$propertyValue
),
self::CODE_CONFLICT
);
}
/**
* @param string $propertyName
* @param list<int> $propertyValue
*
* @return self
*/
public static function idsDoNotExist(string $propertyName, array $propertyValue): self
{
return new self(
sprintf(
_('The %s does not exist with id(s) \'%s\''),
$propertyName,
implode(',', $propertyValue)
),
self::CODE_CONFLICT
);
}
/**
* @param string $serviceTemplateName
*
* @return self
*/
public static function nameAlreadyExists(string $serviceTemplateName): self
{
return new self(
sprintf(
_('The service template name \'%s\' already exists'),
$serviceTemplateName
)
);
}
/**
* @return self
*/
public static function updateNotAllowed(): self
{
return new self(_('You are not allowed to update a service template'));
}
/**
* @return self
*/
public static function invalidServiceGroupAssociation(): self
{
return new self(
_('Host template required in service group association is not linked to service template'),
self::CODE_CONFLICT
);
}
/**
* @return self
*/
public static function circularTemplateInheritance(): self
{
return new self(_('Circular inheritance not allowed'), 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/ServiceTemplate/Application/Repository/ReadServiceTemplateRepositoryInterface.php | centreon/src/Core/ServiceTemplate/Application/Repository/ReadServiceTemplateRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Application\Repository;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Common\Domain\TrimmedString;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Core\ServiceTemplate\Domain\Model\ServiceTemplate;
use Core\ServiceTemplate\Domain\Model\ServiceTemplateInheritance;
interface ReadServiceTemplateRepositoryInterface
{
/**
* Find one service template.
*
* @param int $serviceTemplateId
*
* @throws \Throwable
*
* @return ServiceTemplate|null
*/
public function findById(int $serviceTemplateId): ?ServiceTemplate;
/**
* Find one service template by id and access group ids.
*
* @param int $serviceTemplateId
* @param AccessGroup[] $accessGroups
*
* @return ServiceTemplate|null
*/
public function findByIdAndAccessGroups(int $serviceTemplateId, array $accessGroups): ?ServiceTemplate;
/**
* Find all service templates.
*
* @param RequestParametersInterface $requestParameters
*
* @throws \Throwable
*
* @return ServiceTemplate[]
*/
public function findByRequestParameter(RequestParametersInterface $requestParameters): array;
/**
* Find all service tempalte by request parameters and access groups.
*
* @param RequestParametersInterface $requestParameters
* @param AccessGroup[] $accessGroups
*
* @throws \Throwable
*
* @return ServiceTemplate[]
*/
public function findByRequestParametersAndAccessGroups(
RequestParametersInterface $requestParameters,
array $accessGroups,
): array;
/**
* Indicates whether the service template already exists.
*
* @param int $serviceTemplateId
*
* @throws \Throwable
*
* @return bool
*/
public function exists(int $serviceTemplateId): bool;
/**
* Indicates whether the service template name already exists.
*
* @param TrimmedString $serviceTemplateName
*
* @throws \Throwable
*
* @return bool
*/
public function existsByName(TrimmedString $serviceTemplateName): bool;
/**
* Retrieves all service inheritances from a service template.
*
* @param int $serviceTemplateId
*
* @throws \Throwable
*
* @return ServiceTemplateInheritance[]
*/
public function findParents(int $serviceTemplateId): array;
/**
* Find service templates associated to given host id.
*
* @param int $hostId
*
* @throws \Throwable
*
* @return ServiceTemplate[]
*/
public function findByHostId(int $hostId): array;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Application/Repository/WriteServiceTemplateRepositoryInterface.php | centreon/src/Core/ServiceTemplate/Application/Repository/WriteServiceTemplateRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Application\Repository;
use Core\ServiceTemplate\Domain\Model\NewServiceTemplate;
use Core\ServiceTemplate\Domain\Model\ServiceTemplate;
interface WriteServiceTemplateRepositoryInterface
{
/**
* Delete a service template by ID.
*
* @param int $serviceTemplateId
*
* @throws \Throwable
*/
public function deleteById(int $serviceTemplateId): void;
/**
* Add a new service template.
*
* @param NewServiceTemplate $newServiceTemplate
*
* @throws \Throwable
*
* @return int
*/
public function add(NewServiceTemplate $newServiceTemplate): int;
/**
* Link the service template to host templates.
*
* @param int $serviceTemplateId
* @param list<int> $hostTemplateIds
*
* @throws \Throwable
*/
public function linkToHosts(int $serviceTemplateId, array $hostTemplateIds): void;
/**
* Unlink all host templates from the service template.
*
* @param int $serviceTemplateId
*
* @throws \Throwable
*/
public function unlinkHosts(int $serviceTemplateId): void;
/**
* Update a service template.
*
* @param ServiceTemplate $serviceTemplate
*
* @throws \Throwable
*/
public function update(ServiceTemplate $serviceTemplate): 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/ServiceTemplate/Domain/Model/NewServiceTemplate.php | centreon/src/Core/ServiceTemplate/Domain/Model/NewServiceTemplate.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Common\Domain\YesNoDefault;
use Core\MonitoringServer\Model\MonitoringServer;
class NewServiceTemplate
{
public const MAX_NAME_LENGTH = 255;
public const MAX_ALIAS_LENGTH = 255;
public const MAX_COMMENT_LENGTH = 65535;
public const MAX_NOTES_LENGTH = 65535;
public const MAX_NOTES_URL_LENGTH = 65535;
public const MAX_ACTION_URL_LENGTH = 65535;
public const MAX_ICON_ALT_LENGTH = 200;
protected string $className;
private string $name;
private string $alias;
/** @var string[] */
private array $commandArguments = [];
/** @var string[] */
private array $eventHandlerArguments = [];
/** @var NotificationType[] */
private array $notificationTypes = [];
/** @var list<int> */
private array $hostTemplateIds = [];
private bool $isContactAdditiveInheritance = false;
private bool $isContactGroupAdditiveInheritance = false;
private bool $isLocked = false;
private YesNoDefault $activeChecks = YesNoDefault::Default;
private YesNoDefault $passiveCheck = YesNoDefault::Default;
private YesNoDefault $volatility = YesNoDefault::Default;
private YesNoDefault $checkFreshness = YesNoDefault::Default;
private YesNoDefault $eventHandlerEnabled = YesNoDefault::Default;
private YesNoDefault $flapDetectionEnabled = YesNoDefault::Default;
private YesNoDefault $notificationsEnabled = YesNoDefault::Default;
private ?string $comment = null;
private ?string $note = null;
private ?string $noteUrl = null;
private ?string $actionUrl = null;
private ?string $iconAlternativeText = null;
private ?int $graphTemplateId = null;
private ?int $serviceTemplateParentId = null;
private ?int $commandId = null;
private ?int $eventHandlerId = null;
private ?int $notificationTimePeriodId = null;
private ?int $checkTimePeriodId = null;
private ?int $iconId = null;
private ?int $severityId = null;
private ?int $maxCheckAttempts = null;
private ?int $normalCheckInterval = null;
private ?int $retryCheckInterval = null;
private ?int $freshnessThreshold = null;
private ?int $lowFlapThreshold = null;
private ?int $highFlapThreshold = null;
private ?int $notificationInterval = null;
private ?int $recoveryNotificationDelay = null;
private ?int $firstNotificationDelay = null;
private ?int $acknowledgementTimeout = null;
/**
* @param string $name
* @param string $alias
*
* @throws AssertionFailedException
*/
public function __construct(
string $name,
string $alias,
) {
$this->className = (new \ReflectionClass($this))->getShortName();
$this->setName($name);
$this->setAlias($alias);
}
/**
* @param string $name
*
* @throws AssertionFailedException
*/
public function setName(string $name): void
{
$name = ServiceTemplate::formatName($name) ?? throw AssertionException::notNull($this->className . '::name');
Assertion::notEmptyString($name, $this->className . '::name');
Assertion::maxLength($name, self::MAX_NAME_LENGTH, $this->className . '::name');
Assertion::unauthorizedCharacters(
$name,
MonitoringServer::ILLEGAL_CHARACTERS,
$this->className . '::name'
);
$this->name = $name;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @param string $alias
*
* @throws AssertionFailedException
*/
public function setAlias(string $alias): void
{
$alias = ServiceTemplate::formatName($alias) ?? throw AssertionException::notNull($this->className . '::alias');
Assertion::notEmptyString($alias, $this->className . '::alias');
Assertion::maxLength($alias, self::MAX_ALIAS_LENGTH, $this->className . '::alias');
Assertion::unauthorizedCharacters(
$alias,
MonitoringServer::ILLEGAL_CHARACTERS,
$this->className . '::alias'
);
$this->alias = $alias;
}
/**
* @return string
*/
public function getAlias(): string
{
return $this->alias;
}
/**
* @param string $commandArgument
*/
public function addCommandArgument(string $commandArgument): void
{
$this->commandArguments[] = $commandArgument;
}
public function resetCommandArguments(): void
{
$this->commandArguments = [];
}
/**
* @return list<string>
*/
public function getCommandArguments(): array
{
return $this->commandArguments;
}
/**
* @param string $eventHandlerArgument
*/
public function addEventHandlerArgument(string $eventHandlerArgument): void
{
$this->eventHandlerArguments[] = $eventHandlerArgument;
}
public function resetEventHandlerArguments(): void
{
$this->eventHandlerArguments = [];
}
/**
* @return list<string>
*/
public function getEventHandlerArguments(): array
{
return $this->eventHandlerArguments;
}
/**
* @param NotificationType $notificationType
*/
public function addNotificationType(NotificationType $notificationType): void
{
$this->notificationTypes[] = $notificationType;
}
public function resetNotificationTypes(): void
{
$this->notificationTypes = [];
}
/**
* @return NotificationType[]
*/
public function getNotificationTypes(): array
{
return $this->notificationTypes;
}
/**
* @param bool $isContactAdditiveInheritance
*/
public function setContactAdditiveInheritance(bool $isContactAdditiveInheritance): void
{
$this->isContactAdditiveInheritance = $isContactAdditiveInheritance;
}
/**
* @return bool
*/
public function isContactAdditiveInheritance(): bool
{
return $this->isContactAdditiveInheritance;
}
/**
* @param bool $isContactGroupAdditiveInheritance
*/
public function setContactGroupAdditiveInheritance(bool $isContactGroupAdditiveInheritance): void
{
$this->isContactGroupAdditiveInheritance = $isContactGroupAdditiveInheritance;
}
/**
* @return bool
*/
public function isContactGroupAdditiveInheritance(): bool
{
return $this->isContactGroupAdditiveInheritance;
}
/**
* @param bool $isLocked
*/
public function setLocked(bool $isLocked): void
{
$this->isLocked = $isLocked;
}
/**
* @return bool
*/
public function isLocked(): bool
{
return $this->isLocked;
}
/**
* @param YesNoDefault $activeChecks
*/
public function setActiveChecks(YesNoDefault $activeChecks): void
{
$this->activeChecks = $activeChecks;
}
/**
* @return YesNoDefault
*/
public function getActiveChecks(): YesNoDefault
{
return $this->activeChecks;
}
/**
* @param YesNoDefault $passiveCheck
*/
public function setPassiveCheck(YesNoDefault $passiveCheck): void
{
$this->passiveCheck = $passiveCheck;
}
/**
* @return YesNoDefault
*/
public function getPassiveCheck(): YesNoDefault
{
return $this->passiveCheck;
}
/**
* @param YesNoDefault $volatility
*/
public function setVolatility(YesNoDefault $volatility): void
{
$this->volatility = $volatility;
}
/**
* @return YesNoDefault
*/
public function getVolatility(): YesNoDefault
{
return $this->volatility;
}
/**
* @param YesNoDefault $checkFreshness
*/
public function setCheckFreshness(YesNoDefault $checkFreshness): void
{
$this->checkFreshness = $checkFreshness;
}
/**
* @return YesNoDefault
*/
public function getCheckFreshness(): YesNoDefault
{
return $this->checkFreshness;
}
/**
* @param YesNoDefault $eventHandlerEnabled
*/
public function setEventHandlerEnabled(YesNoDefault $eventHandlerEnabled): void
{
$this->eventHandlerEnabled = $eventHandlerEnabled;
}
/**
* @return YesNoDefault
*/
public function getEventHandlerEnabled(): YesNoDefault
{
return $this->eventHandlerEnabled;
}
/**
* @param YesNoDefault $flapDetectionEnabled
*/
public function setFlapDetectionEnabled(YesNoDefault $flapDetectionEnabled): void
{
$this->flapDetectionEnabled = $flapDetectionEnabled;
}
/**
* @return YesNoDefault
*/
public function getFlapDetectionEnabled(): YesNoDefault
{
return $this->flapDetectionEnabled;
}
/**
* @param YesNoDefault $notificationsEnabled
*/
public function setNotificationsEnabled(YesNoDefault $notificationsEnabled): void
{
$this->notificationsEnabled = $notificationsEnabled;
}
/**
* @return YesNoDefault
*/
public function getNotificationsEnabled(): YesNoDefault
{
return $this->notificationsEnabled;
}
/**
* @param string|null $comment
*
* @throws AssertionFailedException
*/
public function setComment(?string $comment): void
{
if ($comment !== null) {
$comment = trim($comment);
Assertion::notEmptyString($comment, $this->className . '::comment');
Assertion::maxLength($comment, self::MAX_COMMENT_LENGTH, $this->className . '::comment');
}
$this->comment = $comment;
}
/**
* @return string|null
*/
public function getComment(): ?string
{
return $this->comment;
}
/**
* @param string|null $note
*
* @throws AssertionFailedException
*/
public function setNote(?string $note): void
{
if ($note !== null) {
$note = trim($note);
Assertion::notEmptyString($note, $this->className . '::note');
Assertion::maxLength($note, self::MAX_NOTES_LENGTH, $this->className . '::note');
}
$this->note = $note;
}
/**
* @return string|null
*/
public function getNote(): ?string
{
return $this->note;
}
/**
* @param string|null $noteUrl
*
* @throws AssertionFailedException
*/
public function setNoteUrl(?string $noteUrl): void
{
if ($noteUrl !== null) {
$noteUrl = trim($noteUrl);
Assertion::notEmptyString($noteUrl, $this->className . '::noteUrl');
Assertion::maxLength($noteUrl, self::MAX_NOTES_URL_LENGTH, $this->className . '::noteUrl');
}
$this->noteUrl = $noteUrl;
}
/**
* @return string|null
*/
public function getNoteUrl(): ?string
{
return $this->noteUrl;
}
/**
* @param string|null $actionUrl
*
* @throws AssertionFailedException
*/
public function setActionUrl(?string $actionUrl): void
{
if ($actionUrl !== null) {
$actionUrl = trim($actionUrl);
Assertion::notEmptyString($actionUrl, $this->className . '::actionUrl');
Assertion::maxLength($actionUrl, self::MAX_ACTION_URL_LENGTH, $this->className . '::actionUrl');
}
$this->actionUrl = $actionUrl;
}
/**
* @return string|null
*/
public function getActionUrl(): ?string
{
return $this->actionUrl;
}
/**
* @param string|null $iconAlternativeText
*
* @throws AssertionFailedException
*/
public function setIconAlternativeText(?string $iconAlternativeText): void
{
if ($iconAlternativeText !== null) {
$iconAlternativeText = trim($iconAlternativeText);
Assertion::notEmptyString($iconAlternativeText, $this->className . '::iconAlternativeText');
Assertion::maxLength(
$iconAlternativeText,
self::MAX_ICON_ALT_LENGTH,
$this->className . '::iconAlternativeText'
);
}
$this->iconAlternativeText = $iconAlternativeText;
}
/**
* @return string|null
*/
public function getIconAlternativeText(): ?string
{
return $this->iconAlternativeText;
}
/**
* @param int|null $graphTemplateId
*
* @throws AssertionFailedException
*/
public function setGraphTemplateId(?int $graphTemplateId): void
{
if ($graphTemplateId !== null) {
Assertion::positiveInt($graphTemplateId, $this->className . '::graphTemplateId');
}
$this->graphTemplateId = $graphTemplateId;
}
/**
* @return int|null
*/
public function getGraphTemplateId(): ?int
{
return $this->graphTemplateId;
}
/**
* @param int|null $serviceTemplateParentId
*
* @throws AssertionFailedException
*/
public function setServiceTemplateParentId(?int $serviceTemplateParentId): void
{
if ($serviceTemplateParentId !== null) {
Assertion::positiveInt($serviceTemplateParentId, $this->className . '::serviceTemplateParentId');
}
$this->serviceTemplateParentId = $serviceTemplateParentId;
}
/**
* @return int|null
*/
public function getServiceTemplateParentId(): ?int
{
return $this->serviceTemplateParentId;
}
/**
* @param int|null $commandId
*
* @throws AssertionFailedException
*/
public function setCommandId(?int $commandId): void
{
if ($commandId !== null) {
Assertion::positiveInt($commandId, $this->className . '::commandId');
}
$this->commandId = $commandId;
}
/**
* @return int|null
*/
public function getCommandId(): ?int
{
return $this->commandId;
}
/**
* @param int|null $eventHandlerId
*
* @throws AssertionFailedException
*/
public function setEventHandlerId(?int $eventHandlerId): void
{
if ($eventHandlerId !== null) {
Assertion::positiveInt($eventHandlerId, $this->className . '::eventHandlerId');
}
$this->eventHandlerId = $eventHandlerId;
}
/**
* @return int|null
*/
public function getEventHandlerId(): ?int
{
return $this->eventHandlerId;
}
/**
* @param int|null $notificationTimePeriodId
*
* @throws AssertionFailedException
*/
public function setNotificationTimePeriodId(?int $notificationTimePeriodId): void
{
if ($notificationTimePeriodId !== null) {
Assertion::positiveInt($notificationTimePeriodId, $this->className . '::notificationTimePeriodId');
}
$this->notificationTimePeriodId = $notificationTimePeriodId;
}
/**
* @return int|null
*/
public function getNotificationTimePeriodId(): ?int
{
return $this->notificationTimePeriodId;
}
/**
* @param int|null $checkTimePeriodId
*
* @throws AssertionFailedException
*/
public function setCheckTimePeriodId(?int $checkTimePeriodId): void
{
if ($checkTimePeriodId !== null) {
Assertion::positiveInt($checkTimePeriodId, $this->className . '::checkTimePeriodId');
}
$this->checkTimePeriodId = $checkTimePeriodId;
}
/**
* @return int|null
*/
public function getCheckTimePeriodId(): ?int
{
return $this->checkTimePeriodId;
}
/**
* @param int|null $iconId
*
* @throws AssertionFailedException
*/
public function setIconId(?int $iconId): void
{
if ($iconId !== null) {
Assertion::positiveInt($iconId, $this->className . '::iconId');
}
$this->iconId = $iconId;
}
/**
* @return int|null
*/
public function getIconId(): ?int
{
return $this->iconId;
}
/**
* @param int|null $severityId
*
* @throws AssertionFailedException
*/
public function setSeverityId(?int $severityId): void
{
if ($severityId !== null) {
Assertion::positiveInt($severityId, $this->className . '::severityId');
}
$this->severityId = $severityId;
}
/**
* @return int|null
*/
public function getSeverityId(): ?int
{
return $this->severityId;
}
/**
* @param int|null $maxCheckAttempts
*
* @throws AssertionFailedException
*/
public function setMaxCheckAttempts(?int $maxCheckAttempts): void
{
if ($maxCheckAttempts !== null) {
Assertion::min($maxCheckAttempts, 0, $this->className . '::maxCheckAttempts');
}
$this->maxCheckAttempts = $maxCheckAttempts;
}
/**
* @return int|null
*/
public function getMaxCheckAttempts(): ?int
{
return $this->maxCheckAttempts;
}
/**
* @param int|null $normalCheckInterval
*
* @throws AssertionFailedException
*/
public function setNormalCheckInterval(?int $normalCheckInterval): void
{
if ($normalCheckInterval !== null) {
Assertion::min($normalCheckInterval, 0, $this->className . '::normalCheckInterval');
}
$this->normalCheckInterval = $normalCheckInterval;
}
/**
* @return int|null
*/
public function getNormalCheckInterval(): ?int
{
return $this->normalCheckInterval;
}
/**
* @param int|null $retryCheckInterval
*
* @throws AssertionFailedException
*/
public function setRetryCheckInterval(?int $retryCheckInterval): void
{
if ($retryCheckInterval !== null) {
Assertion::min($retryCheckInterval, 0, $this->className . '::retryCheckInterval');
}
$this->retryCheckInterval = $retryCheckInterval;
}
/**
* @return int|null
*/
public function getRetryCheckInterval(): ?int
{
return $this->retryCheckInterval;
}
/**
* @param int|null $freshnessThreshold
*
* @throws AssertionFailedException
*/
public function setFreshnessThreshold(?int $freshnessThreshold): void
{
if ($freshnessThreshold !== null) {
Assertion::min($freshnessThreshold, 0, $this->className . '::freshnessThreshold');
}
$this->freshnessThreshold = $freshnessThreshold;
}
/**
* @return int|null
*/
public function getFreshnessThreshold(): ?int
{
return $this->freshnessThreshold;
}
/**
* @param int|null $lowFlapThreshold
*
* @throws AssertionFailedException
*/
public function setLowFlapThreshold(?int $lowFlapThreshold): void
{
if ($lowFlapThreshold !== null) {
Assertion::min($lowFlapThreshold, 0, $this->className . '::lowFlapThreshold');
}
$this->lowFlapThreshold = $lowFlapThreshold;
}
/**
* @return int|null
*/
public function getLowFlapThreshold(): ?int
{
return $this->lowFlapThreshold;
}
/**
* @param int|null $highFlapThreshold
*
* @throws AssertionFailedException
*/
public function setHighFlapThreshold(?int $highFlapThreshold): void
{
if ($highFlapThreshold !== null) {
Assertion::min($highFlapThreshold, 0, $this->className . '::highFlapThreshold');
}
$this->highFlapThreshold = $highFlapThreshold;
}
/**
* @return int|null
*/
public function getHighFlapThreshold(): ?int
{
return $this->highFlapThreshold;
}
/**
* @param int|null $notificationInterval
*
* @throws AssertionFailedException
*/
public function setNotificationInterval(?int $notificationInterval): void
{
if ($notificationInterval !== null) {
Assertion::min($notificationInterval, 0, $this->className . '::notificationInterval');
}
$this->notificationInterval = $notificationInterval;
}
/**
* @return int|null
*/
public function getNotificationInterval(): ?int
{
return $this->notificationInterval;
}
/**
* @param int|null $recoveryNotificationDelay
*
* @throws AssertionFailedException
*/
public function setRecoveryNotificationDelay(?int $recoveryNotificationDelay): void
{
if ($recoveryNotificationDelay !== null) {
Assertion::min($recoveryNotificationDelay, 0, $this->className . '::recoveryNotificationDelay');
}
$this->recoveryNotificationDelay = $recoveryNotificationDelay;
}
/**
* @return int|null
*/
public function getRecoveryNotificationDelay(): ?int
{
return $this->recoveryNotificationDelay;
}
/**
* @param int|null $firstNotificationDelay
*
* @throws AssertionFailedException
*/
public function setFirstNotificationDelay(?int $firstNotificationDelay): void
{
if ($firstNotificationDelay !== null) {
Assertion::min($firstNotificationDelay, 0, $this->className . '::firstNotificationDelay');
}
$this->firstNotificationDelay = $firstNotificationDelay;
}
/**
* @return int|null
*/
public function getFirstNotificationDelay(): ?int
{
return $this->firstNotificationDelay;
}
/**
* @param int|null $acknowledgementTimeout
*
* @throws AssertionFailedException
*/
public function setAcknowledgementTimeout(?int $acknowledgementTimeout): void
{
if ($acknowledgementTimeout !== null) {
Assertion::min($acknowledgementTimeout, 0, $this->className . '::acknowledgementTimeout');
}
$this->acknowledgementTimeout = $acknowledgementTimeout;
}
/**
* @return int|null
*/
public function getAcknowledgementTimeout(): ?int
{
return $this->acknowledgementTimeout;
}
/**
* @param list<int> $hostTemplateIds
*
* @throws AssertionFailedException
*/
public function setHostTemplateIds(array $hostTemplateIds): void
{
foreach ($hostTemplateIds as $hostTemplateId) {
Assertion::positiveInt($hostTemplateId, $this->className . '::hostTemplateIds');
}
$this->hostTemplateIds = $hostTemplateIds;
}
/**
* @return list<int>
*/
public function getHostTemplateIds(): array
{
return $this->hostTemplateIds;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Domain/Model/NotificationType.php | centreon/src/Core/ServiceTemplate/Domain/Model/NotificationType.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Domain\Model;
enum NotificationType
{
case Warning;
case Unknown;
case Critical;
case Recovery;
case Flapping;
case DowntimeScheduled;
case None;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Domain/Model/ServiceTemplateInheritance.php | centreon/src/Core/ServiceTemplate/Domain/Model/ServiceTemplateInheritance.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
class ServiceTemplateInheritance
{
/**
* @param int $parentId
* @param int $childId
*
* @throws AssertionFailedException
*/
public function __construct(
private readonly int $parentId,
private readonly int $childId,
) {
Assertion::positiveInt($parentId, 'ParentServiceTemplate::parentID');
Assertion::positiveInt($childId, 'ParentServiceTemplate::childId');
}
/**
* @return int
*/
public function getParentId(): int
{
return $this->parentId;
}
/**
* @return int
*/
public function getChildId(): int
{
return $this->childId;
}
/**
* Return an ordered line of inheritance for a service template.
* (This is a recursive method).
*
* @param int $serviceId
* @param ServiceTemplateInheritance[] $parents
*
* @return int[]
*/
public static function createInheritanceLine(int $serviceId, array $parents): array
{
foreach ($parents as $index => $parent) {
if ($parent->getChildId() === $serviceId) {
unset($parents[$index]);
return array_merge(
[$parent->getParentId()],
self::createInheritanceLine($parent->getParentId(), $parents)
);
}
}
return [];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Domain/Model/ServiceTemplate.php | centreon/src/Core/ServiceTemplate/Domain/Model/ServiceTemplate.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Core\Common\Domain\YesNoDefault;
class ServiceTemplate extends NewServiceTemplate
{
public const MAX_NAME_LENGTH = NewServiceTemplate::MAX_NAME_LENGTH;
public const MAX_ALIAS_LENGTH = NewServiceTemplate::MAX_ALIAS_LENGTH;
public const MAX_COMMENT_LENGTH = NewServiceTemplate::MAX_COMMENT_LENGTH;
public const MAX_NOTES_LENGTH = NewServiceTemplate::MAX_NOTES_LENGTH;
public const MAX_NOTES_URL_LENGTH = NewServiceTemplate::MAX_NOTES_URL_LENGTH;
public const MAX_ACTION_URL_LENGTH = NewServiceTemplate::MAX_ACTION_URL_LENGTH;
public const MAX_ICON_ALT_LENGTH = NewServiceTemplate::MAX_ICON_ALT_LENGTH;
/**
* @param int $id
* @param string $name
* @param string $alias
* @param list<mixed> $commandArguments
* @param list<mixed> $eventHandlerArguments
* @param NotificationType[] $notificationTypes
* @param list<int> $hostTemplateIds
* @param bool $contactAdditiveInheritance
* @param bool $contactGroupAdditiveInheritance
* @param bool $isLocked
* @param YesNoDefault $activeChecks
* @param YesNoDefault $passiveCheck
* @param YesNoDefault $volatility
* @param YesNoDefault $checkFreshness
* @param YesNoDefault $eventHandlerEnabled
* @param YesNoDefault $flapDetectionEnabled
* @param YesNoDefault $notificationsEnabled
* @param string|null $comment
* @param string|null $note
* @param string|null $noteUrl
* @param string|null $actionUrl
* @param string|null $iconAlternativeText
* @param int|null $graphTemplateId
* @param int|null $serviceTemplateParentId
* @param int|null $commandId
* @param int|null $eventHandlerId
* @param int|null $notificationTimePeriodId
* @param int|null $checkTimePeriodId
* @param int|null $iconId
* @param int|null $severityId
* @param int|null $maxCheckAttempts
* @param int|null $normalCheckInterval
* @param int|null $retryCheckInterval
* @param int|null $freshnessThreshold
* @param int|null $lowFlapThreshold
* @param int|null $highFlapThreshold
* @param int|null $notificationInterval
* @param int|null $recoveryNotificationDelay
* @param int|null $firstNotificationDelay
* @param int|null $acknowledgementTimeout
*
* @throws AssertionFailedException
*/
public function __construct(
private readonly int $id,
string $name,
string $alias,
array $commandArguments = [],
array $eventHandlerArguments = [],
array $notificationTypes = [],
array $hostTemplateIds = [],
bool $contactAdditiveInheritance = false,
bool $contactGroupAdditiveInheritance = false,
bool $isLocked = false,
YesNoDefault $activeChecks = YesNoDefault::Default,
YesNoDefault $passiveCheck = YesNoDefault::Default,
YesNoDefault $volatility = YesNoDefault::Default,
YesNoDefault $checkFreshness = YesNoDefault::Default,
YesNoDefault $eventHandlerEnabled = YesNoDefault::Default,
YesNoDefault $flapDetectionEnabled = YesNoDefault::Default,
YesNoDefault $notificationsEnabled = YesNoDefault::Default,
?string $comment = null,
?string $note = null,
?string $noteUrl = null,
?string $actionUrl = null,
?string $iconAlternativeText = null,
?int $graphTemplateId = null,
?int $serviceTemplateParentId = null,
?int $commandId = null,
?int $eventHandlerId = null,
?int $notificationTimePeriodId = null,
?int $checkTimePeriodId = null,
?int $iconId = null,
?int $severityId = null,
?int $maxCheckAttempts = null,
?int $normalCheckInterval = null,
?int $retryCheckInterval = null,
?int $freshnessThreshold = null,
?int $lowFlapThreshold = null,
?int $highFlapThreshold = null,
?int $notificationInterval = null,
?int $recoveryNotificationDelay = null,
?int $firstNotificationDelay = null,
?int $acknowledgementTimeout = null,
) {
$this->className = (new \ReflectionClass($this))->getShortName();
Assertion::positiveInt($id, "{$this->className}::id");
parent::__construct($name, $alias);
$this->setComment($comment);
$this->setNote($note);
$this->setNoteUrl($noteUrl);
$this->setActionUrl($actionUrl);
$this->setIconAlternativeText($iconAlternativeText);
$this->setServiceTemplateParentId($serviceTemplateParentId);
$this->setCommandId($commandId);
$this->setEventHandlerId($eventHandlerId);
$this->setNotificationTimePeriodId($notificationTimePeriodId);
$this->setCheckTimePeriodId($checkTimePeriodId);
$this->setIconId($iconId);
$this->setGraphTemplateId($graphTemplateId);
$this->setSeverityId($severityId);
$this->setHostTemplateIds($hostTemplateIds);
$this->setMaxCheckAttempts($maxCheckAttempts);
$this->setNormalCheckInterval($normalCheckInterval);
$this->setRetryCheckInterval($retryCheckInterval);
$this->setFreshnessThreshold($freshnessThreshold);
$this->setNotificationInterval($notificationInterval);
$this->setRecoveryNotificationDelay($recoveryNotificationDelay);
$this->setFirstNotificationDelay($firstNotificationDelay);
$this->setAcknowledgementTimeout($acknowledgementTimeout);
$this->setLowFlapThreshold($lowFlapThreshold);
$this->setHighFlapThreshold($highFlapThreshold);
$this->setContactAdditiveInheritance($contactAdditiveInheritance);
$this->setContactGroupAdditiveInheritance($contactGroupAdditiveInheritance);
$this->setLocked($isLocked);
$this->setActiveChecks($activeChecks);
$this->setPassiveCheck($passiveCheck);
$this->setVolatility($volatility);
$this->setCheckFreshness($checkFreshness);
$this->setEventHandlerEnabled($eventHandlerEnabled);
$this->setFlapDetectionEnabled($flapDetectionEnabled);
$this->setNotificationsEnabled($notificationsEnabled);
foreach (self::stringifyArguments($commandArguments) as $commandArgument) {
$this->addCommandArgument($commandArgument);
}
foreach (self::stringifyArguments($eventHandlerArguments) as $eventHandlerArgument) {
$this->addEventHandlerArgument($eventHandlerArgument);
}
foreach ($notificationTypes as $type) {
Assertion::isInstanceOf($type, NotificationType::class, "{$this->className}::notificationTypes");
$this->addNotificationType($type);
}
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @param list<string> $eventHandlerArguments
*/
public function setEventHandlerArguments(array $eventHandlerArguments): void
{
$this->resetEventHandlerArguments();
foreach (self::stringifyArguments($eventHandlerArguments) as $eventHandlerArgument) {
$this->addEventHandlerArgument($eventHandlerArgument);
}
}
/**
* @param list<string> $commandArguments
*/
public function setCommandArguments(array $commandArguments): void
{
$this->resetCommandArguments();
foreach (self::stringifyArguments($commandArguments) as $commandArgument) {
$this->addCommandArgument($commandArgument);
}
}
public static function formatName(string $name): ?string
{
$value = preg_replace('/\s{2,}/', ' ', $name);
return ($value !== null) ? trim((string) $value) : null;
}
/**
* @param list<mixed> $arguments
*
* @return list<string>
*/
public static function stringifyArguments(array $arguments): array
{
$stringifiedArguments = [];
foreach ($arguments as $argument) {
if (is_scalar($argument)) {
$stringifiedArguments[] = (string) $argument;
}
}
return $stringifiedArguments;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Infrastructure/Model/NotificationTypeConverter.php | centreon/src/Core/ServiceTemplate/Infrastructure/Model/NotificationTypeConverter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Infrastructure\Model;
use Core\ServiceTemplate\Domain\Model\NotificationType;
final class NotificationTypeConverter
{
public const NONE_AS_BIT = 0b000000;
public const NONE_AS_CHAR = 'n';
public const WARNING_AS_BIT = 0b000001;
public const WARNING_AS_CHAR = 'w';
public const UNKNOWN_AS_BIT = 0b000010;
public const UNKNOWN_AS_CHAR = 'u';
public const CRITICAL_AS_BIT = 0b000100;
public const CRITICAL_AS_CHAR = 'c';
public const RECOVERY_AS_BIT = 0b001000;
public const RECOVERY_AS_CHAR = 'r';
public const FLAPPING_AS_BIT = 0b010000;
public const FLAPPING_AS_CHAR = 'f';
public const DOWNTIME_SCHEDULED_AS_BIT = 0b100000;
public const DOWNTIME_SCHEDULED__AS_CHAR = 's';
public const ALL_TYPE = 0b111111;
/**
* @param NotificationType[] $notificationTypes
*
* @return int|null
*/
public static function toBits(array $notificationTypes): ?int
{
if ($notificationTypes === []) {
return null;
}
$bits = 0;
foreach ($notificationTypes as $type) {
// The 0 is considered a "None" type and therefore we do not expect any other values.
if (self::toBit($type) === 0) {
return 0;
}
$bits |= self::toBit($type);
}
return $bits;
}
/**
* @param NotificationType[] $notificationTypes
*
* @return string|null
*/
public static function toString(array $notificationTypes): ?string
{
$notificationChars = [];
if ($notificationTypes === []) {
return null;
}
foreach ($notificationTypes as $notification) {
$notificationChars[] = match ($notification) {
NotificationType::None => self::NONE_AS_CHAR,
NotificationType::Warning => self::WARNING_AS_CHAR,
NotificationType::Unknown => self::UNKNOWN_AS_CHAR,
NotificationType::Critical => self::CRITICAL_AS_CHAR,
NotificationType::Recovery => self::RECOVERY_AS_CHAR,
NotificationType::Flapping => self::FLAPPING_AS_CHAR,
NotificationType::DowntimeScheduled => self::DOWNTIME_SCHEDULED__AS_CHAR,
};
}
return implode(',', $notificationChars);
}
/**
* @param NotificationType $notificationType
*
* @return int
*/
private static function toBit(NotificationType $notificationType): int
{
return match ($notificationType) {
NotificationType::None => self::NONE_AS_BIT,
NotificationType::Warning => self::WARNING_AS_BIT,
NotificationType::Unknown => self::UNKNOWN_AS_BIT,
NotificationType::Critical => self::CRITICAL_AS_BIT,
NotificationType::Recovery => self::RECOVERY_AS_BIT,
NotificationType::Flapping => self::FLAPPING_AS_BIT,
NotificationType::DowntimeScheduled => self::DOWNTIME_SCHEDULED_AS_BIT,
};
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Infrastructure/Model/YesNoDefaultConverter.php | centreon/src/Core/ServiceTemplate/Infrastructure/Model/YesNoDefaultConverter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Infrastructure\Model;
use Core\Common\Domain\YesNoDefault;
final class YesNoDefaultConverter
{
public static function toInt(YesNoDefault $yesNoDefault): int
{
return match ($yesNoDefault) {
YesNoDefault::No => 0,
YesNoDefault::Yes => 1,
default => 2,
};
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Infrastructure/Repository/DbReadServiceTemplateRepository.php | centreon/src/Core/ServiceTemplate/Infrastructure/Repository/DbReadServiceTemplateRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Infrastructure\Repository;
use Assert\AssertionFailedException;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use Core\Common\Domain\TrimmedString;
use Core\Common\Domain\YesNoDefault;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Common\Infrastructure\RequestParameters\Normalizer\BoolToEnumNormalizer;
use Core\ServiceCategory\Infrastructure\Repository\ServiceCategoryRepositoryTrait;
use Core\ServiceTemplate\Application\Repository\ReadServiceTemplateRepositoryInterface;
use Core\ServiceTemplate\Domain\Model\NotificationType;
use Core\ServiceTemplate\Domain\Model\ServiceTemplate;
use Core\ServiceTemplate\Domain\Model\ServiceTemplateInheritance;
use Utility\SqlConcatenator;
/**
* @phpstan-type _ServiceTemplate array{
* service_id: int,
* cg_additive_inheritance: int|null,
* contact_additive_inheritance: int|null,
* command_command_id: int|null,
* command_command_id2: int|null,
* command_command_id_arg: string|null,
* command_command_id_arg2: string|null,
* service_acknowledgement_timeout: int|null,
* service_active_checks_enabled: string,
* service_event_handler_enabled: string,
* service_flap_detection_enabled: string,
* service_check_freshness: string,
* service_locked: int,
* service_notifications_enabled: string|null,
* service_passive_checks_enabled: string|null,
* service_is_volatile: string,
* service_low_flap_threshold: int|null,
* service_high_flap_threshold: int|null,
* service_max_check_attempts: int|null,
* service_description: string,
* service_comment: string,
* service_alias: string,
* service_freshness_threshold: int|null,
* service_normal_check_interval: int|null,
* service_notification_interval: int|null,
* service_notification_options: string|null,
* service_notifications_enabled: string,
* service_passive_checks_enabled: string,
* service_recovery_notification_delay: int|null,
* service_retry_check_interval: int|null,
* service_template_model_stm_id: int|null,
* service_first_notification_delay: int|null,
* timeperiod_tp_id: int|null,
* timeperiod_tp_id2: int|null,
* esi_action_url: string|null,
* esi_icon_image: int|null,
* esi_icon_image_alt: string|null,
* esi_notes: string|null,
* esi_notes_url: string|null,
* graph_id: int|null,
* severity_id: int|null,
* host_template_ids: string|null,
* service_categories_ids: string|null
* }
*/
class DbReadServiceTemplateRepository extends AbstractRepositoryRDB implements ReadServiceTemplateRepositoryInterface
{
use LoggerTrait;
use ServiceCategoryRepositoryTrait;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function findById(int $serviceTemplateId): ?ServiceTemplate
{
$request = <<<'SQL'
SELECT service_id,
service.cg_additive_inheritance,
service.contact_additive_inheritance,
service.command_command_id,
service.command_command_id2,
service.command_command_id_arg,
service.command_command_id_arg2,
service.timeperiod_tp_id,
service.timeperiod_tp_id2,
service_acknowledgement_timeout,
service_active_checks_enabled,
service_event_handler_enabled,
service_flap_detection_enabled,
service_check_freshness,
service_locked,
service_notifications_enabled,
service_passive_checks_enabled,
service_is_volatile,
service_low_flap_threshold,
service_high_flap_threshold,
service_max_check_attempts,
service_description,
service_comment,
service_alias,
service_freshness_threshold,
service_normal_check_interval,
service_notification_interval,
service_notification_options,
service_recovery_notification_delay,
service_retry_check_interval,
service_template_model_stm_id,
service_first_notification_delay,
esi.esi_action_url,
esi.esi_icon_image,
esi.esi_icon_image_alt,
esi.esi_notes,
esi.esi_notes_url,
esi.graph_id,
GROUP_CONCAT(DISTINCT severity.sc_id) as severity_id,
GROUP_CONCAT(DISTINCT hsr.host_host_id) AS host_template_ids
FROM `:db`.service
LEFT JOIN `:db`.extended_service_information esi
ON esi.service_service_id = service.service_id
LEFT JOIN `:db`.service_categories_relation scr
ON scr.service_service_id = service.service_id
LEFT JOIN `:db`.service_categories severity
ON severity.sc_id = scr.sc_id
AND severity.level IS NOT NULL
LEFT JOIN `:db`.host_service_relation hsr
ON hsr.service_service_id = service.service_id
LEFT JOIN `:db`.host
ON host.host_id = hsr.host_host_id
AND host.host_register = '0'
WHERE service.service_id = :id
AND service.service_register = '0'
GROUP BY
service.service_id,
esi.esi_action_url,
esi.esi_icon_image,
esi.esi_icon_image_alt,
esi.esi_notes,
esi.esi_notes_url,
esi.graph_id
SQL;
$statement = $this->db->prepare($this->translateDbName($request));
$statement->bindValue(':id', $serviceTemplateId, \PDO::PARAM_INT);
$statement->execute();
if ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
/** @var _ServiceTemplate $result */
return $this->createServiceTemplate($result);
}
return null;
}
/**
* @inheritDoc
*/
public function findByIdAndAccessGroups(int $serviceTemplateId, array $accessGroups): ?ServiceTemplate
{
$accessGroupIds = array_map(
static fn ($accessGroup) => $accessGroup->getId(),
$accessGroups
);
$subRequest = $this->generateServiceCategoryAclSubRequest($accessGroupIds);
$categoryAcls = empty($subRequest)
? ''
: <<<SQL
AND scr.sc_id IN ({$subRequest})
SQL;
$request = <<<SQL
SELECT service_id,
service.cg_additive_inheritance,
service.contact_additive_inheritance,
service.command_command_id,
service.command_command_id2,
service.command_command_id_arg,
service.command_command_id_arg2,
service.timeperiod_tp_id,
service.timeperiod_tp_id2,
service_acknowledgement_timeout,
service_active_checks_enabled,
service_event_handler_enabled,
service_flap_detection_enabled,
service_check_freshness,
service_locked,
service_notifications_enabled,
service_passive_checks_enabled,
service_is_volatile,
service_low_flap_threshold,
service_high_flap_threshold,
service_max_check_attempts,
service_description,
service_comment,
service_alias,
service_freshness_threshold,
service_normal_check_interval,
service_notification_interval,
service_notification_options,
service_recovery_notification_delay,
service_retry_check_interval,
service_template_model_stm_id,
service_first_notification_delay,
esi.esi_action_url,
esi.esi_icon_image,
esi.esi_icon_image_alt,
esi.esi_notes,
esi.esi_notes_url,
esi.graph_id,
GROUP_CONCAT(DISTINCT severity.sc_id) as severity_id,
GROUP_CONCAT(DISTINCT hsr.host_host_id) AS host_template_ids
FROM `:db`.service
LEFT JOIN `:db`.extended_service_information esi
ON esi.service_service_id = service.service_id
LEFT JOIN `:db`.service_categories_relation scr
ON scr.service_service_id = service.service_id
LEFT JOIN `:db`.service_categories severity
ON severity.sc_id = scr.sc_id
AND severity.level IS NOT NULL
LEFT JOIN `:db`.host_service_relation hsr
ON hsr.service_service_id = service.service_id
LEFT JOIN `:db`.host
ON host.host_id = hsr.host_host_id
AND host.host_register = '0'
WHERE service.service_id = :id
AND service.service_register = '0'
{$categoryAcls}
GROUP BY
service.service_id,
esi.esi_action_url,
esi.esi_icon_image,
esi.esi_icon_image_alt,
esi.esi_notes,
esi.esi_notes_url,
esi.graph_id
SQL;
$statement = $this->db->prepare($this->translateDbName($request));
$statement->bindValue(':id', $serviceTemplateId, \PDO::PARAM_INT);
if ($this->hasRestrictedAccessToServiceCategories($accessGroupIds)) {
foreach ($accessGroupIds as $index => $id) {
$statement->bindValue(':access_group_id_' . $index, $id, \PDO::PARAM_INT);
}
}
$statement->execute();
if ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
/** @var _ServiceTemplate $result */
return $this->createServiceTemplate($result);
}
return null;
}
/**
* @inheritDoc
*/
public function findByRequestParameter(RequestParametersInterface $requestParameters): array
{
$this->info('Searching for service templates');
$sqlTranslator = new SqlRequestParametersTranslator($requestParameters);
$sqlTranslator->getRequestParameters()->setConcordanceStrictMode(RequestParameters::CONCORDANCE_MODE_STRICT);
$sqlTranslator->setConcordanceArray([
'id' => 'service_id',
'name' => 'service_description',
'alias' => 'service_alias',
'is_locked' => 'service_locked',
]);
$sqlTranslator->addNormalizer('is_locked', new BoolToEnumNormalizer());
$serviceTemplates = [];
$request = $this->findServiceTemplatesRequest();
$sqlConcatenator = new SqlConcatenator();
$sqlConcatenator->defineSelect($request);
$sqlConcatenator->appendGroupBy('service.service_id, esi.esi_action_url, esi.esi_icon_image, esi.esi_icon_image_alt, esi.esi_notes, esi.esi_notes_url, esi.graph_id');
$sqlConcatenator->appendWhere("service_register = '0'");
$sqlTranslator->translateForConcatenator($sqlConcatenator);
$sql = $sqlConcatenator->__toString();
$statement = $this->db->prepare($this->translateDbName($sql));
$sqlTranslator->bindSearchValues($statement);
$sqlConcatenator->bindValuesToStatement($statement);
$statement->execute();
$sqlTranslator->calculateNumberOfRows($this->db);
while ($data = $statement->fetch(\PDO::FETCH_ASSOC)) {
/**
* @var _ServiceTemplate $data
*/
$serviceTemplates[] = $this->createServiceTemplate($data);
}
return $serviceTemplates;
}
/**
* @inheritDoc
*/
public function findByRequestParametersAndAccessGroups(
RequestParametersInterface $requestParameters,
array $accessGroups,
): array {
if ($accessGroups === []) {
$this->debug('No access group for this user, return empty');
return [];
}
$accessGroupIds = array_map(
static fn ($accessGroup) => $accessGroup->getId(),
$accessGroups
);
$subRequest = $this->generateServiceCategoryAclSubRequest($accessGroupIds);
$this->info('Searching for service templates');
$sqlTranslator = new SqlRequestParametersTranslator($requestParameters);
$sqlTranslator->getRequestParameters()->setConcordanceStrictMode(RequestParameters::CONCORDANCE_MODE_STRICT);
$sqlTranslator->setConcordanceArray([
'id' => 'service_id',
'name' => 'service_description',
'alias' => 'service_alias',
'is_locked' => 'service_locked',
]);
$sqlTranslator->addNormalizer('is_locked', new BoolToEnumNormalizer());
$serviceTemplates = [];
$request = $this->findServiceTemplatesRequest();
$sqlConcatenator = new SqlConcatenator();
$sqlConcatenator->defineSelect($request);
$sqlConcatenator->appendGroupBy('service.service_id, esi.esi_action_url, esi.esi_icon_image, esi.esi_icon_image_alt, esi.esi_notes, esi.esi_notes_url, esi.graph_id');
if (! empty($subRequest)) {
$sqlConcatenator->appendWhere('scr.sc_id IN (' . $subRequest . ')');
}
$sqlConcatenator->appendWhere("service_register = '0'");
$sqlTranslator->translateForConcatenator($sqlConcatenator);
$sql = $sqlConcatenator->__toString();
$statement = $this->db->prepare($this->translateDbName($sql));
$sqlTranslator->bindSearchValues($statement);
$sqlConcatenator->bindValuesToStatement($statement);
if ($this->hasRestrictedAccessToServiceCategories($accessGroupIds)) {
foreach ($accessGroupIds as $index => $id) {
$statement->bindValue(':access_group_id_' . $index, $id, \PDO::PARAM_INT);
}
}
$statement->execute();
$sqlTranslator->calculateNumberOfRows($this->db);
while ($data = $statement->fetch(\PDO::FETCH_ASSOC)) {
/**
* @var _ServiceTemplate $data
*/
$serviceTemplates[] = $this->createServiceTemplate($data);
}
return $serviceTemplates;
}
/**
* @inheritDoc
*/
public function exists(int $serviceTemplateId): bool
{
$request = $this->translateDbName(
<<<'SQL'
SELECT 1
FROM `:db`.service
WHERE service_id = :id
AND service_register = '0'
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':id', $serviceTemplateId, \PDO::PARAM_INT);
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* @inheritDoc
*/
public function existsByName(TrimmedString $serviceTemplateName): bool
{
$request = $this->translateDbName(
<<<'SQL'
SELECT 1
FROM `:db`.service
WHERE service_description = :name
AND service_register = '0'
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':name', (string) $serviceTemplateName);
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* @inheritDoc
*/
public function findParents(int $serviceTemplateId): array
{
$request = $this->translateDbName(
<<<'SQL'
WITH RECURSIVE parents AS (
SELECT * FROM `:db`.`service`
WHERE `service_id` = :service_template_id
UNION
SELECT rel.* FROM `:db`.`service` AS rel, parents AS p
WHERE rel.`service_id` = p.`service_template_model_stm_id`
)
SELECT `service_id` AS child_id, `service_template_model_stm_id` AS parent_id
FROM parents
WHERE `service_template_model_stm_id` IS NOT NULL
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':service_template_id', $serviceTemplateId, \PDO::PARAM_INT);
$statement->execute();
$serviceTemplateInheritances = [];
while ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
/** @var array{child_id: int, parent_id: int} $result */
$serviceTemplateInheritances[] = new ServiceTemplateInheritance(
(int) $result['parent_id'],
(int) $result['child_id']
);
}
return $serviceTemplateInheritances;
}
/**
* @inheritDoc
*/
public function findByHostId(int $hostId): array
{
$serviceTemplates = [];
$request = $this->translateDbName(
<<<'SQL'
SELECT service_id,
service.cg_additive_inheritance,
service.contact_additive_inheritance,
service.command_command_id,
service.command_command_id2,
service.command_command_id_arg,
service.command_command_id_arg2,
service.timeperiod_tp_id,
service.timeperiod_tp_id2,
service_acknowledgement_timeout,
service_active_checks_enabled,
service_event_handler_enabled,
service_flap_detection_enabled,
service_check_freshness,
service_locked,
service_notifications_enabled,
service_passive_checks_enabled,
service_is_volatile,
service_low_flap_threshold,
service_high_flap_threshold,
service_max_check_attempts,
service_description,
service_comment,
service_alias,
service_freshness_threshold,
service_normal_check_interval,
service_notification_interval,
service_notification_options,
service_recovery_notification_delay,
service_retry_check_interval,
service_template_model_stm_id,
service_first_notification_delay,
esi.esi_action_url,
esi.esi_icon_image,
esi.esi_icon_image_alt,
esi.esi_notes,
esi.esi_notes_url,
esi.graph_id,
GROUP_CONCAT(DISTINCT severity.sc_id) as severity_id,
GROUP_CONCAT(DISTINCT hsr.host_host_id) AS host_template_ids
FROM `:db`.service
LEFT JOIN `:db`.extended_service_information esi
ON esi.service_service_id = service.service_id
LEFT JOIN `:db`.service_categories_relation scr
ON scr.service_service_id = service.service_id
LEFT JOIN `:db`.service_categories severity
ON severity.sc_id = scr.sc_id
AND severity.level IS NOT NULL
LEFT JOIN `:db`.host_service_relation hsr
ON hsr.service_service_id = service.service_id
LEFT JOIN `:db`.host
ON host.host_id = hsr.host_host_id
AND host.host_register = '0'
WHERE host.host_id = :host_id
AND service.service_register = '0'
GROUP BY
service.service_id,
esi.esi_action_url,
esi.esi_icon_image,
esi.esi_icon_image_alt,
esi.esi_notes,
esi.esi_notes_url,
esi.graph_id
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':host_id', (int) $hostId, \PDO::PARAM_INT);
$statement->execute();
while (($data = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
/** @var _ServiceTemplate $data */
$serviceTemplates[] = $this->createServiceTemplate($data);
}
return $serviceTemplates;
}
/**
* @param _ServiceTemplate $data
*
* @throws AssertionFailedException
* @throws \Exception
*
* @return ServiceTemplate
*/
private function createServiceTemplate(array $data): ServiceTemplate
{
$extractCommandArgument = static function (?string $arguments): array {
$commandSplitPattern = '/!([^!]*)/';
$commandArguments = [];
if ($arguments !== null && preg_match_all($commandSplitPattern, $arguments, $result)) {
$commandArguments = $result[1];
}
foreach ($commandArguments as $index => $argument) {
$commandArguments[$index] = str_replace(['#BR#', '#T#', '#R#'], ["\n", "\t", "\r"], $argument);
}
return $commandArguments;
};
$hostTemplateIds = $data['host_template_ids'] !== null
? array_map(
fn (mixed $hostTemplateId): int => (int) $hostTemplateId,
explode(',', $data['host_template_ids'])
)
: [];
return new ServiceTemplate(
(int) $data['service_id'],
$data['service_description'],
$data['service_alias'],
$extractCommandArgument($data['command_command_id_arg']),
$extractCommandArgument($data['command_command_id_arg2']),
$this->createNotificationType($data['service_notification_options']),
$hostTemplateIds,
$data['contact_additive_inheritance'] === 1,
$data['cg_additive_inheritance'] === 1,
$data['service_locked'] === 1,
$this->createYesNoDefault($data['service_active_checks_enabled']),
$this->createYesNoDefault($data['service_passive_checks_enabled']),
$this->createYesNoDefault($data['service_is_volatile']),
$this->createYesNoDefault($data['service_check_freshness']),
$this->createYesNoDefault($data['service_event_handler_enabled']),
$this->createYesNoDefault($data['service_flap_detection_enabled']),
$this->createYesNoDefault($data['service_notifications_enabled']),
$data['service_comment'],
$data['esi_notes'],
$data['esi_notes_url'],
$data['esi_action_url'],
$data['esi_icon_image_alt'],
$data['graph_id'],
$data['service_template_model_stm_id'],
$data['command_command_id'],
$data['command_command_id2'],
$data['timeperiod_tp_id2'],
$data['timeperiod_tp_id'],
$data['esi_icon_image'],
$data['severity_id'] !== null ? (int) $data['severity_id'] : null,
$data['service_max_check_attempts'],
$data['service_normal_check_interval'],
$data['service_retry_check_interval'],
$data['service_freshness_threshold'],
$data['service_low_flap_threshold'],
$data['service_high_flap_threshold'],
$data['service_notification_interval'],
$data['service_recovery_notification_delay'],
$data['service_first_notification_delay'],
$data['service_acknowledgement_timeout']
);
}
/**
* @param string $value
*
* @return YesNoDefault
*/
private function createYesNoDefault(string $value): YesNoDefault
{
return match ($value) {
'0' => YesNoDefault::No,
'1' => YesNoDefault::Yes,
default => YesNoDefault::Default,
};
}
/**
* @param string|null $notificationTypes
*
* @throws \Exception
*
* @return NotificationType[]
*/
private function createNotificationType(?string $notificationTypes): array
{
if ($notificationTypes === null) {
return [];
}
$notifications = [];
$types = explode(',', $notificationTypes);
foreach (array_unique($types) as $type) {
$notifications[] = match ($type) {
'w' => NotificationType::Warning,
'u' => NotificationType::Unknown,
'c' => NotificationType::Critical,
'r' => NotificationType::Recovery,
'f' => NotificationType::Flapping,
's' => NotificationType::DowntimeScheduled,
'n' => NotificationType::None,
default => throw new \Exception("Notification type '{$type}' unknown"),
};
}
return $notifications;
}
/**
* @param int[] $accessGroupIds
*
* @return string
*/
private function findServiceTemplatesRequest(array $accessGroupIds = []): string
{
return <<<'SQL'
SELECT service_id,
service.cg_additive_inheritance,
service.contact_additive_inheritance,
service.command_command_id,
service.command_command_id2,
service.command_command_id_arg,
service.command_command_id_arg2,
service.timeperiod_tp_id,
service.timeperiod_tp_id2,
service_acknowledgement_timeout,
service_active_checks_enabled,
service_event_handler_enabled,
service_flap_detection_enabled,
service_check_freshness,
service_locked,
service_notifications_enabled,
service_passive_checks_enabled,
service_is_volatile,
service_low_flap_threshold,
service_high_flap_threshold,
service_max_check_attempts,
service_description,
service_comment,
service_alias,
service_freshness_threshold,
service_normal_check_interval,
service_notification_interval,
service_notification_options,
service_recovery_notification_delay,
service_retry_check_interval,
service_template_model_stm_id,
service_first_notification_delay,
esi.esi_action_url,
esi.esi_icon_image,
esi.esi_icon_image_alt,
esi.esi_notes,
esi.esi_notes_url,
esi.graph_id,
GROUP_CONCAT(DISTINCT severity.sc_id) as severity_id,
GROUP_CONCAT(DISTINCT hsr.host_host_id) AS host_template_ids
FROM `:db`.service
LEFT JOIN `:db`.extended_service_information esi
ON esi.service_service_id = service.service_id
LEFT JOIN `:db`.service_categories_relation scr
ON scr.service_service_id = service.service_id
LEFT JOIN `:db`.service_categories severity
ON severity.sc_id = scr.sc_id
AND severity.level IS NOT NULL
LEFT JOIN `:db`.host_service_relation hsr
ON hsr.service_service_id = service.service_id
LEFT JOIN `:db`.host
ON host.host_id = hsr.host_host_id
AND host.host_register = '0'
SQL;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Infrastructure/Repository/DbWriteServiceTemplateActionLogRepository.php | centreon/src/Core/ServiceTemplate/Infrastructure/Repository/DbWriteServiceTemplateActionLogRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Infrastructure\Repository;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Infrastructure\DatabaseConnection;
use Core\ActionLog\Application\Repository\WriteActionLogRepositoryInterface;
use Core\ActionLog\Domain\Model\ActionLog;
use Core\Common\Application\Converter\YesNoDefaultConverter;
use Core\Common\Domain\YesNoDefault;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\ServiceTemplate\Application\Repository\ReadServiceTemplateRepositoryInterface;
use Core\ServiceTemplate\Application\Repository\WriteServiceTemplateRepositoryInterface;
use Core\ServiceTemplate\Domain\Model\NewServiceTemplate;
use Core\ServiceTemplate\Domain\Model\NotificationType;
use Core\ServiceTemplate\Domain\Model\ServiceTemplate;
use Core\ServiceTemplate\Infrastructure\Model\NotificationTypeConverter;
class DbWriteServiceTemplateActionLogRepository extends AbstractRepositoryRDB implements WriteServiceTemplateRepositoryInterface
{
use LoggerTrait;
/**
* @param WriteServiceTemplateRepositoryInterface $writeServiceTemplateRepository
* @param ContactInterface $contact
* @param ReadServiceTemplateRepositoryInterface $readServiceTemplateRepository
* @param WriteActionLogRepositoryInterface $writeActionLogRepository
* @param DatabaseConnection $db
*/
public function __construct(
private readonly WriteServiceTemplateRepositoryInterface $writeServiceTemplateRepository,
private readonly ContactInterface $contact,
private readonly ReadServiceTemplateRepositoryInterface $readServiceTemplateRepository,
private readonly WriteActionLogRepositoryInterface $writeActionLogRepository,
DatabaseConnection $db,
) {
$this->db = $db;
}
public function deleteById(int $serviceTemplateId): void
{
try {
$serviceTemplate = $this->readServiceTemplateRepository->findById($serviceTemplateId);
$this->writeServiceTemplateRepository->deleteById($serviceTemplateId);
$actionLog = new ActionLog(
ActionLog::OBJECT_TYPE_SERVICE,
$serviceTemplateId,
$serviceTemplate ? $serviceTemplate->getName() : '',
ActionLog::ACTION_TYPE_DELETE,
$this->contact->getId()
);
$this->writeActionLogRepository->addAction($actionLog);
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
throw $ex;
}
}
public function add(NewServiceTemplate $newServiceTemplate): int
{
try {
$serviceTemplateId = $this->writeServiceTemplateRepository->add($newServiceTemplate);
$actionLog = new ActionLog(
ActionLog::OBJECT_TYPE_SERVICE,
$serviceTemplateId,
$newServiceTemplate->getName(),
ActionLog::ACTION_TYPE_ADD,
$this->contact->getId()
);
$actionLogId = $this->writeActionLogRepository->addAction($actionLog);
$actionLog->setId($actionLogId);
$details = $this->getServiceTemplatePropertiesAsArray($newServiceTemplate);
$this->writeActionLogRepository->addActionDetails($actionLog, $details);
return $serviceTemplateId;
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
throw $ex;
}
}
public function linkToHosts(int $serviceTemplateId, array $hostTemplateIds): void
{
$this->writeServiceTemplateRepository->linkToHosts($serviceTemplateId, $hostTemplateIds);
}
public function unlinkHosts(int $serviceTemplateId): void
{
$this->writeServiceTemplateRepository->unlinkHosts($serviceTemplateId);
}
public function update(ServiceTemplate $serviceTemplate): void
{
try {
$currentServiceTemplate = $this->readServiceTemplateRepository->findById($serviceTemplate->getId());
$currentServiceTemplateDetails = $currentServiceTemplate
? $this->getServiceTemplatePropertiesAsArray($currentServiceTemplate)
: [];
$updatedServiceTemplateDetails = $this->getServiceTemplatePropertiesAsArray($serviceTemplate);
$diff = array_diff_assoc($updatedServiceTemplateDetails, $currentServiceTemplateDetails);
$this->writeServiceTemplateRepository->update($serviceTemplate);
$actionLog = new ActionLog(
ActionLog::OBJECT_TYPE_SERVICE,
$serviceTemplate->getId(),
$serviceTemplate->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($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
throw $ex;
}
}
/**
* @param NewServiceTemplate|ServiceTemplate $serviceTemplate
*
* @return array<string, int|bool|string>
*/
private function getServiceTemplatePropertiesAsArray($serviceTemplate): array
{
$serviceTemplatePropertiesArray = [];
$serviceTemplateReflection = new \ReflectionClass($serviceTemplate);
foreach ($serviceTemplateReflection->getProperties() as $property) {
$property->setAccessible(true);
$value = $property->getValue($serviceTemplate);
if ($value === null) {
$value = '';
}
if ($value instanceof YesNoDefault) {
$value = YesNoDefaultConverter::toString($value);
}
if (is_array($value)) {
if ($value === []) {
$value = '';
} elseif (is_string($value[0])) {
$value = implode(',', str_replace(["\n", "\t", "\r"], ['#BR#', '#T#', '#R#'], $value));
} elseif ($value[0] instanceof NotificationType) {
$value = NotificationTypeConverter::toString($value);
} else {
$value = implode(',', $value);
}
}
$serviceTemplatePropertiesArray[$property->getName()] = $value;
}
return $serviceTemplatePropertiesArray;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Infrastructure/Repository/DbWriteServiceTemplateRepository.php | centreon/src/Core/ServiceTemplate/Infrastructure/Repository/DbWriteServiceTemplateRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\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\ServiceTemplate\Application\Repository\WriteServiceTemplateRepositoryInterface;
use Core\ServiceTemplate\Domain\Model\NewServiceTemplate;
use Core\ServiceTemplate\Domain\Model\ServiceTemplate;
use Core\ServiceTemplate\Infrastructure\Model\NotificationTypeConverter;
use Core\ServiceTemplate\Infrastructure\Model\YesNoDefaultConverter;
class DbWriteServiceTemplateRepository extends AbstractRepositoryRDB implements WriteServiceTemplateRepositoryInterface
{
use LoggerTrait;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function add(NewServiceTemplate $newServiceTemplate): int
{
$request = $this->translateDbName(
<<<'SQL'
INSERT INTO `:db`.service
(
cg_additive_inheritance,
contact_additive_inheritance,
command_command_id,
command_command_id_arg,
command_command_id2,
command_command_id_arg2,
service_acknowledgement_timeout,
service_activate,
service_locked,
service_event_handler_enabled,
service_active_checks_enabled,
service_flap_detection_enabled,
service_check_freshness,
service_notifications_enabled,
service_passive_checks_enabled,
service_is_volatile,
service_low_flap_threshold,
service_high_flap_threshold,
service_max_check_attempts,
service_description,
service_comment,
service_alias,
service_freshness_threshold,
service_normal_check_interval,
service_notification_interval,
service_notification_options,
service_recovery_notification_delay,
service_retry_check_interval,
service_template_model_stm_id,
service_first_notification_delay,
timeperiod_tp_id,
timeperiod_tp_id2
) VALUES (
:contact_group_additive_inheritance,
:contact_additive_inheritance,
:command_id,
:command_arguments,
:event_handler_id,
:event_handler_arguments,
:acknowledgement_timeout,
:is_activated,
:is_locked,
:event_handler_enabled,
:active_checks_enabled,
:flap_detection_enabled,
:check_freshness,
:notifications_enabled,
:passive_checks_enabled,
:volatility,
:low_flap_threshold,
:high_flap_threshold,
:max_check_attempts,
:description,
:comment,
:alias,
:freshness_threshold,
:normal_check_interval,
:notification_interval,
:notification_options,
:recovery_notification_delay,
:retry_check_interval,
:service_template_id,
:first_notification_delay,
:check_time_period_id,
:notification_time_period_id
)
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(
':contact_group_additive_inheritance',
$newServiceTemplate->isContactGroupAdditiveInheritance(),
\PDO::PARAM_INT
);
$statement->bindValue(
':contact_additive_inheritance',
$newServiceTemplate->isContactAdditiveInheritance(),
\PDO::PARAM_INT
);
$statement->bindValue(':command_id', $newServiceTemplate->getCommandId(), \PDO::PARAM_INT);
$statement->bindValue(
':command_arguments',
$this->serializeArguments($newServiceTemplate->getCommandArguments())
);
$statement->bindValue(':event_handler_id', $newServiceTemplate->getEventHandlerId(), \PDO::PARAM_INT);
$statement->bindValue(
':event_handler_arguments',
$this->serializeArguments($newServiceTemplate->getEventHandlerArguments())
);
$statement->bindValue(
':acknowledgement_timeout',
$newServiceTemplate->getAcknowledgementTimeout(),
\PDO::PARAM_INT
);
$statement->bindValue(
':is_activated',
(new BoolToEnumNormalizer())->normalize(true),
\PDO::PARAM_STR
);
$statement->bindValue(
':is_locked',
$newServiceTemplate->isLocked(),
\PDO::PARAM_INT
);
$statement->bindValue(
':active_checks_enabled',
(string) YesNoDefaultConverter::toInt($newServiceTemplate->getActiveChecks())
);
$statement->bindValue(
':event_handler_enabled',
(string) YesNoDefaultConverter::toInt($newServiceTemplate->getEventHandlerEnabled())
);
$statement->bindValue(
':flap_detection_enabled',
(string) YesNoDefaultConverter::toInt($newServiceTemplate->getFlapDetectionEnabled())
);
$statement->bindValue(
':check_freshness',
(string) YesNoDefaultConverter::toInt($newServiceTemplate->getCheckFreshness())
);
$statement->bindValue(
':notifications_enabled',
(string) YesNoDefaultConverter::toInt($newServiceTemplate->getNotificationsEnabled())
);
$statement->bindValue(
':passive_checks_enabled',
(string) YesNoDefaultConverter::toInt($newServiceTemplate->getPassiveCheck())
);
$statement->bindValue(
':volatility',
(string) YesNoDefaultConverter::toInt($newServiceTemplate->getVolatility())
);
$statement->bindValue(
':low_flap_threshold',
$newServiceTemplate->getLowFlapThreshold(),
\PDO::PARAM_INT
);
$statement->bindValue(
':high_flap_threshold',
$newServiceTemplate->getHighFlapThreshold(),
\PDO::PARAM_INT
);
$statement->bindValue(
':max_check_attempts',
$newServiceTemplate->getMaxCheckAttempts(),
\PDO::PARAM_INT
);
$statement->bindValue(
':description',
$newServiceTemplate->getName()
);
$statement->bindValue(
':comment',
$newServiceTemplate->getComment()
);
$statement->bindValue(
':alias',
$newServiceTemplate->getAlias()
);
$statement->bindValue(
':freshness_threshold',
$newServiceTemplate->getFreshnessThreshold(),
\PDO::PARAM_INT
);
$statement->bindValue(
':normal_check_interval',
$newServiceTemplate->getNormalCheckInterval(),
\PDO::PARAM_INT
);
$statement->bindValue(
':notification_interval',
$newServiceTemplate->getNotificationInterval(),
\PDO::PARAM_INT
);
$statement->bindValue(
':notification_options',
NotificationTypeConverter::toString($newServiceTemplate->getNotificationTypes())
);
$statement->bindValue(
':recovery_notification_delay',
$newServiceTemplate->getRecoveryNotificationDelay(),
\PDO::PARAM_INT
);
$statement->bindValue(
':retry_check_interval',
$newServiceTemplate->getRetryCheckInterval(),
\PDO::PARAM_INT
);
$statement->bindValue(
':service_template_id',
$newServiceTemplate->getServiceTemplateParentId(),
\PDO::PARAM_INT
);
$statement->bindValue(
':first_notification_delay',
$newServiceTemplate->getFirstNotificationDelay(),
\PDO::PARAM_INT
);
$statement->bindValue(
':check_time_period_id',
$newServiceTemplate->getCheckTimePeriodId(),
\PDO::PARAM_INT
);
$statement->bindValue(
':notification_time_period_id',
$newServiceTemplate->getNotificationTimePeriodId(),
\PDO::PARAM_INT
);
$isAlreadyInTransaction = $this->db->inTransaction();
if (! $isAlreadyInTransaction) {
$this->db->beginTransaction();
}
try {
$statement->execute();
$newServiceTemplateId = (int) $this->db->lastInsertId();
$this->addExtensionServiceTemplate($newServiceTemplateId, $newServiceTemplate);
$this->linkSeverity($newServiceTemplateId, $newServiceTemplate->getSeverityId());
$this->linkHostTemplates($newServiceTemplateId, $newServiceTemplate->getHostTemplateIds());
if (! $isAlreadyInTransaction) {
$this->db->commit();
}
return $newServiceTemplateId;
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
if (! $isAlreadyInTransaction) {
$this->db->rollBack();
}
throw $ex;
}
}
/**
* @inheritDoc
*/
public function deleteById(int $serviceTemplateId): void
{
$this->info('Delete service template by ID');
$request = $this->translateDbName('DELETE FROM `:db`.service WHERE service_id = :id');
$statement = $this->db->prepare($request);
$statement->bindValue(':id', $serviceTemplateId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @inheritDoc
*/
public function linkToHosts(int $serviceTemplateId, array $hostTemplateIds): void
{
if ($hostTemplateIds === []) {
return;
}
$request = $this->translateDbName(
<<<'SQL'
INSERT INTO `:db`.host_service_relation
(host_host_id, service_service_id)
VALUES (:host_id, :service_template_id)
SQL
);
$alreadyInTransaction = $this->db->inTransaction();
try {
if (! $alreadyInTransaction) {
$this->db->beginTransaction();
}
$statement = $this->db->prepare($request);
$hostTemplateId = null;
$statement->bindParam(':service_template_id', $serviceTemplateId, \PDO::PARAM_INT);
$statement->bindParam(':host_id', $hostTemplateId, \PDO::PARAM_INT);
foreach ($hostTemplateIds as $hostTemplateId) {
$statement->execute();
}
if (! $alreadyInTransaction) {
$this->db->commit();
}
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
if (! $alreadyInTransaction) {
$this->db->rollBack();
}
throw $ex;
}
}
/**
* @inheritDoc
*/
public function unlinkHosts(int $serviceTemplateId): void
{
$alreadyInTransaction = $this->db->inTransaction();
try {
if (! $alreadyInTransaction) {
$this->db->beginTransaction();
}
$request = $this->translateDbName(
<<<'SQL'
DELETE FROM `:db`.host_service_relation
WHERE service_service_id = :service_template_id
AND host_host_id IS NOT NULL
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':service_template_id', $serviceTemplateId, \PDO::PARAM_INT);
$statement->execute();
if (! $alreadyInTransaction) {
$this->db->commit();
}
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
if (! $alreadyInTransaction) {
$this->db->rollBack();
}
throw $ex;
}
}
/**
* @inheritDoc
*/
public function update(ServiceTemplate $serviceTemplate): void
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
UPDATE `:db`.service
SET `cg_additive_inheritance` = :contact_group_additive_inheritance,
`contact_additive_inheritance` = :contact_additive_inheritance,
`command_command_id` = :command_id,
`command_command_id_arg` = :command_arguments,
`command_command_id2` = :event_handler_id,
`command_command_id_arg2` = :event_handler_arguments,
`service_acknowledgement_timeout` = :acknowledgement_timeout,
`service_activate` = :is_activated,
`service_locked` = :is_locked,
`service_event_handler_enabled` = :event_handler_enabled,
`service_active_checks_enabled` = :active_checks_enabled,
`service_flap_detection_enabled` = :flap_detection_enabled,
`service_check_freshness` = :check_freshness,
`service_notifications_enabled` = :notifications_enabled,
`service_passive_checks_enabled` = :passive_checks_enabled,
`service_is_volatile` = :volatility,
`service_low_flap_threshold` = :low_flap_threshold,
`service_high_flap_threshold` = :high_flap_threshold,
`service_max_check_attempts` = :max_check_attempts,
`service_description` = :description,
`service_comment` = :comment,
`service_alias` = :alias,
`service_freshness_threshold` = :freshness_threshold,
`service_normal_check_interval` = :normal_check_interval,
`service_notification_interval` = :notification_interval,
`service_notification_options` = :notification_options,
`service_recovery_notification_delay` = :recovery_notification_delay,
`service_retry_check_interval` = :retry_check_interval,
`service_template_model_stm_id` = :service_template_id,
`service_first_notification_delay` = :first_notification_delay,
`timeperiod_tp_id` = :check_time_period_id,
`timeperiod_tp_id2` = :notification_time_period_id
WHERE `service_id` = :service_id
SQL
));
$statement->bindValue(
':contact_group_additive_inheritance',
(int) $serviceTemplate->isContactGroupAdditiveInheritance(),
\PDO::PARAM_INT
);
$statement->bindValue(
':contact_additive_inheritance',
$serviceTemplate->isContactAdditiveInheritance(),
\PDO::PARAM_INT
);
$statement->bindValue(
':command_id',
$serviceTemplate->getCommandId(),
\PDO::PARAM_INT
);
$statement->bindValue(
':command_arguments',
$this->serializeArguments($serviceTemplate->getCommandArguments())
);
$statement->bindValue(':event_handler_id', $serviceTemplate->getEventHandlerId(), \PDO::PARAM_INT);
$statement->bindValue(
':event_handler_arguments',
$this->serializeArguments($serviceTemplate->getEventHandlerArguments())
);
$statement->bindValue(
':acknowledgement_timeout',
$serviceTemplate->getAcknowledgementTimeout(),
\PDO::PARAM_INT
);
$statement->bindValue(
':is_activated',
(new BoolToEnumNormalizer())->normalize(true),
\PDO::PARAM_STR
);
$statement->bindValue(
':is_locked',
$serviceTemplate->isLocked(),
\PDO::PARAM_INT
);
$statement->bindValue(
':event_handler_enabled',
(string) YesNoDefaultConverter::toInt($serviceTemplate->getEventHandlerEnabled())
);
$statement->bindValue(
':active_checks_enabled',
(string) YesNoDefaultConverter::toInt($serviceTemplate->getActiveChecks())
);
$statement->bindValue(
':flap_detection_enabled',
(string) YesNoDefaultConverter::toInt($serviceTemplate->getFlapDetectionEnabled())
);
$statement->bindValue(
':check_freshness',
(string) YesNoDefaultConverter::toInt($serviceTemplate->getCheckFreshness())
);
$statement->bindValue(
':notifications_enabled',
(string) YesNoDefaultConverter::toInt($serviceTemplate->getNotificationsEnabled())
);
$statement->bindValue(
':passive_checks_enabled',
(string) YesNoDefaultConverter::toInt($serviceTemplate->getPassiveCheck())
);
$statement->bindValue(
':volatility',
(string) YesNoDefaultConverter::toInt($serviceTemplate->getVolatility())
);
$statement->bindValue(':low_flap_threshold', $serviceTemplate->getLowFlapThreshold(), \PDO::PARAM_INT);
$statement->bindValue(':high_flap_threshold', $serviceTemplate->getHighFlapThreshold(), \PDO::PARAM_INT);
$statement->bindValue(':max_check_attempts', $serviceTemplate->getMaxCheckAttempts(), \PDO::PARAM_INT);
$statement->bindValue(':description', $serviceTemplate->getName());
$statement->bindValue(':comment', $serviceTemplate->getComment());
$statement->bindValue(':alias', $serviceTemplate->getAlias());
$statement->bindValue(':freshness_threshold', $serviceTemplate->getFreshnessThreshold(), \PDO::PARAM_INT);
$statement->bindValue(':normal_check_interval', $serviceTemplate->getNormalCheckInterval(), \PDO::PARAM_INT);
$statement->bindValue(':notification_interval', $serviceTemplate->getNotificationInterval(), \PDO::PARAM_INT);
$statement->bindValue(
':notification_options',
NotificationTypeConverter::toString($serviceTemplate->getNotificationTypes())
);
$statement->bindValue(
':recovery_notification_delay',
$serviceTemplate->getRecoveryNotificationDelay(),
\PDO::PARAM_INT
);
$statement->bindValue(':retry_check_interval', $serviceTemplate->getRetryCheckInterval(), \PDO::PARAM_INT);
$statement->bindValue(':service_template_id', $serviceTemplate->getServiceTemplateParentId(), \PDO::PARAM_INT);
$statement->bindValue(
':first_notification_delay',
$serviceTemplate->getFirstNotificationDelay(),
\PDO::PARAM_INT
);
$statement->bindValue(':check_time_period_id', $serviceTemplate->getCheckTimePeriodId(), \PDO::PARAM_INT);
$statement->bindValue(
':notification_time_period_id',
$serviceTemplate->getNotificationTimePeriodId(),
\PDO::PARAM_INT
);
$statement->bindValue(':service_id', $serviceTemplate->getId(), \PDO::PARAM_INT);
$isAlreadyInTransaction = $this->db->inTransaction();
if (! $isAlreadyInTransaction) {
$this->db->beginTransaction();
}
try {
$statement->execute();
$this->updateExtensionServiceTemplate($serviceTemplate);
$this->updateSeverityLink($serviceTemplate);
if (! $isAlreadyInTransaction) {
$this->db->commit();
}
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
if (! $isAlreadyInTransaction) {
$this->db->rollBack();
}
throw $ex;
}
}
/**
* @param int $serviceTemplateId
* @param NewServiceTemplate $serviceTemplate
*/
private function addExtensionServiceTemplate(int $serviceTemplateId, NewServiceTemplate $serviceTemplate): void
{
$request = $this->translateDbName(
<<<'SQL'
INSERT INTO `:db`.extended_service_information
(
service_service_id,
esi_action_url,
esi_icon_image,
esi_icon_image_alt,
esi_notes,
esi_notes_url,
graph_id
) VALUES (
:service_template_id,
:action_url,
:icon_id,
:icon_alternative_text,
:notes,
:notes_url,
:graph_template_id
)
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':service_template_id', $serviceTemplateId, \PDO::PARAM_INT);
$statement->bindValue(':action_url', $serviceTemplate->getActionUrl());
$statement->bindValue(':icon_id', $serviceTemplate->getIconId(), \PDO::PARAM_INT);
$statement->bindValue(':icon_alternative_text', $serviceTemplate->getIconAlternativeText());
$statement->bindValue(':notes', $serviceTemplate->getNote());
$statement->bindValue(':notes_url', $serviceTemplate->getNoteUrl());
$statement->bindValue(':graph_template_id', $serviceTemplate->getGraphTemplateId(), \PDO::PARAM_INT);
$statement->execute();
}
/**
* @param ServiceTemplate $serviceTemplate
*
* @throws \Throwable
*/
private function updateExtensionServiceTemplate(ServiceTemplate $serviceTemplate): void
{
$request = $this->translateDbName(
<<<'SQL'
UPDATE `:db`.extended_service_information
SET `esi_action_url` = :action_url,
`esi_icon_image` = :icon_id,
`esi_icon_image_alt` = :icon_alternative_text,
`esi_notes` = :notes,
`esi_notes_url` = :notes_url,
`graph_id` = :graph_template_id
WHERE service_service_id = :service_id
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':service_id', $serviceTemplate->getId(), \PDO::PARAM_INT);
$statement->bindValue(':action_url', $serviceTemplate->getActionUrl());
$statement->bindValue(':icon_id', $serviceTemplate->getIconId(), \PDO::PARAM_INT);
$statement->bindValue(':icon_alternative_text', $serviceTemplate->getIconAlternativeText());
$statement->bindValue(':notes', $serviceTemplate->getNote());
$statement->bindValue(':notes_url', $serviceTemplate->getNoteUrl());
$statement->bindValue(':graph_template_id', $serviceTemplate->getGraphTemplateId(), \PDO::PARAM_INT);
$statement->execute();
}
/**
* @param int $serviceTemplateId
* @param int|null $severityId
*
* @throws \Throwable
*/
private function linkSeverity(int $serviceTemplateId, ?int $severityId): void
{
if ($severityId === null) {
return;
}
$request = $this->translateDbName(
<<<'SQL'
INSERT INTO `:db`.service_categories_relation
(
service_service_id,
sc_id
) VALUES
(
:service_template_id,
:severity_id
)
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':service_template_id', $serviceTemplateId, \PDO::PARAM_INT);
$statement->bindValue(':severity_id', $severityId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @param ServiceTemplate $serviceTemplate
*
* @throws \Throwable
*/
private function updateSeverityLink(ServiceTemplate $serviceTemplate): void
{
$this->deleteSeverityLink($serviceTemplate->getId());
$this->linkSeverity($serviceTemplate->getId(), $serviceTemplate->getSeverityId());
}
/**
* @param int $serviceTemplateId
*
* @throws \Throwable
*/
private function deleteSeverityLink(int $serviceTemplateId): void
{
$request = $this->translateDbName(
<<<'SQL'
DELETE scr
FROM `:db`.service_categories_relation scr
INNER JOIN `:db`.service_categories sc
ON sc.sc_id = scr.sc_id
AND sc.level IS NOT NULL
WHERE service_service_id = :service_template_id
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':service_template_id', $serviceTemplateId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* Link host templates to service template.
*
* @param int $serviceTemplateId
* @param list<int> $hostTemplateIds
*
* @throws \PDOException
*/
private function linkHostTemplates(int $serviceTemplateId, array $hostTemplateIds): void
{
$request = $this->translateDbName(
<<<'SQL'
INSERT INTO `:db`.host_service_relation
(
host_host_id,
service_service_id
) VALUES
(
:host_template_id,
:service_template_id
)
SQL
);
$statement = $this->db->prepare($request);
$statement->bindParam(':service_template_id', $serviceTemplateId, \PDO::PARAM_INT);
foreach ($hostTemplateIds as $hostTemplateId) {
$statement->bindParam(':host_template_id', $hostTemplateId, \PDO::PARAM_INT);
$statement->execute();
}
}
/**
* @param list<string> $arguments
*
* @return string
*/
private function serializeArguments(array $arguments): string
{
$serializedArguments = '';
foreach ($arguments as $argument) {
$serializedArguments .= '!' . str_replace(["\n", "\t", "\r"], ['#BR#', '#T#', '#R#'], $argument);
}
return $serializedArguments;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Infrastructure/API/PartialUpdateServiceTemplate/PartialUpdateServiceTemplateController.php | centreon/src/Core/ServiceTemplate/Infrastructure/API/PartialUpdateServiceTemplate/PartialUpdateServiceTemplateController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Infrastructure\API\PartialUpdateServiceTemplate;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\ServiceTemplate\Application\UseCase\PartialUpdateServiceTemplate\MacroDto;
use Core\ServiceTemplate\Application\UseCase\PartialUpdateServiceTemplate\PartialUpdateServiceTemplate;
use Core\ServiceTemplate\Application\UseCase\PartialUpdateServiceTemplate\PartialUpdateServiceTemplateRequest;
use Core\ServiceTemplate\Application\UseCase\PartialUpdateServiceTemplate\ServiceGroupDto;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* @phpstan-type _ServiceTemplate = array{
* name: string,
* alias: string,
* comment: string|null,
* service_template_id: int|null,
* check_command_id: int|null,
* check_command_args: list<string>,
* check_timeperiod_id: int,
* max_check_attempts: int|null,
* normal_check_interval: int|null,
* retry_check_interval: int|null,
* active_check_enabled: int,
* passive_check_enabled: int,
* volatility_enabled: int,
* notification_enabled: int,
* is_contact_additive_inheritance: boolean,
* is_contact_group_additive_inheritance: boolean,
* notification_interval: int|null,
* notification_timeperiod_id: int,
* notification_type: int,
* first_notification_delay: int|null,
* recovery_notification_delay: int|null,
* acknowledgement_timeout: int|null,
* freshness_checked: int,
* freshness_threshold: int|null,
* flap_detection_enabled: int,
* low_flap_threshold: int|null,
* high_flap_threshold: int|null,
* event_handler_enabled: int,
* event_handler_command_id: int|null,
* event_handler_command_args: list<string>,
* graph_template_id: int|null,
* host_templates: list<int>,
* note: string|null,
* note_url: string|null,
* action_url: string|null,
* icon_id: int|null,
* icon_alternative: string|null,
* severity_id: int|null,
* host_templates: list<int>,
* service_categories: list<int>,
* macros: array<array{name: string, value: string|null, is_password: bool, description: string|null}>,
* service_groups: array<array{host_template_id: int, service_group_id: int}>
* }
*/
final class PartialUpdateServiceTemplateController extends AbstractController
{
use LoggerTrait;
/**
* @param PartialUpdateServiceTemplate $useCase
* @param DefaultPresenter $presenter
* @param bool $isCloudPlatform
* @param int $serviceTemplateId
* @param Request $request
*
* @return Response
*/
public function __invoke(
PartialUpdateServiceTemplate $useCase,
DefaultPresenter $presenter,
bool $isCloudPlatform,
int $serviceTemplateId,
Request $request,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
$validationSchema = $isCloudPlatform
? 'PartialUpdateServiceTemplateSaasSchema.json'
: 'PartialUpdateServiceTemplateOnPremSchema.json';
try {
/** @var _ServiceTemplate $data
*/
$data = $this->validateAndRetrieveDataSent(
$request,
__DIR__ . DIRECTORY_SEPARATOR . $validationSchema
);
$useCase($this->createDto($serviceTemplateId, $data), $presenter);
} catch (\InvalidArgumentException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
}
return $presenter->show();
}
/**
* @param int $serviceTemplateId
* @param _ServiceTemplate $request
*
* @return PartialUpdateServiceTemplateRequest
*/
private function createDto(int $serviceTemplateId, array $request): PartialUpdateServiceTemplateRequest
{
$serviceTemplate = new PartialUpdateServiceTemplateRequest($serviceTemplateId);
if (array_key_exists('name', $request)) {
$serviceTemplate->name = $request['name'];
}
if (array_key_exists('alias', $request)) {
$serviceTemplate->alias = $request['alias'];
}
if (array_key_exists('comment', $request)) {
$serviceTemplate->comment = $request['comment'];
}
if (array_key_exists('service_template_id', $request)) {
$serviceTemplate->serviceTemplateParentId = $request['service_template_id'];
}
if (array_key_exists('check_command_id', $request)) {
$serviceTemplate->commandId = $request['check_command_id'];
}
if (array_key_exists('check_command_args', $request)) {
$serviceTemplate->commandArguments = $request['check_command_args'];
}
if (array_key_exists('check_timeperiod_id', $request)) {
$serviceTemplate->checkTimePeriodId = $request['check_timeperiod_id'];
}
if (array_key_exists('max_check_attempts', $request)) {
$serviceTemplate->maxCheckAttempts = $request['max_check_attempts'];
}
if (array_key_exists('normal_check_interval', $request)) {
$serviceTemplate->normalCheckInterval = $request['normal_check_interval'];
}
if (array_key_exists('retry_check_interval', $request)) {
$serviceTemplate->retryCheckInterval = $request['retry_check_interval'];
}
if (array_key_exists('active_check_enabled', $request)) {
$serviceTemplate->activeChecksEnabled = $request['active_check_enabled'];
}
if (array_key_exists('passive_check_enabled', $request)) {
$serviceTemplate->passiveCheckEnabled = $request['passive_check_enabled'];
}
if (array_key_exists('volatility_enabled', $request)) {
$serviceTemplate->volatility = $request['volatility_enabled'];
}
if (array_key_exists('notification_enabled', $request)) {
$serviceTemplate->notificationsEnabled = $request['notification_enabled'];
}
if (array_key_exists('is_contact_additive_inheritance', $request)) {
$serviceTemplate->isContactAdditiveInheritance = $request['is_contact_additive_inheritance'];
}
if (array_key_exists('is_contact_group_additive_inheritance', $request)) {
$serviceTemplate->isContactGroupAdditiveInheritance = $request['is_contact_group_additive_inheritance'];
}
if (array_key_exists('notification_interval', $request)) {
$serviceTemplate->notificationInterval = $request['notification_interval'];
}
if (array_key_exists('notification_timeperiod_id', $request)) {
$serviceTemplate->notificationTimePeriodId = $request['notification_timeperiod_id'];
}
if (array_key_exists('notification_type', $request)) {
$serviceTemplate->notificationTypes = $request['notification_type'];
}
if (array_key_exists('first_notification_delay', $request)) {
$serviceTemplate->firstNotificationDelay = $request['first_notification_delay'];
}
if (array_key_exists('recovery_notification_delay', $request)) {
$serviceTemplate->recoveryNotificationDelay = $request['recovery_notification_delay'];
}
if (array_key_exists('acknowledgement_timeout', $request)) {
$serviceTemplate->acknowledgementTimeout = $request['acknowledgement_timeout'];
}
if (array_key_exists('freshness_checked', $request)) {
$serviceTemplate->checkFreshness = $request['freshness_checked'];
}
if (array_key_exists('freshness_threshold', $request)) {
$serviceTemplate->freshnessThreshold = $request['freshness_threshold'];
}
if (array_key_exists('flap_detection_enabled', $request)) {
$serviceTemplate->flapDetectionEnabled = $request['flap_detection_enabled'];
}
if (array_key_exists('low_flap_threshold', $request)) {
$serviceTemplate->lowFlapThreshold = $request['low_flap_threshold'];
}
if (array_key_exists('high_flap_threshold', $request)) {
$serviceTemplate->highFlapThreshold = $request['high_flap_threshold'];
}
if (array_key_exists('event_handler_enabled', $request)) {
$serviceTemplate->eventHandlerEnabled = $request['event_handler_enabled'];
}
if (array_key_exists('event_handler_command_id', $request)) {
$serviceTemplate->eventHandlerId = $request['event_handler_command_id'];
}
if (array_key_exists('event_handler_command_args', $request)) {
$serviceTemplate->eventHandlerArguments = $request['event_handler_command_args'];
}
if (array_key_exists('graph_template_id', $request)) {
$serviceTemplate->graphTemplateId = $request['graph_template_id'];
}
if (array_key_exists('note', $request)) {
$serviceTemplate->note = $request['note'];
}
if (array_key_exists('note_url', $request)) {
$serviceTemplate->noteUrl = $request['note_url'];
}
if (array_key_exists('action_url', $request)) {
$serviceTemplate->actionUrl = $request['action_url'];
}
if (array_key_exists('icon_id', $request)) {
$serviceTemplate->iconId = $request['icon_id'];
}
if (array_key_exists('icon_alternative', $request)) {
$serviceTemplate->iconAlternativeText = $request['icon_alternative'];
}
if (array_key_exists('severity_id', $request)) {
$serviceTemplate->severityId = $request['severity_id'];
}
if (array_key_exists('host_templates', $request)) {
$serviceTemplate->hostTemplates = $request['host_templates'];
}
if (array_key_exists('service_categories', $request)) {
$serviceTemplate->serviceCategories = $request['service_categories'];
}
if (array_key_exists('macros', $request)) {
$serviceTemplate->macros = array_map(
fn (array $macro): MacroDto => new MacroDto(
$macro['name'],
$macro['value'],
(bool) $macro['is_password'],
$macro['description']
),
$request['macros']
);
}
if (array_key_exists('service_groups', $request)) {
$serviceTemplate->serviceGroups = array_map(
fn (array $serviceGroup): ServiceGroupDto => new ServiceGroupDto(
$serviceGroup['host_template_id'],
$serviceGroup['service_group_id']
),
$request['service_groups']
);
}
return $serviceTemplate;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Infrastructure/API/AddServiceTemplate/AddServiceTemplateController.php | centreon/src/Core/ServiceTemplate/Infrastructure/API/AddServiceTemplate/AddServiceTemplateController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Infrastructure\API\AddServiceTemplate;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Common\Domain\YesNoDefault;
use Core\ServiceTemplate\Application\UseCase\AddServiceTemplate\AddServiceTemplate;
use Core\ServiceTemplate\Application\UseCase\AddServiceTemplate\AddServiceTemplateRequest;
use Core\ServiceTemplate\Application\UseCase\AddServiceTemplate\MacroDto;
use Core\ServiceTemplate\Application\UseCase\AddServiceTemplate\ServiceGroupDto;
use Core\ServiceTemplate\Infrastructure\Model\YesNoDefaultConverter;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
/**
* @phpstan-type _ServiceTemplate = array{
* name: string,
* alias: string,
* comment: string|null,
* service_template_id: int|null,
* check_command_id: int|null,
* check_command_args: list<string>|null,
* check_timeperiod_id: int|null,
* max_check_attempts: int|null,
* normal_check_interval: int|null,
* retry_check_interval: int|null,
* active_check_enabled: int|null,
* passive_check_enabled: int|null,
* volatility_enabled: int|null,
* notification_enabled: int|null,
* is_contact_additive_inheritance: boolean|null,
* is_contact_group_additive_inheritance: boolean|null,
* notification_interval: int|null,
* notification_timeperiod_id: int|null,
* notification_type: int|null,
* first_notification_delay: int|null,
* recovery_notification_delay: int|null,
* acknowledgement_timeout: int|null,
* freshness_checked: int|null,
* freshness_threshold: int|null,
* flap_detection_enabled: int|null,
* low_flap_threshold: int|null,
* high_flap_threshold: int|null,
* event_handler_enabled: int|null,
* event_handler_command_id: int|null,
* event_handler_command_args: list<string>|null,
* graph_template_id: int|null,
* host_templates: list<int>|null,
* note: string|null,
* note_url: string|null,
* action_url: string|null,
* icon_id: int|null,
* icon_alternative: string|null,
* severity_id: int|null,
* is_locked: boolean|null,
* macros: array<array{name: string, value: string|null, is_password: bool, description: string|null}>,
* service_categories: list<int>|null,
* service_groups: array<array{host_template_id: int, service_group_id: int}>
* }
*/
final class AddServiceTemplateController extends AbstractController
{
use LoggerTrait;
/**
* @param AddServiceTemplate $useCase
* @param AddServiceTemplateOnPremPresenter $onPremPresenter
* @param AddServiceTemplateSaasPresenter $saasPresenter
* @param bool $isCloudPlatform
* @param Request $request
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
AddServiceTemplate $useCase,
AddServiceTemplateOnPremPresenter $onPremPresenter,
AddServiceTemplateSaasPresenter $saasPresenter,
bool $isCloudPlatform,
Request $request,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
$presenter = $isCloudPlatform ? $saasPresenter : $onPremPresenter;
$validationSchema = $isCloudPlatform
? 'AddServiceTemplateSaasSchema.json'
: 'AddServiceTemplateOnPremSchema.json';
try {
/** @var _ServiceTemplate $data */
$data = $this->validateAndRetrieveDataSent(
$request,
__DIR__ . DIRECTORY_SEPARATOR . $validationSchema
);
$useCase($this->createDto($data), $presenter);
} catch (\InvalidArgumentException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
}
return $presenter->show();
}
/**
* @param _ServiceTemplate $request
*
* @return AddServiceTemplateRequest
*/
private function createDto(array $request): AddServiceTemplateRequest
{
$defaultOptionValue = YesNoDefaultConverter::toInt(YesNoDefault::Default);
$dto = new AddServiceTemplateRequest();
$dto->name = $request['name'];
$dto->alias = $request['alias'];
$dto->comment = $request['comment'] ?? null;
$dto->serviceTemplateParentId = $request['service_template_id'];
$dto->commandId = $request['check_command_id'] ?? null;
$dto->commandArguments = $request['check_command_args'] ?? [];
$dto->checkTimePeriodId = $request['check_timeperiod_id'];
$dto->maxCheckAttempts = $request['max_check_attempts'] ?? null;
$dto->normalCheckInterval = $request['normal_check_interval'] ?? null;
$dto->retryCheckInterval = $request['retry_check_interval'] ?? null;
$dto->activeChecks = $request['active_check_enabled'] ?? $defaultOptionValue;
$dto->passiveCheck = $request['passive_check_enabled'] ?? $defaultOptionValue;
$dto->volatility = $request['volatility_enabled'] ?? $defaultOptionValue;
$dto->notificationsEnabled = $request['notification_enabled'] ?? $defaultOptionValue;
$dto->isContactAdditiveInheritance = $request['is_contact_additive_inheritance'] ?? false;
$dto->isContactGroupAdditiveInheritance = $request['is_contact_group_additive_inheritance'] ?? false;
$dto->notificationInterval = $request['notification_interval'] ?? null;
$dto->notificationTimePeriodId = $request['notification_timeperiod_id'] ?? null;
$dto->notificationTypes = $request['notification_type'] ?? null;
$dto->firstNotificationDelay = $request['first_notification_delay'] ?? null;
$dto->recoveryNotificationDelay = $request['recovery_notification_delay'] ?? null;
$dto->acknowledgementTimeout = $request['acknowledgement_timeout'] ?? null;
$dto->checkFreshness = $request['freshness_checked'] ?? $defaultOptionValue;
$dto->freshnessThreshold = $request['freshness_threshold'] ?? null;
$dto->flapDetectionEnabled = $request['flap_detection_enabled'] ?? $defaultOptionValue;
$dto->lowFlapThreshold = $request['low_flap_threshold'] ?? null;
$dto->highFlapThreshold = $request['high_flap_threshold'] ?? null;
$dto->eventHandlerEnabled = $request['event_handler_enabled'] ?? $defaultOptionValue;
$dto->eventHandlerId = $request['event_handler_command_id'] ?? null;
$dto->eventHandlerArguments = $request['event_handler_command_args'] ?? [];
$dto->graphTemplateId = $request['graph_template_id'] ?? null;
$dto->hostTemplateIds = $request['host_templates'] ?? [];
$dto->note = $request['note'];
$dto->noteUrl = $request['note_url'];
$dto->actionUrl = $request['action_url'];
$dto->iconId = $request['icon_id'] ?? null;
$dto->iconAlternativeText = $request['icon_alternative'] ?? null;
$dto->severityId = $request['severity_id'];
$dto->serviceCategories = $request['service_categories'] ?? [];
foreach ($request['service_groups'] as $macro) {
$dto->serviceGroups[] = new ServiceGroupDto(
$macro['host_template_id'],
$macro['service_group_id']
);
}
foreach ($request['macros'] as $macro) {
$dto->macros[] = new MacroDto(
$macro['name'],
$macro['value'],
(bool) $macro['is_password'],
$macro['description']
);
}
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/ServiceTemplate/Infrastructure/API/AddServiceTemplate/AddServiceTemplateOnPremPresenter.php | centreon/src/Core/ServiceTemplate/Infrastructure/API/AddServiceTemplate/AddServiceTemplateOnPremPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Infrastructure\API\AddServiceTemplate;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\CreatedResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\ServiceTemplate\Application\UseCase\AddServiceTemplate\AddServiceTemplatePresenterInterface;
use Core\ServiceTemplate\Application\UseCase\AddServiceTemplate\AddServiceTemplateResponse;
use Core\ServiceTemplate\Application\UseCase\AddServiceTemplate\MacroDto;
use Core\ServiceTemplate\Infrastructure\Model\NotificationTypeConverter;
use Core\ServiceTemplate\Infrastructure\Model\YesNoDefaultConverter;
class AddServiceTemplateOnPremPresenter extends AbstractPresenter implements AddServiceTemplatePresenterInterface
{
public function presentResponse(ResponseStatusInterface|AddServiceTemplateResponse $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
$this->present(
new CreatedResponse(
$response->id,
[
'id' => $response->id,
'name' => $response->name,
'alias' => $response->alias,
'comment' => $response->comment,
'service_template_id' => $response->serviceTemplateId,
'check_command_id' => $response->commandId,
'check_command_args' => $response->commandArguments,
'check_timeperiod_id' => $response->checkTimePeriodId,
'max_check_attempts' => $response->maxCheckAttempts,
'normal_check_interval' => $response->normalCheckInterval,
'retry_check_interval' => $response->retryCheckInterval,
'active_check_enabled' => YesNoDefaultConverter::toInt($response->activeChecks),
'passive_check_enabled' => YesNoDefaultConverter::toInt($response->passiveCheck),
'volatility_enabled' => YesNoDefaultConverter::toInt($response->volatility),
'notification_enabled' => YesNoDefaultConverter::toInt($response->notificationsEnabled),
'is_contact_additive_inheritance' => $response->isContactAdditiveInheritance,
'is_contact_group_additive_inheritance' => $response->isContactGroupAdditiveInheritance,
'notification_interval' => $response->notificationInterval,
'notification_timeperiod_id' => $response->notificationTimePeriodId,
'notification_type' => NotificationTypeConverter::toBits($response->notificationTypes),
'first_notification_delay' => $response->firstNotificationDelay,
'recovery_notification_delay' => $response->recoveryNotificationDelay,
'acknowledgement_timeout' => $response->acknowledgementTimeout,
'freshness_checked' => YesNoDefaultConverter::toInt($response->checkFreshness),
'freshness_threshold' => $response->freshnessThreshold,
'flap_detection_enabled' => YesNoDefaultConverter::toInt($response->flapDetectionEnabled),
'low_flap_threshold' => $response->lowFlapThreshold,
'high_flap_threshold' => $response->highFlapThreshold,
'event_handler_enabled' => YesNoDefaultConverter::toInt($response->eventHandlerEnabled),
'event_handler_command_id' => $response->eventHandlerId,
'event_handler_command_args' => $response->eventHandlerArguments,
'graph_template_id' => $response->graphTemplateId,
'note' => $response->note,
'note_url' => $response->noteUrl,
'action_url' => $response->actionUrl,
'icon_id' => $response->iconId,
'icon_alternative' => $response->iconAlternativeText,
'severity_id' => $response->severityId,
'host_templates' => $response->hostTemplateIds,
'is_locked' => $response->isLocked,
'macros' => array_map(fn (MacroDto $macro): array => [
'name' => $macro->name,
// Note: do not handle vault storage at the moment
'value' => $macro->isPassword ? null : $macro->value,
'is_password' => $macro->isPassword,
'description' => $macro->description,
], $response->macros),
'categories' => array_map(fn ($category): array => [
'id' => $category['id'],
'name' => $category['name'],
], $response->categories),
'groups' => array_map(fn ($group): array => [
'id' => $group['serviceGroupId'],
'name' => $group['serviceGroupName'],
'host_template_id' => $group['hostTemplateId'],
'host_template_name' => $group['hostTemplateName'],
], $response->groups),
]
)
);
// The location will be implemented when the FindServiceTemplate API endpoint is implemented.
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Infrastructure/API/AddServiceTemplate/AddServiceTemplateSaasPresenter.php | centreon/src/Core/ServiceTemplate/Infrastructure/API/AddServiceTemplate/AddServiceTemplateSaasPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Infrastructure\API\AddServiceTemplate;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\CreatedResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\ServiceTemplate\Application\UseCase\AddServiceTemplate\AddServiceTemplatePresenterInterface;
use Core\ServiceTemplate\Application\UseCase\AddServiceTemplate\AddServiceTemplateResponse;
use Core\ServiceTemplate\Application\UseCase\AddServiceTemplate\MacroDto;
class AddServiceTemplateSaasPresenter extends AbstractPresenter implements AddServiceTemplatePresenterInterface
{
public function __construct(PresenterFormatterInterface $presenterFormatter)
{
parent::__construct($presenterFormatter);
}
public function presentResponse(ResponseStatusInterface|AddServiceTemplateResponse $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
$this->present(
new CreatedResponse(
$response->id,
[
'id' => $response->id,
'name' => $response->name,
'alias' => $response->alias,
'service_template_id' => $response->serviceTemplateId,
'check_timeperiod_id' => $response->checkTimePeriodId,
'check_command_id' => $response->commandId,
'check_command_args' => $response->commandArguments,
'max_check_attempts' => $response->maxCheckAttempts,
'normal_check_interval' => $response->normalCheckInterval,
'retry_check_interval' => $response->retryCheckInterval,
'note' => $response->note,
'note_url' => $response->noteUrl,
'action_url' => $response->actionUrl,
'icon_id' => $response->iconId,
'severity_id' => $response->severityId,
'host_templates' => $response->hostTemplateIds,
'is_locked' => $response->isLocked,
'categories' => array_map(fn ($category): array => [
'id' => $category['id'],
'name' => $category['name'],
], $response->categories),
'macros' => array_map(fn (MacroDto $macro): array => [
'name' => $macro->name,
// Note: do not handle vault storage at the moment
'value' => $macro->isPassword ? null : $macro->value,
'is_password' => $macro->isPassword,
'description' => $macro->description,
], $response->macros),
'groups' => array_map(fn ($group): array => [
'id' => $group['serviceGroupId'],
'name' => $group['serviceGroupName'],
'host_template_id' => $group['hostTemplateId'],
'host_template_name' => $group['hostTemplateName'],
], $response->groups),
]
)
);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Infrastructure/API/DeleteServiceTemplate/DeleteServiceTemplateController.php | centreon/src/Core/ServiceTemplate/Infrastructure/API/DeleteServiceTemplate/DeleteServiceTemplateController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Infrastructure\API\DeleteServiceTemplate;
use Centreon\Application\Controller\AbstractController;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\ServiceTemplate\Application\UseCase\DeleteServiceTemplate\DeleteServiceTemplate;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class DeleteServiceTemplateController extends AbstractController
{
/**
* @param DeleteServiceTemplate $useCase
* @param DefaultPresenter $presenter
* @param int $serviceTemplateId
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
DeleteServiceTemplate $useCase,
DefaultPresenter $presenter,
int $serviceTemplateId,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($serviceTemplateId, $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/ServiceTemplate/Infrastructure/API/FindServiceTemplates/FindServiceTemplatesOnPremPresenter.php | centreon/src/Core/ServiceTemplate/Infrastructure/API/FindServiceTemplates/FindServiceTemplatesOnPremPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Infrastructure\API\FindServiceTemplates;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Infrastructure\Common\Presenter\PresenterTrait;
use Core\ServiceTemplate\Application\UseCase\FindServiceTemplates\FindServiceTemplateResponse;
use Core\ServiceTemplate\Application\UseCase\FindServiceTemplates\FindServiceTemplatesPresenterInterface;
use Core\ServiceTemplate\Infrastructure\Model\NotificationTypeConverter;
use Core\ServiceTemplate\Infrastructure\Model\YesNoDefaultConverter;
class FindServiceTemplatesOnPremPresenter extends AbstractPresenter implements FindServiceTemplatesPresenterInterface
{
use PresenterTrait;
public function __construct(
private readonly RequestParametersInterface $requestParameters,
protected PresenterFormatterInterface $presenterFormatter,
) {
parent::__construct($presenterFormatter);
}
/**
* @param ResponseStatusInterface|FindServiceTemplateResponse $response
*/
public function presentResponse(ResponseStatusInterface|FindServiceTemplateResponse $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
$result = [];
foreach ($response->serviceTemplates as $dto) {
$result[] = [
'id' => $dto->id,
'name' => $dto->name,
'alias' => $dto->alias,
'comment' => $dto->comment,
'service_template_id' => $dto->serviceTemplateId,
'check_command_id' => $dto->commandId,
'check_command_args' => $dto->commandArguments,
'check_timeperiod_id' => $dto->checkTimePeriodId,
'max_check_attempts' => $dto->maxCheckAttempts,
'normal_check_interval' => $dto->normalCheckInterval,
'retry_check_interval' => $dto->retryCheckInterval,
'active_check_enabled' => YesNoDefaultConverter::toInt($dto->activeChecks),
'passive_check_enabled' => YesNoDefaultConverter::toInt($dto->passiveCheck),
'volatility_enabled' => YesNoDefaultConverter::toInt($dto->volatility),
'notification_enabled' => YesNoDefaultConverter::toInt($dto->notificationsEnabled),
'is_contact_additive_inheritance' => $dto->isContactAdditiveInheritance,
'is_contact_group_additive_inheritance' => $dto->isContactGroupAdditiveInheritance,
'notification_interval' => $dto->notificationInterval,
'notification_timeperiod_id' => $dto->notificationTimePeriodId,
'notification_type' => NotificationTypeConverter::toBits($dto->notificationTypes),
'first_notification_delay' => $dto->firstNotificationDelay,
'recovery_notification_delay' => $dto->recoveryNotificationDelay,
'acknowledgement_timeout' => $dto->acknowledgementTimeout,
'freshness_checked' => YesNoDefaultConverter::toInt($dto->checkFreshness),
'freshness_threshold' => $dto->freshnessThreshold,
'flap_detection_enabled' => YesNoDefaultConverter::toInt($dto->flapDetectionEnabled),
'low_flap_threshold' => $dto->lowFlapThreshold,
'high_flap_threshold' => $dto->highFlapThreshold,
'event_handler_enabled' => YesNoDefaultConverter::toInt($dto->eventHandlerEnabled),
'event_handler_command_id' => $dto->eventHandlerId,
'event_handler_command_args' => $dto->eventHandlerArguments,
'graph_template_id' => $dto->graphTemplateId,
'note' => $dto->note,
'note_url' => $dto->noteUrl,
'action_url' => $dto->actionUrl,
'icon_id' => $dto->iconId,
'icon_alternative' => $dto->iconAlternativeText,
'severity_id' => $dto->severityId,
'host_templates' => $dto->hostTemplateIds,
'is_locked' => $dto->isLocked,
];
}
$this->present([
'result' => $result,
'meta' => $this->requestParameters->toArray(),
]);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Infrastructure/API/FindServiceTemplates/FindServiceTemplatesSaasPresenter.php | centreon/src/Core/ServiceTemplate/Infrastructure/API/FindServiceTemplates/FindServiceTemplatesSaasPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Infrastructure\API\FindServiceTemplates;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Infrastructure\Common\Presenter\PresenterTrait;
use Core\ServiceTemplate\Application\UseCase\FindServiceTemplates\FindServiceTemplateResponse;
use Core\ServiceTemplate\Application\UseCase\FindServiceTemplates\FindServiceTemplatesPresenterInterface;
class FindServiceTemplatesSaasPresenter extends AbstractPresenter implements FindServiceTemplatesPresenterInterface
{
use PresenterTrait;
public function __construct(
private readonly RequestParametersInterface $requestParameters,
protected PresenterFormatterInterface $presenterFormatter,
) {
parent::__construct($presenterFormatter);
}
public function presentResponse(ResponseStatusInterface|FindServiceTemplateResponse $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
$result = [];
foreach ($response->serviceTemplates as $dto) {
$result[] = [
'id' => $dto->id,
'name' => $dto->name,
'alias' => $dto->alias,
'service_template_id' => $dto->serviceTemplateId,
'check_timeperiod_id' => $dto->checkTimePeriodId,
'max_check_attempts' => $dto->maxCheckAttempts,
'normal_check_interval' => $dto->normalCheckInterval,
'retry_check_interval' => $dto->retryCheckInterval,
'icon_id' => $dto->iconId,
'note' => $dto->note,
'note_url' => $dto->noteUrl,
'action_url' => $dto->actionUrl,
'severity_id' => $dto->severityId,
'host_templates' => $dto->hostTemplateIds,
'is_locked' => $dto->isLocked,
];
}
$this->present([
'result' => $result,
'meta' => $this->requestParameters->toArray(),
]);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceTemplate/Infrastructure/API/FindServiceTemplates/FindServiceTemplatesController.php | centreon/src/Core/ServiceTemplate/Infrastructure/API/FindServiceTemplates/FindServiceTemplatesController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceTemplate\Infrastructure\API\FindServiceTemplates;
use Centreon\Application\Controller\AbstractController;
use Core\ServiceTemplate\Application\UseCase\FindServiceTemplates\FindServiceTemplates;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class FindServiceTemplatesController extends AbstractController
{
/**
* @param FindServiceTemplates $useCase
* @param FindServiceTemplatesOnPremPresenter $onPremPresenter
* @param FindServiceTemplatesSaasPresenter $saasPresenter
* @param bool $isCloudPlatform
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
FindServiceTemplates $useCase,
FindServiceTemplatesOnPremPresenter $onPremPresenter,
FindServiceTemplatesSaasPresenter $saasPresenter,
bool $isCloudPlatform,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
$presenter = $isCloudPlatform ? $saasPresenter : $onPremPresenter;
$useCase($presenter);
return $presenter->show();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Contact/Application/UseCase/FindContactTemplates/FindContactTemplatesPresenterInterface.php | centreon/src/Core/Contact/Application/UseCase/FindContactTemplates/FindContactTemplatesPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Contact\Application\UseCase\FindContactTemplates;
use Core\Application\Common\UseCase\PresenterInterface;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface FindContactTemplatesPresenterInterface extends PresenterInterface
{
/**
* @param ResponseStatusInterface|FindContactTemplatesResponse $response
*/
public function presentResponse(ResponseStatusInterface|FindContactTemplatesResponse $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/Contact/Application/UseCase/FindContactTemplates/FindContactTemplates.php | centreon/src/Core/Contact/Application/UseCase/FindContactTemplates/FindContactTemplates.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Contact\Application\UseCase\FindContactTemplates;
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\Common\Domain\Exception\RepositoryException;
use Core\Contact\Application\Exception\ContactTemplateException;
use Core\Contact\Application\Repository\ReadContactTemplateRepositoryInterface;
class FindContactTemplates
{
use LoggerTrait;
/**
* @param ReadContactTemplateRepositoryInterface $repository
* @param ContactInterface $user
*/
public function __construct(
readonly private ReadContactTemplateRepositoryInterface $repository,
readonly private ContactInterface $user,
) {
}
/**
* @param FindContactTemplatesPresenterInterface $presenter
*/
public function __invoke(FindContactTemplatesPresenterInterface $presenter): void
{
try {
if (
! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_CONTACT_TEMPLATES_READ)
&& ! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_CONTACT_TEMPLATES_READ_WRITE)
) {
$presenter->presentResponse(
new ForbiddenResponse(ContactTemplateException::listingNotAllowed())
);
return;
}
$presenter->presentResponse(new FindContactTemplatesResponse($this->repository->findAll()));
} catch (RepositoryException $exception) {
$presenter->presentResponse(
new ErrorResponse(
ContactTemplateException::errorWhileSearchingForContactTemplate(),
['user_id' => $this->user->getId()],
$exception
)
);
return;
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Contact/Application/UseCase/FindContactTemplates/FindContactTemplatesResponse.php | centreon/src/Core/Contact/Application/UseCase/FindContactTemplates/FindContactTemplatesResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Contact\Application\UseCase\FindContactTemplates;
use Core\Contact\Domain\Model\ContactTemplate;
final class FindContactTemplatesResponse
{
/** @var array<array<string,string|int>> */
public array $contactTemplates;
/**
* @param array<ContactTemplate> $contactTemplates
*/
public function __construct(array $contactTemplates)
{
$this->contactTemplates = $this->contactTemplatesToArray($contactTemplates);
}
/**
* @param array<ContactTemplate> $contactTemplates
*
* @return array<array<string,string|int>>
*/
private function contactTemplatesToArray(array $contactTemplates): array
{
return array_map(
fn (ContactTemplate $contactTemplate) => [
'id' => $contactTemplate->getId(),
'name' => $contactTemplate->getName(),
],
$contactTemplates
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Contact/Application/UseCase/FindContactGroups/FindContactGroupsPresenterInterface.php | centreon/src/Core/Contact/Application/UseCase/FindContactGroups/FindContactGroupsPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Contact\Application\UseCase\FindContactGroups;
use Core\Application\Common\UseCase\PresenterInterface;
interface FindContactGroupsPresenterInterface extends PresenterInterface
{
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Contact/Application/UseCase/FindContactGroups/FindContactGroupsResponse.php | centreon/src/Core/Contact/Application/UseCase/FindContactGroups/FindContactGroupsResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Contact\Application\UseCase\FindContactGroups;
use Core\Contact\Domain\Model\ContactGroup;
use Core\Contact\Domain\Model\ContactGroupType;
final class FindContactGroupsResponse
{
/** @var array<array<string,string|int|bool>> */
public array $contactGroups;
/**
* @param array<ContactGroup> $contactGroups
*/
public function __construct(array $contactGroups)
{
$this->contactGroups = $this->contactGroupsToArray($contactGroups);
}
/**
* @param array<ContactGroup> $contactGroups
*
* @return array<array<string,string|int|bool>>
*/
private function contactGroupsToArray(array $contactGroups): array
{
return array_map(
fn (ContactGroup $contactGroup) => [
'id' => $contactGroup->getId(),
'name' => $contactGroup->getName(),
'alias' => $contactGroup->getAlias(),
'comments' => $contactGroup->getComments(),
'type' => $contactGroup->getType() === ContactGroupType::Local
? 'local'
: 'ldap',
'is_activated' => $contactGroup->isActivated(),
],
$contactGroups
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Contact/Application/UseCase/FindContactGroups/FindContactGroups.php | centreon/src/Core/Contact/Application/UseCase/FindContactGroups/FindContactGroups.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Contact\Application\UseCase\FindContactGroups;
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\Contact\Application\Exception\ContactGroupException;
use Core\Contact\Application\Repository\ReadContactGroupRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
class FindContactGroups
{
use LoggerTrait;
public const AUTHORIZED_ACL_GROUPS = 'customer_admin_acl';
public function __construct(
private readonly ReadAccessGroupRepositoryInterface $accessGroupRepository,
private readonly ReadContactGroupRepositoryInterface $contactGroupRepository,
private readonly ContactInterface $user,
private readonly RequestParametersInterface $requestParameters,
private readonly bool $isCloudPlatform,
) {
}
/**
* @param FindContactGroupsPresenterInterface $presenter
*/
public function __invoke(FindContactGroupsPresenterInterface $presenter): void
{
try {
$this->info('Find contact groups', ['user' => $this->user->getName()]);
if ($this->isUserAdmin()) {
$contactGroups = $this->contactGroupRepository->findAll($this->requestParameters);
$presenter->present(new FindContactGroupsResponse($contactGroups));
} elseif ($this->contactCanExecuteThisUseCase()) {
$accessGroups = $this->accessGroupRepository->findByContact($this->user);
$contactGroups = $this->contactGroupRepository->findByAccessGroupsAndUserAndRequestParameter(
$accessGroups,
$this->user,
$this->requestParameters
);
$presenter->present(new FindContactGroupsResponse($contactGroups));
} else {
$this->error('User doesn\'t have sufficient right to see contact groups', [
'user_id' => $this->user->getId(),
]);
$presenter->setResponseStatus(
new ForbiddenResponse(
ContactGroupException::notAllowed()->getMessage()
)
);
return;
}
} catch (\Throwable $ex) {
$this->error(
'An error occured in data storage while getting contact groups',
['trace' => $ex->getTraceAsString()]
);
$presenter->setResponseStatus(
new ErrorResponse(
ContactGroupException::errorWhileSearchingForContactGroups()->getMessage()
)
);
return;
}
}
/**
* @throws \Throwable
*
* @return bool
*/
private function isUserAdmin(): bool
{
if ($this->user->isAdmin()) {
return true;
}
// this is only true on Cloud context
$userAccessGroupNames = array_map(
static fn (AccessGroup $accessGroup): string => $accessGroup->getName(),
$this->accessGroupRepository->findByContact($this->user)
);
return $this->isCloudPlatform === true && in_array(self::AUTHORIZED_ACL_GROUPS, $userAccessGroupNames, true);
}
/**
* @return bool
*/
private function contactCanExecuteThisUseCase(): bool
{
// The use case can be executed onPrem is user has access to the pages.
// On Cloud context user does not have access to those pages so he can execute the use case in any case.
return $this->isCloudPlatform === true
|| $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_USERS_CONTACT_GROUPS_READ)
|| $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_USERS_CONTACT_GROUPS_READ_WRITE);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Contact/Application/Exception/ContactGroupException.php | centreon/src/Core/Contact/Application/Exception/ContactGroupException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Contact\Application\Exception;
class ContactGroupException extends \Exception
{
public static function errorWhileSearchingForContactGroups(): self
{
return new self(_('Impossible to get contact groups from data storage'));
}
public static function notAllowed(): self
{
return new self(_('You are not allowed to access contact groups'));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Contact/Application/Exception/ContactTemplateException.php | centreon/src/Core/Contact/Application/Exception/ContactTemplateException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Contact\Application\Exception;
class ContactTemplateException extends \Exception
{
public static function errorWhileSearchingForContactTemplate(): self
{
return new self(_('Error while searching for contact templates'));
}
public static function listingNotAllowed(): self
{
return new self(_('You are not allowed to list contact templates'));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Contact/Application/Repository/ReadContactRepositoryInterface.php | centreon/src/Core/Contact/Application/Repository/ReadContactRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Contact\Application\Repository;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Contact\Domain\Model\BasicContact;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
interface ReadContactRepositoryInterface
{
/**
* Find contact names by IDs.
*
* @param int ...$ids
*
* @throws RepositoryException
*
* @return array<int, array{id: int, name: string}>
*/
public function findNamesByIds(int ...$ids): array;
/**
* Find contact alias by IDs.
*
* @param int ...$ids
*
* @throws RepositoryException
*
* @return array<int, array{id: int, alias: string}>
*/
public function findAliasesByIds(int ...$ids): array;
/**
* Check user existence by its id.
*
* @param int $userId
*
* @throws \Throwable
*
* @return bool
*/
public function exists(int $userId): bool;
/**
* Check existence of provided users
* Return an array of the existing user IDs out of the provided ones.
*
* @param int[] $userIds
*
* @return int[]
*/
public function exist(array $userIds): array;
/**
* Find contact_ids link to given contactGroups.
*
* @param int[] $contactGroupIds
*
* @return int[]
*/
public function findContactIdsByContactGroups(array $contactGroupIds): array;
/**
* Checks if in an user exists in given access groups.
*
* @param int $contactId
* @param int[] $accessGroupIds
*
* @throws \Throwable
*
* @return bool
*/
public function existInAccessGroups(int $contactId, array $accessGroupIds): bool;
/**
* Find contact IDs member of given access groups.
*
* @param int[] $accessGroupIds
*
* @return int[]
*/
public function findContactIdsByAccessGroups(array $accessGroupIds): array;
/**
* @param RequestParametersInterface $requestParameters
*
* @throws \Throwable
*
* @return Contact[]
*/
public function findAdminWithRequestParameters(RequestParametersInterface $requestParameters): array;
/**
* Retrieve admins based on given IDs.
*
* @param int[] $contactIds
*
* @throws \Throwable
*
* @return Contact[]
*/
public function findAdminsByIds(array $contactIds): array;
/**
* Retrieve contacts based on given IDs.
*
* @param int[] $contactIds
*
* @throws \Throwable
*
* @return BasicContact[]
*/
public function findByIds(array $contactIds): array;
/**
* Check existence of provided contacts
* Return an array of the existing user IDs out of the provided ones.
*
* @param int[] $contactIds
*
* @return int[]
*/
public function retrieveExistingContactIds(array $contactIds): array;
/**
* Find contact ids by access groups.
*
* @param AccessGroup[] $accessGroups
*
* @return BasicContact[]
*/
public function findByAccessGroup(array $accessGroups): array;
/**
* Finds all contacts that the contact can see based on contacts and contact groups
* defined in ACL groups filtered by access groups.
* As well as all the contacts in the contact groups to which he belongs.
*
* @param AccessGroup[] $accessGroups
* @param ContactInterface $user
* @param ?RequestParametersInterface $requestParameters
*
* @throws \Throwable
*
* @return BasicContact[]
*/
public function findByAccessGroupsAndUserAndRequestParameters(
array $accessGroups,
ContactInterface $user,
?RequestParametersInterface $requestParameters = null,
): array;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Contact/Application/Repository/ReadContactGroupRepositoryInterface.php | centreon/src/Core/Contact/Application/Repository/ReadContactGroupRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Contact\Application\Repository;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Contact\Domain\Model\ContactGroup;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
interface ReadContactGroupRepositoryInterface
{
/**
* Get all contact groups.
*
* @param RequestParametersInterface|null $requestParameters
*
* @throws \Throwable
*
* @return array<ContactGroup>
*/
public function findAll(?RequestParametersInterface $requestParameters = null): array;
/**
* Get all contact groups of a contact.
*
* @param int $userId
*
* @throws \Throwable
*
* @return array<ContactGroup>
*/
public function findAllByUserId(int $userId): array;
/**
* Get a Contact Group.
*
* @param int $contactGroupId
*
* @throws \Throwable
*
* @return ContactGroup|null
*/
public function find(int $contactGroupId): ?ContactGroup;
/**
* Get Contact groups by their ids.
*
* @param int[] $contactGroupIds
*
* @throws \Throwable
*
* @return ContactGroup[]
*/
public function findByIds(array $contactGroupIds): array;
/**
* Get Contact groups by access groups, user and request parameters.
*
* Be careful, it will return contact groups that are in the access groups
* and the contact groups of the user.
*
* @param AccessGroup[] $accessGroups
* @param ContactInterface $user
* @param RequestParametersInterface|null $requestParameters
*
* @return ContactGroup[]
*/
public function findByAccessGroupsAndUserAndRequestParameter(
array $accessGroups,
ContactInterface $user,
?RequestParametersInterface $requestParameters = null,
): array;
/**
* Check existence of provided contact groups.
* Return an array of the existing contact group IDs out of the provided ones.
*
* @param int[] $contactGroupIds
*
* @return int[]
*/
public function exist(array $contactGroupIds): array;
/**
* Check that the contact group ID provided exists.
*
* @param int $contactGroupId
*
* @return bool
*/
public function exists(int $contactGroupId): bool;
/**
* @param int $contactGroupId
* @param int[] $accessGroupIds
*
* @return bool
*/
public function existsInAccessGroups(int $contactGroupId, array $accessGroupIds): bool;
/**
* Find contact group names by IDs.
*
* @param int ...$ids
*
* @throws RepositoryException
*
* @return array<int, array{id: int, name: string}>
*/
public function findNamesByIds(int ...$ids): array;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Contact/Application/Repository/ReadContactTemplateRepositoryInterface.php | centreon/src/Core/Contact/Application/Repository/ReadContactTemplateRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Contact\Application\Repository;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Contact\Domain\Model\ContactTemplate;
interface ReadContactTemplateRepositoryInterface
{
/**
* Get all contact templates.
*
* @throws RepositoryException
* @return array<ContactTemplate>
*/
public function findAll(): array;
/**
* Find a contact template by id.
*
* @param int $id
*
* @throws RepositoryException
* @return ContactTemplate|null
*/
public function find(int $id): ?ContactTemplate;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Contact/Application/Repository/WriteContactGroupRepositoryInterface.php | centreon/src/Core/Contact/Application/Repository/WriteContactGroupRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Contact\Application\Repository;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Contact\Domain\Model\ContactGroup;
interface WriteContactGroupRepositoryInterface
{
/**
* Delete all contact groups for a given user.
*
* @param ContactInterface $user
*/
public function deleteContactGroupsForUser(ContactInterface $user): void;
/**
* Insert a contact group for a given user.
*
* @param ContactInterface $user
* @param ContactGroup $contactGroup
*/
public function insertContactGroupForUser(ContactInterface $user, ContactGroup $contactGroup): 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/Contact/Domain/AdminResolver.php | centreon/src/Core/Contact/Domain/AdminResolver.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Core\Contact\Domain;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
/**
* This service allows to determine if a contact is admin or not.
* It would probably be better to add this logic to the Contact model but
* for now we keep it that way to avoid touching too many things.
*/
class AdminResolver
{
public function __construct(
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly bool $isCloudPlatform,
) {
}
public function isAdmin(ContactInterface $contact): bool
{
if ($contact->isAdmin()) {
return true;
}
if (! $this->isCloudPlatform) {
return false;
}
// In cloud platform, check if user has customer_admin_acl
$accessGroups = $this->readAccessGroupRepository->findByContact($contact);
$accessGroupNames = array_map(
fn (AccessGroup $accessGroup): string => $accessGroup->getName(),
$accessGroups
);
return in_array('customer_admin_acl', $accessGroupNames, 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/Contact/Domain/Model/ContactGroup.php | centreon/src/Core/Contact/Domain/Model/ContactGroup.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Contact\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
class ContactGroup
{
/**
* @param int $id
* @param string $name
* @param string $alias
* @param string $comments
* @param bool $isActivated
* @param ContactGroupType $type
*
* @throws AssertionFailedException
*/
public function __construct(
private readonly int $id,
private readonly string $name,
private readonly string $alias,
private readonly string $comments = '',
private readonly bool $isActivated = true,
private readonly ContactGroupType $type = ContactGroupType::Local,
) {
Assertion::notEmpty($name, 'ContactGroup::name');
Assertion::notEmpty($alias, 'ContactGroup::alias');
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
public function getAlias(): string
{
return $this->alias;
}
public function getComments(): string
{
return $this->comments;
}
public function isActivated(): bool
{
return $this->isActivated;
}
public function getType(): ContactGroupType
{
return $this->type;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Contact/Domain/Model/ContactGroupType.php | centreon/src/Core/Contact/Domain/Model/ContactGroupType.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Contact\Domain\Model;
enum ContactGroupType
{
case Local;
case Ldap;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Contact/Domain/Model/ContactTemplate.php | centreon/src/Core/Contact/Domain/Model/ContactTemplate.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Contact\Domain\Model;
class ContactTemplate
{
/**
* @param int $id
* @param string $name
*/
public function __construct(
private int $id,
private string $name,
) {
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Contact/Domain/Model/BasicContact.php | centreon/src/Core/Contact/Domain/Model/BasicContact.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Contact\Domain\Model;
use Core\Common\Domain\NotEmptyString;
use Core\Common\Domain\PositiveInteger;
class BasicContact
{
public function __construct(
private readonly PositiveInteger $id,
private readonly NotEmptyString $name,
private readonly NotEmptyString $alias,
private readonly NotEmptyString $email,
private readonly bool $isAdmin,
private readonly bool $isActive,
) {
}
public function getId(): int
{
return $this->id->getValue();
}
public function getName(): string
{
return (string) $this->name;
}
public function getAlias(): string
{
return (string) $this->alias;
}
public function getEmail(): string
{
return (string) $this->email;
}
public function isAdmin(): bool
{
return $this->isAdmin;
}
public function isActive(): bool
{
return $this->isActive;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Contact/Infrastructure/Api/FindContactTemplates/FindContactTemplatesController.php | centreon/src/Core/Contact/Infrastructure/Api/FindContactTemplates/FindContactTemplatesController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Contact\Infrastructure\Api\FindContactTemplates;
use Centreon\Application\Controller\AbstractController;
use Core\Contact\Application\UseCase\FindContactTemplates\{
FindContactTemplates,
FindContactTemplatesPresenterInterface
};
final class FindContactTemplatesController extends AbstractController
{
/**
* @param FindContactTemplates $useCase
* @param FindContactTemplatesPresenterInterface $presenter
*
* @return object
*/
public function __invoke(FindContactTemplates $useCase, FindContactTemplatesPresenterInterface $presenter): object
{
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($presenter);
return $presenter->show();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Contact/Infrastructure/Api/FindContactTemplates/FindContactTemplatesPresenter.php | centreon/src/Core/Contact/Infrastructure/Api/FindContactTemplates/FindContactTemplatesPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Contact\Infrastructure\Api\FindContactTemplates;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Common\Infrastructure\ExceptionLogger\ExceptionLogger;
use Core\Contact\Application\UseCase\FindContactTemplates\{FindContactTemplatesPresenterInterface,
FindContactTemplatesResponse};
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
class FindContactTemplatesPresenter extends AbstractPresenter implements FindContactTemplatesPresenterInterface
{
use LoggerTrait;
/**
* @param RequestParametersInterface $requestParameters
* @param PresenterFormatterInterface $presenterFormatter
* @param ContactInterface $user
* @param ExceptionLogger $exceptionLogger
*/
public function __construct(
private RequestParametersInterface $requestParameters,
protected PresenterFormatterInterface $presenterFormatter,
private readonly ContactInterface $user,
private readonly ExceptionLogger $exceptionLogger,
) {
parent::__construct($presenterFormatter);
}
/**
* @param FindContactTemplatesResponse|ResponseStatusInterface $response
*/
public function presentResponse(ResponseStatusInterface|FindContactTemplatesResponse $response): void
{
if ($response instanceof ResponseStatusInterface) {
if ($response instanceof ErrorResponse && ! is_null($response->getException())) {
$this->exceptionLogger->log($response->getException());
} elseif ($response instanceof ForbiddenResponse) {
$this->error('User doesn\'t have sufficient rights to list contact templates', [
'user_id' => $this->user->getId(),
]);
}
$this->setResponseStatus($response);
return;
}
$this->present([
'result' => $response->contactTemplates,
'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/Contact/Infrastructure/Api/FindContactGroups/FindContactGroupsPresenter.php | centreon/src/Core/Contact/Infrastructure/Api/FindContactGroups/FindContactGroupsPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Contact\Infrastructure\Api\FindContactGroups;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Contact\Application\UseCase\FindContactGroups\{
FindContactGroupsPresenterInterface,
FindContactGroupsResponse
};
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
class FindContactGroupsPresenter extends AbstractPresenter implements FindContactGroupsPresenterInterface
{
/**
* @param RequestParametersInterface $requestParameters
* @param PresenterFormatterInterface $presenterFormatter
*/
public function __construct(
private readonly RequestParametersInterface $requestParameters,
protected PresenterFormatterInterface $presenterFormatter,
) {
}
/**
* @param FindContactGroupsResponse $presentedData
*/
public function present(mixed $presentedData): void
{
parent::present([
'result' => $presentedData->contactGroups,
'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/Contact/Infrastructure/Api/FindContactGroups/FindContactGroupsController.php | centreon/src/Core/Contact/Infrastructure/Api/FindContactGroups/FindContactGroupsController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Contact\Infrastructure\Api\FindContactGroups;
use Centreon\Application\Controller\AbstractController;
use Core\Contact\Application\UseCase\FindContactGroups\{
FindContactGroups,
FindContactGroupsPresenterInterface
};
final class FindContactGroupsController extends AbstractController
{
/**
* @param FindContactGroups $useCase
* @param FindContactGroupsPresenterInterface $presenter
*
* @return object
*/
public function __invoke(FindContactGroups $useCase, FindContactGroupsPresenterInterface $presenter): object
{
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($presenter);
return $presenter->show();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Contact/Infrastructure/Repository/DbReadContactGroupRepository.php | centreon/src/Core/Contact/Infrastructure/Repository/DbReadContactGroupRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Contact\Infrastructure\Repository;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait;
use Core\Common\Infrastructure\RequestParameters\Normalizer\BoolToEnumNormalizer;
use Core\Contact\Application\Repository\ReadContactGroupRepositoryInterface;
use Core\Contact\Domain\Model\ContactGroup;
/**
* @phpstan-type _ContactGroup array{
* cg_id: int,
* cg_name: string,
* cg_alias: string,
* cg_comment?: string,
* cg_activate: string,
* cg_type: string
* }
*/
class DbReadContactGroupRepository extends AbstractRepositoryDRB implements ReadContactGroupRepositoryInterface
{
use LoggerTrait;
use SqlMultipleBindTrait;
/** @var SqlRequestParametersTranslator */
private SqlRequestParametersTranslator $sqlRequestTranslator;
/**
* @param DatabaseConnection $db
* @param SqlRequestParametersTranslator $sqlRequestTranslator
*/
public function __construct(DatabaseConnection $db, SqlRequestParametersTranslator $sqlRequestTranslator)
{
$this->db = $db;
$this->sqlRequestTranslator = $sqlRequestTranslator;
$this->sqlRequestTranslator
->getRequestParameters()
->setConcordanceStrictMode(RequestParameters::CONCORDANCE_MODE_STRICT);
$this->sqlRequestTranslator->setConcordanceArray([
'id' => 'cg_id',
'name' => 'cg_name',
]);
}
/**
* @inheritDoc
*/
public function exists(int $contactGroupId): bool
{
$request = $this->translateDbName(
<<<'SQL'
SELECT 1 FROM `:db`.contactgroup
WHERE cg_id = :contactGroupId
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':contactGroupId', $contactGroupId, \PDO::PARAM_INT);
$statement->execute();
return (bool) $statement->fetchColumn();
}
public function existsInAccessGroups(int $contactGroupId, array $accessGroupIds): bool
{
$bind = [];
foreach ($accessGroupIds as $key => $accessGroupId) {
$bind[':access_group_' . $key] = $accessGroupId;
}
if ($bind === []) {
return false;
}
$accessGroupIdsAsString = implode(',', array_keys($bind));
$statement = $this->db->prepare($this->translateDbName(
<<<SQL
SELECT 1
FROM `:db`.contactgroup cg
INNER JOIN `:db`.acl_group_contactgroups_relations gcgr
ON cg.cg_id = gcgr.cg_cg_id
WHERE cg.cg_id = :contactGroupId
AND gcgr.acl_group_id IN ({$accessGroupIdsAsString})
SQL
));
$statement->bindValue(':contactGroupId', $contactGroupId, \PDO::PARAM_INT);
foreach ($bind as $token => $accessGroupId) {
$statement->bindValue($token, $accessGroupId, \PDO::PARAM_INT);
}
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* @inheritDoc
*/
public function findNamesByIds(int ...$ids): array
{
try {
if ($ids === []) {
return [];
}
$ids = array_unique($ids);
$fields = '';
foreach ($ids as $index => $id) {
$fields .= ($fields === '' ? '' : ', ') . ':id_' . $index;
}
$select = <<<SQL
SELECT
`cg_id` as `id`,
`cg_name` as `name`
FROM
`:db`.`contactgroup`
WHERE
`cg_id` IN ({$fields})
SQL;
$statement = $this->db->prepare($this->translateDbName($select));
foreach ($ids as $index => $id) {
$statement->bindValue(':id_' . $index, $id, \PDO::PARAM_INT);
}
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
// Retrieve data
$names = [];
foreach ($statement as $result) {
/** @var array{ id: int, name: string } $result */
$names[$result['id']] = $result;
}
return $names;
} catch (\PDOException $e) {
throw new RepositoryException(
message: 'An error occurred while retrieving contact group names by IDs',
context: ['ids' => $ids],
previous: $e
);
}
}
/**
* @inheritDoc
*/
public function findAll(?RequestParametersInterface $requestParameters = null): array
{
$request = <<<'SQL_WRAP'
SELECT SQL_CALC_FOUND_ROWS
cg_id, cg_name, cg_alias, cg_comment, cg_activate, cg_type
FROM `:db`.contactgroup
SQL_WRAP;
$sqlTranslator = $requestParameters !== null
? new SqlRequestParametersTranslator($requestParameters)
: null;
$sqlTranslator?->setConcordanceArray([
'id' => 'cg_id',
'name' => 'cg_name',
'alias' => 'cg_alias',
'type' => 'cg_type',
'comments' => 'cg_comment',
'is_activated' => 'cg_activate',
]);
$sqlTranslator?->addNormalizer('is_activated', new BoolToEnumNormalizer());
// Search
$request .= $sqlTranslator?->translateSearchParameterToSql();
// Sort
$sortRequest = $sqlTranslator?->translateSortParameterToSql();
$request .= ! is_null($sortRequest)
? $sortRequest
: ' ORDER BY cg_id ASC';
// Pagination
$request .= $sqlTranslator?->translatePaginationToSql();
$statement = $this->db->prepare($this->translateDbName($request));
if ($sqlTranslator !== null) {
foreach ($sqlTranslator->getSearchValues() as $key => $data) {
$type = (int) key($data);
$value = $data[$type];
$statement->bindValue($key, $value, $type);
}
}
$statement->execute();
$sqlTranslator?->calculateNumberOfRows($this->db);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$contactGroups = [];
foreach ($statement as $result) {
/** @var _ContactGroup $result */
$contactGroups[] = DbContactGroupFactory::createFromRecord($result);
}
return $contactGroups;
}
/**
* @inheritDoc
*/
public function findAllByUserId(int $userId): array
{
$request = <<<'SQL_WRAP'
SELECT SQL_CALC_FOUND_ROWS
cg_id, cg_name, cg_alias, cg_comment, cg_activate, cg_type
FROM `:db`.contactgroup cg
INNER JOIN `:db`.contactgroup_contact_relation ccr
ON ccr.contactgroup_cg_id = cg.cg_id
SQL_WRAP;
// Search
$searchRequest = $this->sqlRequestTranslator->translateSearchParameterToSql();
$request .= $searchRequest !== null
? $searchRequest . ' AND '
: ' WHERE ';
$request .= "ccr.contact_contact_id = :userId AND cg_activate = '1'";
// Sort
$sortRequest = $this->sqlRequestTranslator->translateSortParameterToSql();
$request .= $sortRequest ?? ' ORDER BY cg_id ASC';
// Pagination
$request .= $this->sqlRequestTranslator->translatePaginationToSql();
$statement = $this->db->prepare($this->translateDbName($request));
foreach ($this->sqlRequestTranslator->getSearchValues() as $key => $data) {
/**
* @var int
*/
$type = key($data);
$value = $data[$type];
$statement->bindValue($key, $value, $type);
}
$statement->bindValue(':userId', $userId, \PDO::PARAM_INT);
$statement->execute();
// Set total
$result = $this->db->query('SELECT FOUND_ROWS()');
if ($result !== false && ($total = $result->fetchColumn()) !== false) {
$this->sqlRequestTranslator->getRequestParameters()->setTotal((int) $total);
}
$contactGroups = [];
while ($statement !== false && is_array($result = $statement->fetch(\PDO::FETCH_ASSOC))) {
/** @var _ContactGroup $result */
$contactGroups[] = DbContactGroupFactory::createFromRecord($result);
}
return $contactGroups;
}
/**
* @inheritDoc
*/
public function find(int $contactGroupId): ?ContactGroup
{
$this->debug('Getting Contact Group by id', [
'contact_group_id' => $contactGroupId,
]);
$statement = $this->db->prepare(
$this->translateDbName(
<<<'SQL'
SELECT cg_id, cg_name, cg_alias, cg_comment, cg_activate, cg_type
FROM `:db`.contactgroup
WHERE cg_id = :contactGroupId
SQL
)
);
$statement->bindValue(':contactGroupId', $contactGroupId, \PDO::PARAM_INT);
$statement->execute();
$contactGroup = null;
if ($statement !== false && $result = $statement->fetch(\PDO::FETCH_ASSOC)) {
/** @var _ContactGroup $result */
$contactGroup = DbContactGroupFactory::createFromRecord($result);
}
$this->debug(
$contactGroup === null ? 'No Contact Group found' : 'Contact Group Found',
[
'contact_group_id' => $contactGroupId,
]
);
return $contactGroup;
}
/**
* @inheritDoc
*/
public function findByIds(array $contactGroupIds): array
{
$this->debug('Getting Contact Group by Ids', [
'ids' => implode(', ', $contactGroupIds),
]);
$queryBindValues = [];
foreach ($contactGroupIds as $contactGroupId) {
$queryBindValues[':contact_group_' . $contactGroupId] = $contactGroupId;
}
if ($queryBindValues === []) {
return [];
}
$contactGroups = [];
$boundIds = implode(', ', array_keys($queryBindValues));
$statement = $this->db->prepare(
$this->translateDbName(
<<<SQL
SELECT cg_id, cg_name, cg_alias, cg_comment, cg_activate, cg_type
FROM `:db`.contactgroup
WHERE cg_id IN ({$boundIds})
SQL
)
);
foreach ($queryBindValues as $bindKey => $contactGroupId) {
$statement->bindValue($bindKey, $contactGroupId, \PDO::PARAM_INT);
}
$statement->execute();
while ($statement !== false && is_array($result = $statement->fetch(\PDO::FETCH_ASSOC))) {
/** @var _ContactGroup $result */
$contactGroups[] = DbContactGroupFactory::createFromRecord($result);
}
$this->debug('Contact Group found: ' . count($contactGroups));
return $contactGroups;
}
/**
* @inheritDoc
*/
public function findByAccessGroupsAndUserAndRequestParameter(
array $accessGroups,
ContactInterface $user,
?RequestParametersInterface $requestParameters = null,
): array {
$accessGroupIds = array_map(
fn ($accessGroup) => $accessGroup->getId(),
$accessGroups
);
[$bindValues, $subQuery] = $this->createMultipleBindQuery($accessGroupIds, ':id_');
$request = $this->translateDbName(
<<<SQL
SELECT SQL_CALC_FOUND_ROWS *
FROM (
SELECT /* Search for contact groups directly related to the user with ACL groups */
cg_id, cg_name, cg_alias, cg_comment, cg_activate, cg_type
FROM `:db`.acl_group_contactgroups_relations gcgr
INNER JOIN `:db`.contactgroup cg
ON cg.cg_id = gcgr.cg_cg_id
WHERE gcgr.acl_group_id IN ({$subQuery})
GROUP BY cg_id, cg_name, cg_alias, cg_comment, cg_activate, cg_type
UNION
SELECT /* Search for contact groups the user belongs to */
cg_id, cg_name, cg_alias, cg_comment, cg_activate, cg_type
FROM `:db`.contactgroup cg
INNER JOIN `:db`.contactgroup_contact_relation ccr
ON ccr.contactgroup_cg_id = cg.cg_id
INNER JOIN `:db`.contact c
ON c.contact_id = ccr.contact_contact_id
WHERE ccr.contact_contact_id = :user_id
AND c.contact_register = '1'
) AS contact_groups
SQL
);
$sqlTranslator = $requestParameters !== null
? new SqlRequestParametersTranslator($requestParameters)
: null;
$sqlTranslator?->setConcordanceArray([
'id' => 'cg_id',
'name' => 'cg_name',
'alias' => 'cg_alias',
'type' => 'cg_type',
'comments' => 'cg_comment',
'is_activated' => 'cg_activate',
]);
$sqlTranslator?->addNormalizer('is_activated', new BoolToEnumNormalizer());
// Search
if ($search = $sqlTranslator?->translateSearchParameterToSql()) {
$request .= ' WHERE ' . $search;
}
$request .= ' GROUP BY cg_id, cg_name, cg_alias, cg_comment, cg_activate, cg_type';
// Sort
$sortRequest = $sqlTranslator?->translateSortParameterToSql();
$request .= $sortRequest ?? ' ORDER BY cg_id ASC';
// Pagination
$request .= $sqlTranslator?->translatePaginationToSql();
$statement = $this->db->prepare($this->translateDbName($request));
if ($sqlTranslator !== null) {
foreach ($sqlTranslator->getSearchValues() as $key => $data) {
$type = (int) key($data);
$value = $data[$type];
$statement->bindValue($key, $value, $type);
}
}
foreach ($bindValues as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->bindValue(':user_id', $user->getId(), \PDO::PARAM_INT);
$statement->execute();
$sqlTranslator?->calculateNumberOfRows($this->db);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$contactGroups = [];
foreach ($statement as $result) {
/** @var _ContactGroup $result */
$contactGroups[] = DbContactGroupFactory::createFromRecord($result);
}
return $contactGroups;
}
/**
* @inheritDoc
*/
public function exist(array $contactGroupIds): array
{
$bind = [];
foreach ($contactGroupIds as $key => $contactGroupId) {
$bind[":cg_{$key}"] = $contactGroupId;
}
if ($bind === []) {
return [];
}
$contactGroupIdsAsString = implode(', ', array_keys($bind));
$request = $this->translateDbName(
<<<SQL
SELECT cg_id FROM `:db`.contactgroup
WHERE cg_id IN ({$contactGroupIdsAsString})
SQL
);
$statement = $this->db->prepare($request);
foreach ($bind as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->execute();
return $statement->fetchAll(\PDO::FETCH_COLUMN, 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/Contact/Infrastructure/Repository/DbWriteContactGroupRepository.php | centreon/src/Core/Contact/Infrastructure/Repository/DbWriteContactGroupRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Contact\Infrastructure\Repository;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Core\Contact\Application\Repository\WriteContactGroupRepositoryInterface;
use Core\Contact\Domain\Model\ContactGroup;
class DbWriteContactGroupRepository extends AbstractRepositoryDRB implements WriteContactGroupRepositoryInterface
{
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function deleteContactGroupsForUser(ContactInterface $user): void
{
$statement = $this->db->prepare($this->translateDbName(
'DELETE FROM `:db`.contactgroup_contact_relation WHERE contact_contact_id = :userId'
));
$statement->bindValue(':userId', $user->getId(), \PDO::PARAM_INT);
$statement->execute();
}
/**
* @inheritDoc
*/
public function insertContactGroupForUser(ContactInterface $user, ContactGroup $contactGroup): void
{
$statement = $this->db->prepare($this->translateDbName(
'INSERT INTO contactgroup_contact_relation VALUES (:userId, :contactGroupId)'
));
$statement->bindValue(':userId', $user->getId(), \PDO::PARAM_INT);
$statement->bindValue(':contactGroupId', $contactGroup->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/Contact/Infrastructure/Repository/DbReadContactRepository.php | centreon/src/Core/Contact/Infrastructure/Repository/DbReadContactRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Contact\Infrastructure\Repository;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Common\Domain\NotEmptyString;
use Core\Common\Domain\PositiveInteger;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait;
use Core\Contact\Application\Repository\ReadContactRepositoryInterface;
use Core\Contact\Domain\Model\BasicContact;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
/**
* @phpstan-type _ContactRecord array{
* contact_id: int|string,
* contact_alias: string,
* contact_name: string,
* contact_email: string,
* contact_admin: string,
* contact_activate: string,
* }
*/
class DbReadContactRepository extends AbstractRepositoryRDB implements ReadContactRepositoryInterface
{
use LoggerTrait;
use SqlMultipleBindTrait;
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function findNamesByIds(int ...$ids): array
{
try {
if ($ids === []) {
return [];
}
$ids = array_unique($ids);
$fields = '';
foreach ($ids as $index => $id) {
$fields .= ($fields === '' ? '' : ', ') . ':id_' . $index;
}
$select = <<<SQL
SELECT
`contact_id` as `id`,
`contact_name` as `name`
FROM
`:db`.`contact`
WHERE
`contact_id` IN ({$fields})
SQL;
$statement = $this->db->prepare($this->translateDbName($select));
foreach ($ids as $index => $id) {
$statement->bindValue(':id_' . $index, $id, \PDO::PARAM_INT);
}
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
// Retrieve data
$names = [];
foreach ($statement as $result) {
/** @var array{ id: int, name: string } $result */
$names[$result['id']] = $result;
}
return $names;
} catch (\PDOException $e) {
throw new RepositoryException(
message: 'An error occurred while retrieving contact names by IDs.',
context: ['ids' => $ids],
previous: $e
);
}
}
/**
* @inheritDoc
*/
public function findAliasesByIds(int ...$ids): array
{
try {
if ($ids === []) {
return [];
}
$ids = array_unique($ids);
$fields = '';
foreach ($ids as $index => $id) {
$fields .= ($fields === '' ? '' : ', ') . ':id_' . $index;
}
$select = <<<SQL
SELECT
`contact_id` as `id`,
`contact_alias` as `alias`
FROM
`:db`.`contact`
WHERE
`contact_id` IN ({$fields})
SQL;
$statement = $this->db->prepare($this->translateDbName($select));
foreach ($ids as $index => $id) {
$statement->bindValue(':id_' . $index, $id, \PDO::PARAM_INT);
}
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
// Retrieve data
$names = [];
foreach ($statement as $result) {
/** @var array{ id: int, alias: string } $result */
$names[$result['id']] = $result;
}
return $names;
} catch (\PDOException $e) {
throw new RepositoryException(
message: 'An error occurred while retrieving contact names by IDs.',
context: ['ids' => $ids],
previous: $e
);
}
}
/**
* @inheritDoc
*/
public function exists(int $userId): bool
{
$request = $this->translateDbName(
<<<'SQL'
SELECT 1 FROM `:db`.contact
WHERE contact_id = :userId
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':userId', $userId, \PDO::PARAM_INT);
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* @inheritDoc
*/
public function exist(array $userIds): array
{
$bind = [];
foreach ($userIds as $key => $userId) {
$bind[":user_{$key}"] = $userId;
}
if ($bind === []) {
return [];
}
$contactIdsAsString = implode(', ', array_keys($bind));
$request = $this->translateDbName(
<<<SQL
SELECT contact_id FROM `:db`.contact
WHERE contact_id IN ({$contactIdsAsString})
SQL
);
$statement = $this->db->prepare($request);
foreach ($bind as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->execute();
return $statement->fetchAll(\PDO::FETCH_COLUMN, 0);
}
/**
* @inheritDoc
*/
public function findContactIdsByContactGroups(array $contactGroupIds): array
{
$bind = [];
foreach ($contactGroupIds as $key => $contactGroupId) {
$bind[":contactGroup_{$key}"] = $contactGroupId;
}
if ($bind === []) {
return [];
}
$bindAsString = implode(', ', array_keys($bind));
$request = <<<SQL
SELECT
contact_contact_id
FROM
`:db`.`contactgroup_contact_relation` cgcr
WHERE
cgcr.contactgroup_cg_id IN ({$bindAsString})
SQL;
$statement = $this->db->prepare($this->translateDbName($request));
foreach ($bind as $token => $bindValue) {
$statement->bindValue($token, $bindValue, \PDO::PARAM_INT);
}
$statement->execute();
return $statement->fetchAll(\PDO::FETCH_COLUMN, 0);
}
/**
* @inheritDoc
*/
public function existInAccessGroups(int $contactId, array $accessGroupIds): bool
{
$bind = [];
foreach ($accessGroupIds as $key => $accessGroupId) {
$bind[':access_group_' . $key] = $accessGroupId;
}
if ($bind === []) {
return false;
}
$accessGroupIdsAsString = implode(',', array_keys($bind));
$statement = $this->db->prepare($this->translateDbName(
<<<SQL
SELECT 1
FROM `:db`.contact c
LEFT JOIN `:db`.contactgroup_contact_relation ccr
ON c.contact_id = ccr.contact_contact_id
LEFT JOIN `:db`.acl_group_contacts_relations gcr
ON c.contact_id = gcr.contact_contact_id
LEFT JOIN `:db`.acl_group_contactgroups_relations gcgr
ON ccr.contactgroup_cg_id = gcgr.cg_cg_id
WHERE c.contact_id = :contactId
AND (gcr.acl_group_id IN ({$accessGroupIdsAsString})
OR gcgr.acl_group_id IN ({$accessGroupIdsAsString}));
SQL
));
$statement->bindValue(':contactId', $contactId, \PDO::PARAM_INT);
foreach ($bind as $token => $accessGroupId) {
$statement->bindValue($token, $accessGroupId, \PDO::PARAM_INT);
}
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* @inheritDoc
*/
public function findAdminWithRequestParameters(RequestParametersInterface $requestParameters): array
{
$sqlTranslator = new SqlRequestParametersTranslator($requestParameters);
$sqlTranslator->getRequestParameters()->setConcordanceStrictMode(
RequestParameters::CONCORDANCE_MODE_STRICT
);
$sqlTranslator->setConcordanceArray([
'name' => 'c.contact_name',
]);
$query = <<<'SQL_WRAP'
SELECT SQL_CALC_FOUND_ROWS
c.contact_id,
c.contact_name,
c.contact_email,
c.contact_admin
FROM `:db`.contact c
SQL_WRAP;
$searchRequest = $sqlTranslator->translateSearchParameterToSql();
$query .= $searchRequest !== null
? $searchRequest . ' AND '
: ' WHERE ';
$query .= "c.contact_admin = '1' AND c.contact_oreon = '1'";
$query .= $sqlTranslator->translatePaginationToSql();
$statement = $this->db->prepare($this->translateDbName($query));
foreach ($sqlTranslator->getSearchValues() as $key => $data) {
/**
* @var int
*/
$type = key($data);
$value = $data[$type];
$statement->bindValue($key, $value, $type);
}
$statement->execute();
$result = $this->db->query('SELECT FOUND_ROWS()');
if ($result !== false && ($total = $result->fetchColumn()) !== false) {
$sqlTranslator->getRequestParameters()->setTotal((int) $total);
}
$admins = [];
foreach ($statement as $admin) {
/** @var array{
* contact_admin: string,
* contact_name: string,
* contact_id: int,
* contact_email: string
* } $admin
*/
$admins[] = (new Contact())
->setAdmin(true)
->setName($admin['contact_name'])
->setId($admin['contact_id'])
->setEmail($admin['contact_email']);
}
return $admins;
}
/**
* @inheritDoc
*/
public function findContactIdsByAccessGroups(array $accessGroupIds): array
{
$bind = [];
foreach ($accessGroupIds as $key => $accessGroupId) {
$bind[':access_group_' . $key] = $accessGroupId;
}
if ($bind === []) {
return [];
}
$accessGroupIdsAsString = implode(',', array_keys($bind));
$statement = $this->db->prepare(
$this->translateDbName(
<<<SQL
SELECT c.contact_id
FROM `:db`.contact c
LEFT JOIN `:db`.contactgroup_contact_relation ccr
ON c.contact_id = ccr.contact_contact_id
LEFT JOIN `:db`.acl_group_contacts_relations gcr
ON c.contact_id = gcr.contact_contact_id
LEFT JOIN `:db`.acl_group_contactgroups_relations gcgr
ON ccr.contactgroup_cg_id = gcgr.cg_cg_id
WHERE gcr.acl_group_id IN ({$accessGroupIdsAsString})
OR gcgr.acl_group_id IN ({$accessGroupIdsAsString});
SQL
)
);
foreach ($bind as $token => $accessGroupId) {
$statement->bindValue($token, $accessGroupId, \PDO::PARAM_INT);
}
$statement->execute();
return $statement->fetchAll(\PDO::FETCH_COLUMN, 0);
}
/**
* @inheritDoc
*/
public function findAdminsByIds(array $contactIds): array
{
$bind = [];
foreach ($contactIds as $key => $contactId) {
$bind[':contact' . $key] = $contactId;
}
if ($bind === []) {
return [];
}
$bindTokenAsString = implode(', ', array_keys($bind));
$query = <<<SQL
SELECT c.contact_id,
c.contact_name,
c.contact_email,
c.contact_admin
FROM `:db`.contact c
WHERE c.contact_admin = '1'
AND c.contact_oreon = '1'
AND c.contact_id IN ({$bindTokenAsString})
SQL;
$statement = $this->db->prepare($this->translateDbName($query));
foreach ($bind as $token => $contactId) {
$statement->bindValue($token, $contactId, \PDO::PARAM_INT);
}
$statement->execute();
$admins = [];
foreach ($statement as $admin) {
/** @var array{
* contact_admin: string,
* contact_name: string,
* contact_id: int,
* contact_email: string
* } $admin
*/
$admins[] = (new Contact())
->setAdmin(true)
->setName($admin['contact_name'])
->setId($admin['contact_id'])
->setEmail($admin['contact_email']);
}
return $admins;
}
/**
* @inheritDoc
*/
public function findByIds(array $contactIds): array
{
if ($contactIds === []) {
return [];
}
[$bindValues, $subRequest] = $this->createMultipleBindQuery($contactIds, ':id');
$statement = $this->db->prepare(
$this->translateDbName(
<<<SQL
SELECT contact_id, contact_name, contact_alias, contact_email,
contact_admin, contact_activate
FROM `:db`.contact
WHERE contact_id IN ({$subRequest})
SQL
)
);
foreach ($bindValues as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->execute();
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$contacts = [];
foreach ($statement as $data) {
/** @var _ContactRecord $data */
$contacts[] = $this->createBasicContact($data);
}
return $contacts;
}
/**
* @inheritDoc
*/
public function retrieveExistingContactIds(array $contactIds): array
{
if ($contactIds === []) {
return [];
}
[$bindValues, $subRequest] = $this->createMultipleBindQuery($contactIds, ':id_');
$statement = $this->db->prepare(
$this->translateDbName(
"SELECT contact_id FROM `:db`.contact WHERE contact_id IN ({$subRequest})"
)
);
foreach ($bindValues as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->execute();
return $statement->fetchAll(\PDO::FETCH_COLUMN, 0);
}
/**
* @inheritDoc
*
* @throws AssertionFailedException
*/
public function findByAccessGroup(array $accessGroups): array
{
if ($accessGroups === []) {
return [];
}
$accessGroupIds = array_map(
fn (AccessGroup $accessGroup): int => $accessGroup->getId(),
$accessGroups
);
[$accessGroupBindValues, $accessGroupSubRequest] = $this->createMultipleBindQuery($accessGroupIds, ':id_');
$request = $this->translateDbName(
<<<SQL
SELECT contact_id, contact_name, contact_alias, contact_email,
contact_admin, contact_activate
FROM `:db`.contact
LEFT JOIN `:db`.contactgroup_contact_relation cgcr
ON cgcr.contact_contact_id = contact.contact_id
LEFT JOIN `:db`.acl_group_contactgroups_relations gcgr
ON gcgr.cg_cg_id = cgcr.contactgroup_cg_id
LEFT JOIN `:db`.acl_groups aclcg
ON aclcg.acl_group_id = gcgr.acl_group_id
AND aclcg.acl_group_activate = '1'
LEFT JOIN `:db`.acl_group_contacts_relations gcr
ON gcr.contact_contact_id = contact.contact_id
LEFT JOIN `:db`.acl_groups aclc
ON aclc.acl_group_id = gcr.acl_group_id
WHERE contact.contact_register = '1'
AND (aclc.acl_group_id IN ({$accessGroupSubRequest}) OR aclcg.acl_group_id IN ({$accessGroupSubRequest}))
GROUP BY contact.contact_id
SQL
);
$statement = $this->db->prepare($request);
foreach ($accessGroupBindValues as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->execute();
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$contacts = [];
foreach ($statement as $result) {
/**
* @var _ContactRecord $result
*/
$contacts[] = $this->createBasicContact($result);
}
return $contacts;
}
/**
* @inheritDoc
*/
public function findByAccessGroupsAndUserAndRequestParameters(
array $accessGroups,
ContactInterface $user,
?RequestParametersInterface $requestParameters = null,
): array {
if ($accessGroups === []) {
return [];
}
$accessGroupIds = array_map(
static fn (AccessGroup $accessGroup): int => $accessGroup->getId(),
$accessGroups
);
[$binValues, $subRequest] = $this->createMultipleBindQuery($accessGroupIds, ':id_');
$request = <<<SQL
SELECT DISTINCT SQL_CALC_FOUND_ROWS *
FROM (
SELECT /* Finds associated users in ACL group rules */
contact.contact_id, contact.contact_alias, contact.contact_name,
contact.contact_email, contact.contact_admin, contact.contact_activate
FROM `:db`.`contact`
INNER JOIN `:db`.`acl_group_contacts_relations` acl_c_rel
ON acl_c_rel.contact_contact_id = contact.contact_id
WHERE contact.contact_register = '1'
AND acl_c_rel.acl_group_id IN ({$subRequest})
UNION
SELECT /* Finds users belonging to associated contact groups in ACL group rules */
contact.contact_id, contact.contact_alias, contact.contact_name,
contact.contact_email, contact.contact_admin, contact.contact_activate
FROM `:db`.`contact`
INNER JOIN `:db`.`contactgroup_contact_relation` c_cg_rel
ON c_cg_rel.contact_contact_id = contact.contact_id
INNER JOIN `:db`.`acl_group_contactgroups_relations` acl_cg_rel
ON acl_cg_rel.cg_cg_id = c_cg_rel.contactgroup_cg_id
WHERE contact.contact_register = '1'
AND acl_cg_rel.acl_group_id IN ({$subRequest})
UNION
SELECT /* Finds users belonging to the same contact groups as the user */
contact2.contact_id, contact2.contact_alias, contact2.contact_name,
contact2.contact_email, contact2.contact_admin, contact.contact_activate
FROM `:db`.`contact`
INNER JOIN `:db`.`contactgroup_contact_relation` c_cg_rel
ON c_cg_rel.contact_contact_id = contact.contact_id
INNER JOIN `:db`.`contactgroup_contact_relation` c_cg_rel2
ON c_cg_rel2.contactgroup_cg_id = c_cg_rel.contactgroup_cg_id
INNER JOIN `:db`.`contact` contact2
ON contact2.contact_id = c_cg_rel2.contact_contact_id
WHERE c_cg_rel.contact_contact_id = :user_id
AND contact.contact_register = '1'
AND contact2.contact_register = '1'
GROUP BY contact2.contact_id
) as contact
SQL;
// Update the SQL query with the RequestParameters through SqlRequestParametersTranslator
$sqlTranslator = $requestParameters ? new SqlRequestParametersTranslator($requestParameters) : null;
$sqlTranslator?->getRequestParameters()->setConcordanceStrictMode(RequestParameters::CONCORDANCE_MODE_STRICT);
$sqlTranslator?->setConcordanceArray([
'id' => 'contact_id',
'alias' => 'contact_alias',
'name' => 'contact_name',
'email' => 'contact_email',
'is_admin' => 'contact_admin',
'is_activate' => 'contact_activate',
]);
$searchRequest = $sqlTranslator?->translateSearchParameterToSql();
$request .= $searchRequest;
// handle sort
$request .= $sqlTranslator?->translateSortParameterToSql();
// handle pagination
$request .= $sqlTranslator?->translatePaginationToSql();
$statement = $this->db->prepare($this->translateDbName($request));
$statement->bindValue(':user_id', $user->getId(), \PDO::PARAM_INT);
foreach ($binValues as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
if ($sqlTranslator !== null) {
foreach ($sqlTranslator->getSearchValues() as $key => $data) {
$type = (int) key($data);
$value = $data[$type];
$statement->bindValue($key, $value, $type);
}
}
$statement->execute();
$statement->setFetchMode(\PDO::FETCH_ASSOC);
// Calculate the number of rows for the pagination.
if ($total = $this->calculateNumberOfRows()) {
$requestParameters?->setTotal($total);
}
$basicContacts = [];
foreach ($statement as $result) {
/** @var _ContactRecord $result */
$basicContacts[] = $this->createBasicContact($result);
}
return $basicContacts;
}
/**
* @param _ContactRecord $data
*
* @return BasicContact
*/
private function createBasicContact(array $data): BasicContact
{
return new BasicContact(
new PositiveInteger((int) $data['contact_id']),
new NotEmptyString($data['contact_name']),
new NotEmptyString($data['contact_alias']),
new NotEmptyString($data['contact_email']),
$data['contact_admin'] === '1',
$data['contact_activate'] === '1'
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Contact/Infrastructure/Repository/DbContactTemplateFactory.php | centreon/src/Core/Contact/Infrastructure/Repository/DbContactTemplateFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Contact\Infrastructure\Repository;
use Core\Contact\Domain\Model\ContactTemplate;
class DbContactTemplateFactory
{
/**
* @param array<string,string> $record
*
* @return ContactTemplate
*/
public static function createFromRecord(array $record): ContactTemplate
{
return new ContactTemplate(
(int) $record['contact_id'],
$record['contact_name']
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Contact/Infrastructure/Repository/DbContactGroupFactory.php | centreon/src/Core/Contact/Infrastructure/Repository/DbContactGroupFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Contact\Infrastructure\Repository;
use Assert\AssertionFailedException;
use Core\Contact\Domain\Model\ContactGroup;
use Core\Contact\Domain\Model\ContactGroupType;
/**
* @phpstan-type _ContactGroup array{
* cg_id: int,
* cg_name: string,
* cg_alias: string,
* cg_comment?: string,
* cg_activate: string,
* cg_type: string
* }
*/
class DbContactGroupFactory
{
/**
* @param _ContactGroup $record
*
* @throws AssertionFailedException
*
* @return ContactGroup
*/
public static function createFromRecord(array $record): ContactGroup
{
return new ContactGroup(
(int) $record['cg_id'],
$record['cg_name'],
$record['cg_alias'],
$record['cg_comment'] ?? '',
$record['cg_activate'] === '1',
$record['cg_type'] === 'local'
? ContactGroupType::Local
: ContactGroupType::Ldap
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Contact/Infrastructure/Repository/DbReadContactTemplateRepository.php | centreon/src/Core/Contact/Infrastructure/Repository/DbReadContactTemplateRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Contact\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 Adaptation\Database\QueryBuilder\Exception\QueryBuilderException;
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\Contact\Application\Repository\ReadContactTemplateRepositoryInterface;
use Core\Contact\Domain\Model\ContactTemplate;
/**
* Class
*
* @class DbReadContactTemplateRepository
* @package Core\Contact\Infrastructure\Repository
*/
class DbReadContactTemplateRepository extends DatabaseRepository implements ReadContactTemplateRepositoryInterface
{
/** @var SqlRequestParametersTranslator */
private SqlRequestParametersTranslator $sqlRequestTranslator;
/**
* DbReadContactTemplateRepository constructor
*
* @param ConnectionInterface $connection
* @param SqlRequestParametersTranslator $sqlRequestTranslator
*/
public function __construct(
ConnectionInterface $connection,
SqlRequestParametersTranslator $sqlRequestTranslator,
) {
parent::__construct($connection);
$this->sqlRequestTranslator = $sqlRequestTranslator;
$this->sqlRequestTranslator
->getRequestParameters()
->setConcordanceStrictMode(RequestParameters::CONCORDANCE_MODE_STRICT);
$this->sqlRequestTranslator->setConcordanceArray([
'id' => 'contact_id',
'name' => 'contact_name',
]);
}
/**
* @throws RepositoryException
* @return ContactTemplate[]
*/
public function findAll(): array
{
try {
$query = $this->connection->createQueryBuilder()
->select('SQL_CALC_FOUND_ROWS contact_id, contact_name')
->from('contact')
->getQuery();
// Search
$searchRequest = $this->sqlRequestTranslator->translateSearchParameterToSql();
$query .= $searchRequest !== null
? $searchRequest . ' AND '
: ' WHERE ';
$query .= 'contact_register = 0 ';
// Sort
$sortRequest = $this->sqlRequestTranslator->translateSortParameterToSql();
$query .= $sortRequest ?? ' ORDER BY contact_id ASC';
// Pagination
$query .= $this->sqlRequestTranslator->translatePaginationToSql();
$queryParameters = SearchRequestParametersTransformer::reverseToQueryParameters(
$this->sqlRequestTranslator->getSearchValues()
);
// get data with pagination
$contactTemplates = [];
$results = $this->connection->fetchAllAssociative($query, $queryParameters);
foreach ($results as $result) {
$contactTemplates[] = DbContactTemplateFactory::createFromRecord($result);
}
// get total without pagination
if (($total = $this->connection->fetchOne('SELECT FOUND_ROWS() from contact')) !== false) {
$this->sqlRequestTranslator->getRequestParameters()->setTotal((int) $total);
}
return $contactTemplates;
} catch (QueryBuilderException|RequestParametersTranslatorException|TransformerException|ConnectionException $exception) {
throw new RepositoryException(
message: 'finding all contact template failed',
previous: $exception
);
}
}
/**
* @param int $id
*
* @throws RepositoryException
* @return ContactTemplate|null
*/
public function find(int $id): ?ContactTemplate
{
try {
$queryBuilder = $this->connection->createQueryBuilder();
$query = $queryBuilder->select('contact_id, contact_name')
->from('contact')
->where($queryBuilder->expr()->equal('contact_id', ':id'))
->andWhere($queryBuilder->expr()->equal('contact_register', ':register'))
->getQuery();
$queryParameters = QueryParameters::create([
QueryParameter::int('id', $id),
QueryParameter::int('register', 0),
]);
$result = $this->connection->fetchAssociative($query, $queryParameters);
if ($result !== []) {
/** @var array<string, string> $result */
return DbContactTemplateFactory::createFromRecord($result);
}
return null;
} catch (QueryBuilderException|CollectionException|ValueObjectException|ConnectionException $exception) {
throw new RepositoryException(
'finding contact template by id failed',
['id' => $id, 'exception' => $exception->getContext()],
$exception
);
}
}
}
| 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.