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/App/MonitoringConfiguration/Domain/Aggregate/GlobalMacro/GlobalMacroName.php
centreon/src/App/MonitoringConfiguration/Domain/Aggregate/GlobalMacro/GlobalMacroName.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Domain\Aggregate\GlobalMacro; use Webmozart\Assert\Assert; final readonly class GlobalMacroName { public const NAMING_VALIDATION_REGEX = '/^\$.*\$$/'; public function __construct( public string $value, ) { Assert::lengthBetween($value, 1, 255); Assert::regex($value, self::NAMING_VALIDATION_REGEX); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Domain/Aggregate/GlobalMacro/GlobalMacroId.php
centreon/src/App/MonitoringConfiguration/Domain/Aggregate/GlobalMacro/GlobalMacroId.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Domain\Aggregate\GlobalMacro; use App\Shared\Domain\Aggregate\AggregateRootId; final readonly class GlobalMacroId extends AggregateRootId { }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Domain/Aggregate/GlobalMacro/GlobalMacro.php
centreon/src/App/MonitoringConfiguration/Domain/Aggregate/GlobalMacro/GlobalMacro.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Domain\Aggregate\GlobalMacro; use App\MonitoringConfiguration\Domain\Aggregate\Poller\Poller; use App\Shared\Domain\Aggregate\AggregateRoot; use App\Shared\Domain\Collection; final class GlobalMacro extends AggregateRoot { /** * @param Collection<Poller> $pollers */ public function __construct( ?GlobalMacroId $id, public readonly GlobalMacroName $name, public readonly GlobalMacroExpression $expression, public readonly ?GlobalMacroComment $comment, public readonly bool $isPassword, public readonly bool $activated, public readonly Collection $pollers, ) { parent::__construct($id); } public function addPoller(Poller $poller): void { if ($this->pollers->contains($poller)) { return; } $this->pollers->add($poller); $poller->addGlobalMacro($this); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Domain/Aggregate/GlobalMacro/GlobalMacroComment.php
centreon/src/App/MonitoringConfiguration/Domain/Aggregate/GlobalMacro/GlobalMacroComment.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Domain\Aggregate\GlobalMacro; use Webmozart\Assert\Assert; final readonly class GlobalMacroComment { public function __construct( public string $value, ) { Assert::maxLength($value, 255); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Domain/Aggregate/Plugin/Plugin.php
centreon/src/App/MonitoringConfiguration/Domain/Aggregate/Plugin/Plugin.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Domain\Aggregate\Plugin; use App\Shared\Domain\Aggregate\AggregateRoot; final class Plugin extends AggregateRoot { public function __construct( public readonly PluginName $name, ) { } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Domain/Aggregate/Plugin/PluginName.php
centreon/src/App/MonitoringConfiguration/Domain/Aggregate/Plugin/PluginName.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Domain\Aggregate\Plugin; use Webmozart\Assert\Assert; final readonly class PluginName { public function __construct( public string $value, ) { Assert::notEmpty($value); Assert::maxLength($value, 255); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Domain/Aggregate/Option/OptionName.php
centreon/src/App/MonitoringConfiguration/Domain/Aggregate/Option/OptionName.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Domain\Aggregate\Option; use Webmozart\Assert\Assert; final readonly class OptionName { public function __construct( public string $value, ) { Assert::lengthBetween($value, 1, 255); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Domain/Aggregate/Option/OptionValue.php
centreon/src/App/MonitoringConfiguration/Domain/Aggregate/Option/OptionValue.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Domain\Aggregate\Option; use Webmozart\Assert\Assert; final readonly class OptionValue { public function __construct( public string $value, ) { Assert::lengthBetween($value, 1, 255); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Domain/Aggregate/Option/Option.php
centreon/src/App/MonitoringConfiguration/Domain/Aggregate/Option/Option.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Domain\Aggregate\Option; use App\Shared\Domain\Aggregate\AggregateRoot; final class Option extends AggregateRoot { public const PLUGIN_PATH_OPTION_NAME = 'nagios_path_plugins'; public function __construct( public readonly OptionName $name, public readonly OptionValue $value, ) { } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Domain/Aggregate/StandardMacro/StandardMacroId.php
centreon/src/App/MonitoringConfiguration/Domain/Aggregate/StandardMacro/StandardMacroId.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Domain\Aggregate\StandardMacro; use App\Shared\Domain\Aggregate\AggregateRootId; final readonly class StandardMacroId extends AggregateRootId { }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Domain/Aggregate/StandardMacro/StandardMacro.php
centreon/src/App/MonitoringConfiguration/Domain/Aggregate/StandardMacro/StandardMacro.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Domain\Aggregate\StandardMacro; use App\Shared\Domain\Aggregate\AggregateRoot; final class StandardMacro extends AggregateRoot { public function __construct( ?StandardMacroId $id, public readonly StandardMacroName $name, ) { parent::__construct($id); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Domain/Aggregate/StandardMacro/StandardMacroName.php
centreon/src/App/MonitoringConfiguration/Domain/Aggregate/StandardMacro/StandardMacroName.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Domain\Aggregate\StandardMacro; use Webmozart\Assert\Assert; final readonly class StandardMacroName { public const NAMING_VALIDATION_REGEX = '/^\$.*\$$/'; public function __construct(public string $value) { Assert::maxLength($value, 255); Assert::regex($value, self::NAMING_VALIDATION_REGEX); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Domain/Repository/PluginRepository.php
centreon/src/App/MonitoringConfiguration/Domain/Repository/PluginRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Domain\Repository; use App\MonitoringConfiguration\Domain\Aggregate\Option\OptionValue; use App\MonitoringConfiguration\Domain\Aggregate\Plugin\Plugin; use App\Shared\Domain\Collection; interface PluginRepository { /** * @return Collection<Plugin> */ public function findByPath(OptionValue $path): Collection; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Domain/Repository/GlobalMacroRepository.php
centreon/src/App/MonitoringConfiguration/Domain/Repository/GlobalMacroRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Domain\Repository; use App\MonitoringConfiguration\Domain\Aggregate\GlobalMacro\GlobalMacro; use App\MonitoringConfiguration\Domain\Repository\Criteria\GlobalMacroCriteria; interface GlobalMacroRepository { /** * @return \IteratorAggregate<int, GlobalMacro>&\Countable */ public function findAll(?GlobalMacroCriteria $criteria = null): \IteratorAggregate&\Countable; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Domain/Repository/ServiceCategoryRepository.php
centreon/src/App/MonitoringConfiguration/Domain/Repository/ServiceCategoryRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Domain\Repository; use App\MonitoringConfiguration\Domain\Aggregate\ServiceCategory\ServiceCategory; use App\MonitoringConfiguration\Domain\Aggregate\ServiceCategory\ServiceCategoryName; interface ServiceCategoryRepository { public function add(ServiceCategory $serviceCategory): void; public function findOneByName(ServiceCategoryName $name): ?ServiceCategory; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Domain/Repository/PollerRepository.php
centreon/src/App/MonitoringConfiguration/Domain/Repository/PollerRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Domain\Repository; use App\MonitoringConfiguration\Domain\Aggregate\GlobalMacro\GlobalMacro; use App\MonitoringConfiguration\Domain\Aggregate\Poller\Poller; use App\Shared\Domain\Collection; interface PollerRepository { /** * @return Collection<Poller> */ public function findAllByGlobalMacro(GlobalMacro $globalMacro): Collection; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Domain/Repository/OptionRepository.php
centreon/src/App/MonitoringConfiguration/Domain/Repository/OptionRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Domain\Repository; use App\MonitoringConfiguration\Domain\Aggregate\Option\Option; use App\MonitoringConfiguration\Domain\Aggregate\Option\OptionName; use App\MonitoringConfiguration\Domain\Exception\OptionDoesNotExistException; interface OptionRepository { /** * @throws OptionDoesNotExistException */ public function getByName(OptionName $name): Option; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Domain/Repository/StandardMacroRepository.php
centreon/src/App/MonitoringConfiguration/Domain/Repository/StandardMacroRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Domain\Repository; use App\MonitoringConfiguration\Domain\Aggregate\StandardMacro\StandardMacro; use App\MonitoringConfiguration\Domain\Repository\Criteria\StandardMacroCriteria; interface StandardMacroRepository { /** * @return \IteratorAggregate<int, StandardMacro>&\Countable */ public function findAll(?StandardMacroCriteria $criteria = null): \IteratorAggregate&\Countable; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Domain/Repository/Criteria/GlobalMacroCriteria.php
centreon/src/App/MonitoringConfiguration/Domain/Repository/Criteria/GlobalMacroCriteria.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Domain\Repository\Criteria; use Webmozart\Assert\Assert; final class GlobalMacroCriteria { public const OPERATOR_EQUAL = 'eq'; public const OPERATOR_LIKE = 'lk'; public const ALLOWED_OPERATORS = [self::OPERATOR_EQUAL, self::OPERATOR_LIKE]; private ?int $page = null; private ?int $itemsPerPage = null; /** @var array<self::OPERATOR_*, list<string>> */ private array $names = []; private bool $lazyRelations = false; public function withPagination(int $page, int $itemsPerPage): self { Assert::positiveInteger($page); Assert::positiveInteger($itemsPerPage); $new = clone $this; $new->page = $page; $new->itemsPerPage = $itemsPerPage; return $new; } /** * @param self::OPERATOR_* $operator */ public function withName(string $name, string $operator): self { Assert::notEmpty($name); Assert::inArray($operator, self::ALLOWED_OPERATORS); $names = $this->names[$operator] ?? []; $names[] = $name; $names = array_values(array_unique($names)); $new = clone $this; $new->names[$operator] = $names; return $new; } public function withLazyRelations(bool $lazyRelations = true): self { $new = clone $this; $new->lazyRelations = $lazyRelations; return $new; } public function getPage(): ?int { return $this->page; } public function getItemsPerPage(): ?int { return $this->itemsPerPage; } /** * @return array<self::OPERATOR_*, list<string>> */ public function getNames(): array { return $this->names; } public function hasLazyRelations(): bool { return $this->lazyRelations; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Domain/Repository/Criteria/StandardMacroCriteria.php
centreon/src/App/MonitoringConfiguration/Domain/Repository/Criteria/StandardMacroCriteria.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Domain\Repository\Criteria; use Webmozart\Assert\Assert; final class StandardMacroCriteria { public const OPERATOR_EQUAL = 'eq'; public const OPERATOR_LIKE = 'lk'; public const ALLOWED_OPERATORS = [self::OPERATOR_EQUAL, self::OPERATOR_LIKE]; private ?int $page = null; private ?int $itemsPerPage = null; /** @var array<self::OPERATOR_*, list<string>> */ private array $names = []; public function withPagination(int $page, int $itemsPerPage): self { Assert::positiveInteger($page); Assert::positiveInteger($itemsPerPage); $new = clone $this; $new->page = $page; $new->itemsPerPage = $itemsPerPage; return $new; } /** * @param self::OPERATOR_* $operator */ public function withName(string $name, string $operator): self { Assert::notEmpty($name); Assert::inArray($operator, self::ALLOWED_OPERATORS); $names = $this->names[$operator] ?? []; $names[] = $name; $names = array_values(array_unique($names)); $new = clone $this; $new->names[$operator] = $names; return $new; } public function getPage(): ?int { return $this->page; } public function getItemsPerPage(): ?int { return $this->itemsPerPage; } /** * @return array<self::OPERATOR_*, list<string>> */ public function getNames(): array { return $this->names; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Domain/Security/ServiceCategoryPermissionEnum.php
centreon/src/App/MonitoringConfiguration/Domain/Security/ServiceCategoryPermissionEnum.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Domain\Security; enum ServiceCategoryPermissionEnum: string { case CanRead = 'can_read_service_category'; case CanWrite = 'can_write_service_category'; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Domain/Security/GlobalMacroPermissionEnum.php
centreon/src/App/MonitoringConfiguration/Domain/Security/GlobalMacroPermissionEnum.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Domain\Security; enum GlobalMacroPermissionEnum: string { case CanRead = 'can_read_global_macro'; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Infrastructure/FileSystem/FileSystemPluginRepository.php
centreon/src/App/MonitoringConfiguration/Infrastructure/FileSystem/FileSystemPluginRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Infrastructure\FileSystem; use App\MonitoringConfiguration\Domain\Aggregate\Option\OptionValue; use App\MonitoringConfiguration\Domain\Aggregate\Plugin\Plugin; use App\MonitoringConfiguration\Domain\Aggregate\Plugin\PluginName; use App\MonitoringConfiguration\Domain\Repository\PluginRepository; use App\Shared\Domain\Collection; use Symfony\Component\Finder\Finder; use Symfony\Component\Finder\SplFileInfo; final readonly class FileSystemPluginRepository implements PluginRepository { private Finder $finder; public function __construct() { $this->finder = new Finder(); } public function findByPath(OptionValue $path): Collection { $pluginInfos = $this->finder->files()->in($path->value); return new Collection( array_map( static fn (SplFileInfo $plugin): Plugin => new Plugin(new PluginName($plugin->getFilename())), iterator_to_array($pluginInfos->getIterator()) ), Plugin::class ); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Infrastructure/Legacy/LegacyGlobalMacroPermissionVoter.php
centreon/src/App/MonitoringConfiguration/Infrastructure/Legacy/LegacyGlobalMacroPermissionVoter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Infrastructure\Legacy; use App\MonitoringConfiguration\Domain\Security\GlobalMacroPermissionEnum; use Centreon\Domain\Contact\Contact; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authorization\Voter\Vote; use Symfony\Component\Security\Core\Authorization\Voter\Voter; /** * @extends Voter<value-of<GlobalMacroPermissionEnum>, mixed> */ final class LegacyGlobalMacroPermissionVoter extends Voter { /** * @var array<value-of<GlobalMacroPermissionEnum>, string> */ private const LEGACY_PERMISSION_MAP = [ GlobalMacroPermissionEnum::CanRead->value => Contact::ROLE_CONFIGURATION_POLLERS_GLOBAL_MACRO_RW, ]; protected function supports(string $attribute, mixed $subject): bool { return GlobalMacroPermissionEnum::tryFrom($attribute) !== null; } protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token, ?Vote $vote = null): bool { $user = $token->getUser(); if (! $user instanceof Contact) { $vote?->addReason('The user is not logged in.'); return false; } if (! $user->hasTopologyRole(self::LEGACY_PERMISSION_MAP[$attribute])) { $vote?->addReason('The user do not have the required topology role: ' . self::LEGACY_PERMISSION_MAP[$attribute]); return false; } return true; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Infrastructure/Legacy/LegacyServiceCategoryPermissionVoter.php
centreon/src/App/MonitoringConfiguration/Infrastructure/Legacy/LegacyServiceCategoryPermissionVoter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Infrastructure\Legacy; use App\MonitoringConfiguration\Domain\Security\ServiceCategoryPermissionEnum; use Centreon\Domain\Contact\Contact; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authorization\Voter\Vote; use Symfony\Component\Security\Core\Authorization\Voter\Voter; /** * @extends Voter<value-of<ServiceCategoryPermissionEnum>, mixed> */ final class LegacyServiceCategoryPermissionVoter extends Voter { /** * @var array<value-of<ServiceCategoryPermissionEnum>, string> */ private const LEGACY_PERMISSION_MAP = [ ServiceCategoryPermissionEnum::CanRead->value => Contact::ROLE_CONFIGURATION_SERVICES_CATEGORIES_READ, ServiceCategoryPermissionEnum::CanWrite->value => Contact::ROLE_CONFIGURATION_SERVICES_CATEGORIES_READ_WRITE, ]; protected function supports(string $attribute, mixed $subject): bool { return ServiceCategoryPermissionEnum::tryFrom($attribute) !== null; } protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token, ?Vote $vote = null): bool { $user = $token->getUser(); if (! $user instanceof Contact) { $vote?->addReason('The user is not logged in.'); return false; } if (! $user->hasTopologyRole(self::LEGACY_PERMISSION_MAP[$attribute])) { $vote?->addReason('The user has not the required topology role.'); return false; } return true; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Infrastructure/ApiPlatform/Resource/StandardMacroResource.php
centreon/src/App/MonitoringConfiguration/Infrastructure/ApiPlatform/Resource/StandardMacroResource.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Infrastructure\ApiPlatform\Resource; use ApiPlatform\Metadata\ApiProperty; use ApiPlatform\Metadata\ApiResource; use ApiPlatform\Metadata\GetCollection; use ApiPlatform\OpenApi\Model; use App\MonitoringConfiguration\Infrastructure\ApiPlatform\State\ListStandardMacrosProvider; #[ApiResource( operations: [ new GetCollection( uriTemplate: '/configuration/standard-macros', provider: ListStandardMacrosProvider::class, openapi: new Model\Operation( parameters: [ new Model\Parameter( name: 'name[lk]', in: 'query', description: 'Filter by name using "like" operator', required: false, schema: [ 'type' => 'array', 'items' => ['type' => 'string'], ], ), new Model\Parameter( name: 'name[eq]', in: 'query', description: 'Filter by name using "equals" operator', required: false, schema: [ 'type' => 'array', 'items' => ['type' => 'string'], ], ), ], ), ), ], )] final class StandardMacroResource { public function __construct( #[ApiProperty(identifier: true, writable: false)] public ?int $id = null, public ?string $name = null, ) { } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Infrastructure/ApiPlatform/Resource/GlobalMacroResource.php
centreon/src/App/MonitoringConfiguration/Infrastructure/ApiPlatform/Resource/GlobalMacroResource.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Infrastructure\ApiPlatform\Resource; use ApiPlatform\Metadata\ApiProperty; use ApiPlatform\Metadata\ApiResource; use ApiPlatform\Metadata\GetCollection; use ApiPlatform\OpenApi\Model; use App\MonitoringConfiguration\Domain\Aggregate\GlobalMacro\GlobalMacroName; use App\MonitoringConfiguration\Domain\Security\GlobalMacroPermissionEnum; use App\MonitoringConfiguration\Infrastructure\ApiPlatform\State\ListGlobalMacrosProvider; use Symfony\Component\Validator\Constraints as Assert; #[ApiResource( operations: [ new GetCollection( uriTemplate: '/configuration/global-macros', provider: ListGlobalMacrosProvider::class, openapi: new Model\Operation( parameters: [ new Model\Parameter( name: 'name[lk]', in: 'query', description: 'Filter by name using "like" operator', required: false, schema: [ 'type' => 'array', 'items' => ['type' => 'string'], ], ), new Model\Parameter( name: 'name[eq]', in: 'query', description: 'Filter by name using "equals" operator', required: false, schema: [ 'type' => 'array', 'items' => ['type' => 'string'], ], ), ], ), security: "is_granted('" . GlobalMacroPermissionEnum::CanRead->value . "')", securityMessage: 'You are not allowed to list global macros', ), ], )] final class GlobalMacroResource { public function __construct( #[ApiProperty(identifier: true, writable: false)] public ?int $id = null, #[Assert\NotNull] #[Assert\Length(min: 1, max: 255)] #[Assert\Regex( pattern: GlobalMacroName::NAMING_VALIDATION_REGEX, message: "The name must start and end with a '$'" )] #[ApiProperty( description: 'Name of the global macro', openapiContext: ['example' => '$USER1$'] )] public ?string $name = null, #[Assert\NotNull] #[Assert\Length(min: 1, max: 255)] #[ApiProperty( description: 'Expression (value) of the global macro', openapiContext: ['example' => '/usr/lib64/nagios/plugins'] )] public ?string $expression = null, #[Assert\Length(max: 255)] #[ApiProperty( description: 'Additional information about the macro', openapiContext: ['example' => 'This macro is used to define the path of plugins'] )] public ?string $comment = null, public bool $isPassword = false, public bool $isActivated = false, ) { } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Infrastructure/ApiPlatform/Resource/ServiceCategoryResource.php
centreon/src/App/MonitoringConfiguration/Infrastructure/ApiPlatform/Resource/ServiceCategoryResource.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Infrastructure\ApiPlatform\Resource; use ApiPlatform\Metadata\ApiProperty; use ApiPlatform\Metadata\ApiResource; use ApiPlatform\Metadata\Post; use ApiPlatform\OpenApi\Model; use App\MonitoringConfiguration\Domain\Security\ServiceCategoryPermissionEnum; use App\MonitoringConfiguration\Infrastructure\ApiPlatform\State\CreateServiceCategoryProcessor; use Symfony\Component\Validator\Constraints as Assert; #[ApiResource( shortName: 'ServiceCategory', operations: [ new Post( uriTemplate: '/configuration/services/categories', processor: CreateServiceCategoryProcessor::class, openapi: new Model\Operation( responses: [ 409 => new Model\Response('ServiceCategory resource already exists'), ], ), security: "is_granted('" . ServiceCategoryPermissionEnum::CanWrite->value . "')", securityMessage: 'You are not allowed to create service categories', ), ], )] final class ServiceCategoryResource { public function __construct( #[ApiProperty(identifier: true, writable: false)] public ?int $id = null, #[Assert\NotNull] #[Assert\Length(min: 1, max: 255)] public ?string $name = null, #[Assert\NotNull] #[Assert\Length(min: 1, max: 255)] public ?string $alias = null, public bool $isActivated = true, ) { } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Infrastructure/ApiPlatform/Resource/PluginResource.php
centreon/src/App/MonitoringConfiguration/Infrastructure/ApiPlatform/Resource/PluginResource.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Infrastructure\ApiPlatform\Resource; use ApiPlatform\Metadata\ApiProperty; use ApiPlatform\Metadata\ApiResource; use ApiPlatform\Metadata\GetCollection; use App\MonitoringConfiguration\Infrastructure\ApiPlatform\State\ListPluginsProvider; use Symfony\Component\Validator\Constraints as Assert; #[ApiResource( shortName: 'ListPlugins', operations: [ new GetCollection( uriTemplate: '/configuration/plugins', provider: ListPluginsProvider::class, ), ], )] final class PluginResource { public function __construct( #[Assert\NotNull] #[Assert\NotBlank] #[Assert\Length(max: 255)] #[ApiProperty( description: 'Name of plugin', openapiContext: ['example' => 'negate'] )] public ?string $name = null, ) { } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Infrastructure/ApiPlatform/State/CreateServiceCategoryProcessor.php
centreon/src/App/MonitoringConfiguration/Infrastructure/ApiPlatform/State/CreateServiceCategoryProcessor.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Infrastructure\ApiPlatform\State; use ApiPlatform\Metadata\Operation; use ApiPlatform\State\ProcessorInterface; use App\MonitoringConfiguration\Application\Command\CreateServiceCategoryCommand; use App\MonitoringConfiguration\Domain\Aggregate\ServiceCategory\ServiceCategory; use App\MonitoringConfiguration\Domain\Aggregate\ServiceCategory\ServiceCategoryName; use App\MonitoringConfiguration\Infrastructure\ApiPlatform\Resource\ServiceCategoryResource; use App\Shared\Application\Command\CommandBus; use App\Shared\Infrastructure\Legacy\LegacySecurity; use App\Shared\Infrastructure\TransformerInterface; use Symfony\Component\DependencyInjection\Attribute\Autowire; use Webmozart\Assert\Assert; /** * @implements ProcessorInterface<ServiceCategoryResource, ServiceCategoryResource> */ final readonly class CreateServiceCategoryProcessor implements ProcessorInterface { /** * @param TransformerInterface<ServiceCategory, ServiceCategoryResource> $transformer */ public function __construct( private CommandBus $commandBus, #[Autowire(service: ResourceServiceCategoryTransformer::class)] private TransformerInterface $transformer, private LegacySecurity $legacySecurity, ) { } public function process($data, Operation $operation, array $uriVariables = [], array $context = []): ServiceCategoryResource { Assert::notNull($data->name); Assert::notNull($data->alias); $command = new CreateServiceCategoryCommand( name: new ServiceCategoryName($data->name), alias: new ServiceCategoryName($data->alias), activated: $data->isActivated, creatorId: $this->legacySecurity->getUserId(), ); $model = $this->commandBus->execute($command); Assert::isInstanceOf($model, ServiceCategory::class); return $this->transformer->transform($model); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Infrastructure/ApiPlatform/State/ResourceServiceCategoryTransformer.php
centreon/src/App/MonitoringConfiguration/Infrastructure/ApiPlatform/State/ResourceServiceCategoryTransformer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Infrastructure\ApiPlatform\State; use App\MonitoringConfiguration\Domain\Aggregate\ServiceCategory\ServiceCategory; use App\MonitoringConfiguration\Infrastructure\ApiPlatform\Resource\ServiceCategoryResource; use App\Shared\Infrastructure\TransformerInterface; /** * @implements TransformerInterface<ServiceCategory, ServiceCategoryResource> */ final readonly class ResourceServiceCategoryTransformer implements TransformerInterface { public function transform(mixed $from): ServiceCategoryResource { return new ServiceCategoryResource( id: $from->id()->value, name: $from->name->value, alias: $from->alias->value, isActivated: $from->activated, ); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Infrastructure/ApiPlatform/State/ListGlobalMacrosProvider.php
centreon/src/App/MonitoringConfiguration/Infrastructure/ApiPlatform/State/ListGlobalMacrosProvider.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Infrastructure\ApiPlatform\State; use ApiPlatform\Metadata\Operation; use ApiPlatform\State\Pagination\Pagination; use ApiPlatform\State\Pagination\TraversablePaginator; use ApiPlatform\State\ProviderInterface; use App\MonitoringConfiguration\Domain\Aggregate\GlobalMacro\GlobalMacro; use App\MonitoringConfiguration\Domain\Repository\Criteria\GlobalMacroCriteria; use App\MonitoringConfiguration\Domain\Repository\GlobalMacroRepository; use App\MonitoringConfiguration\Infrastructure\ApiPlatform\Resource\GlobalMacroResource; use App\Shared\Domain\Repository\Paginator; use App\Shared\Infrastructure\TransformerInterface; use Symfony\Component\DependencyInjection\Attribute\Autowire; /** * @implements ProviderInterface<GlobalMacroResource> */ final readonly class ListGlobalMacrosProvider implements ProviderInterface { /** * @param TransformerInterface<GlobalMacro,GlobalMacroResource> $transformer */ public function __construct( #[Autowire(service: ResourceGlobalMacroTransformer::class)] private TransformerInterface $transformer, private GlobalMacroRepository $repository, private Pagination $pagination, ) { } /** * @return iterable<GlobalMacroResource> */ public function provide(Operation $operation, array $uriVariables = [], array $context = []): iterable { $criteria = new GlobalMacroCriteria(); if ($this->pagination->isEnabled($operation, $context)) { $criteria = $criteria->withPagination( $this->pagination->getPage($context), $this->pagination->getLimit($operation, $context) ); } /** @var array{filters: array{name?: array<string, string|array<string>>}} $context */ $nameFilter = $context['filters']['name'] ?? null; if ($nameFilter) { foreach ($nameFilter as $operator => $names) { if (! in_array($operator, GlobalMacroCriteria::ALLOWED_OPERATORS, true)) { continue; } if (is_string($names)) { $names = [$names]; } foreach ($names as $name) { $criteria = $criteria->withName($name, $operator); } } } $models = $this->repository->findAll($criteria); $resources = []; foreach ($models as $model) { $resources[] = $this->transformer->transform($model); } if (! $models instanceof Paginator) { return $resources; } return new TraversablePaginator( new \ArrayIterator($resources), $models->getCurrentPage(), $models->getItemsPerPage(), $models->getTotalItems() ); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Infrastructure/ApiPlatform/State/ListPluginsProvider.php
centreon/src/App/MonitoringConfiguration/Infrastructure/ApiPlatform/State/ListPluginsProvider.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Infrastructure\ApiPlatform\State; use ApiPlatform\Metadata\Operation; use ApiPlatform\State\ProviderInterface; use App\MonitoringConfiguration\Domain\Aggregate\Option\Option; use App\MonitoringConfiguration\Domain\Aggregate\Option\OptionName; use App\MonitoringConfiguration\Domain\Aggregate\Plugin\Plugin; use App\MonitoringConfiguration\Domain\Repository\OptionRepository; use App\MonitoringConfiguration\Domain\Repository\PluginRepository; use App\MonitoringConfiguration\Infrastructure\ApiPlatform\Resource\PluginResource; use App\Shared\Infrastructure\TransformerInterface; use Symfony\Component\DependencyInjection\Attribute\Autowire; /** * @implements ProviderInterface<PluginResource> */ final readonly class ListPluginsProvider implements ProviderInterface { /** * @param TransformerInterface<Plugin,PluginResource> $transformer */ public function __construct( #[Autowire(service: ResourcePluginTransformer::class)] private TransformerInterface $transformer, private PluginRepository $pluginRepository, private OptionRepository $optionRepository, ) { } /** * @return iterable<PluginResource> */ public function provide(Operation $operation, array $uriVariables = [], array $context = []): iterable { $pluginPathOption = $this->optionRepository->getByName(new OptionName(Option::PLUGIN_PATH_OPTION_NAME)); $plugins = $this->pluginRepository->findByPath($pluginPathOption->value); $pluginResources = []; foreach ($plugins as $plugin) { $pluginResources[] = $this->transformer->transform($plugin); } return $pluginResources; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Infrastructure/ApiPlatform/State/ResourceGlobalMacroTransformer.php
centreon/src/App/MonitoringConfiguration/Infrastructure/ApiPlatform/State/ResourceGlobalMacroTransformer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Infrastructure\ApiPlatform\State; use App\MonitoringConfiguration\Domain\Aggregate\GlobalMacro\GlobalMacro; use App\MonitoringConfiguration\Infrastructure\ApiPlatform\Resource\GlobalMacroResource; use App\Shared\Infrastructure\TransformerInterface; /** * @implements TransformerInterface<GlobalMacro,GlobalMacroResource> */ final readonly class ResourceGlobalMacroTransformer implements TransformerInterface { public function transform(mixed $from): GlobalMacroResource { return new GlobalMacroResource( id: $from->id()->value, name: $from->name->value, expression: $from->expression->value, comment: $from->comment?->value, isActivated: $from->activated, isPassword: $from->isPassword ); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Infrastructure/ApiPlatform/State/ResourcePluginTransformer.php
centreon/src/App/MonitoringConfiguration/Infrastructure/ApiPlatform/State/ResourcePluginTransformer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Infrastructure\ApiPlatform\State; use App\MonitoringConfiguration\Domain\Aggregate\Plugin\Plugin; use App\MonitoringConfiguration\Infrastructure\ApiPlatform\Resource\PluginResource; use App\Shared\Infrastructure\TransformerInterface; /** * @implements TransformerInterface<Plugin, PluginResource> */ final readonly class ResourcePluginTransformer implements TransformerInterface { public function transform(mixed $from): PluginResource { return new PluginResource(name: $from->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/App/MonitoringConfiguration/Infrastructure/ApiPlatform/State/ListStandardMacrosProvider.php
centreon/src/App/MonitoringConfiguration/Infrastructure/ApiPlatform/State/ListStandardMacrosProvider.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Infrastructure\ApiPlatform\State; use ApiPlatform\Metadata\Operation; use ApiPlatform\State\Pagination\Pagination; use ApiPlatform\State\Pagination\TraversablePaginator; use ApiPlatform\State\ProviderInterface; use App\MonitoringConfiguration\Domain\Aggregate\StandardMacro\StandardMacro; use App\MonitoringConfiguration\Domain\Repository\Criteria\StandardMacroCriteria; use App\MonitoringConfiguration\Domain\Repository\StandardMacroRepository; use App\MonitoringConfiguration\Infrastructure\ApiPlatform\Resource\StandardMacroResource; use App\Shared\Domain\Repository\Paginator; use App\Shared\Infrastructure\TransformerInterface; use Symfony\Component\DependencyInjection\Attribute\Autowire; /** * @implements ProviderInterface<StandardMacroResource> */ final readonly class ListStandardMacrosProvider implements ProviderInterface { /** * @param TransformerInterface<StandardMacro,StandardMacroResource> $transformer */ public function __construct( #[Autowire(service: ResourceStandardMacroTransformer::class)] private TransformerInterface $transformer, private StandardMacroRepository $macroRepository, private Pagination $pagination, ) { } /** * @return iterable<StandardMacroResource> */ public function provide(Operation $operation, array $uriVariables = [], array $context = []): iterable { $criteria = new StandardMacroCriteria(); if ($this->pagination->isEnabled($operation, $context)) { $criteria = $criteria->withPagination( $this->pagination->getPage($context), $this->pagination->getLimit($operation, $context) ); } /** @var array{filters: array{name?: array<string, string|array<string>>}} $context */ $nameFilter = $context['filters']['name'] ?? null; if ($nameFilter) { foreach ($nameFilter as $operator => $names) { if (! in_array($operator, StandardMacroCriteria::ALLOWED_OPERATORS, true)) { continue; } if (is_string($names)) { $names = [$names]; } foreach ($names as $name) { $criteria = $criteria->withName($name, $operator); } } } $standardMacros = $this->macroRepository->findAll($criteria); $standardMacroResources = []; foreach ($standardMacros as $standardMacro) { $standardMacroResources[] = $this->transformer->transform($standardMacro); } if (! $standardMacros instanceof Paginator) { return $standardMacroResources; } return new TraversablePaginator( new \ArrayIterator($standardMacroResources), $standardMacros->getCurrentPage(), $standardMacros->getItemsPerPage(), $standardMacros->getTotalItems() ); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Infrastructure/ApiPlatform/State/ResourceStandardMacroTransformer.php
centreon/src/App/MonitoringConfiguration/Infrastructure/ApiPlatform/State/ResourceStandardMacroTransformer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Infrastructure\ApiPlatform\State; use App\MonitoringConfiguration\Domain\Aggregate\StandardMacro\StandardMacro; use App\MonitoringConfiguration\Infrastructure\ApiPlatform\Resource\StandardMacroResource; use App\Shared\Infrastructure\TransformerInterface; /** * @implements TransformerInterface<StandardMacro, StandardMacroResource> */ final readonly class ResourceStandardMacroTransformer implements TransformerInterface { public function transform(mixed $from): StandardMacroResource { return new StandardMacroResource( id: $from->id()->value, name: $from->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/App/MonitoringConfiguration/Infrastructure/Dbal/DbalServiceCategoryTransformer.php
centreon/src/App/MonitoringConfiguration/Infrastructure/Dbal/DbalServiceCategoryTransformer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Infrastructure\Dbal; use App\MonitoringConfiguration\Domain\Aggregate\ServiceCategory\ServiceCategory; use App\MonitoringConfiguration\Domain\Aggregate\ServiceCategory\ServiceCategoryId; use App\MonitoringConfiguration\Domain\Aggregate\ServiceCategory\ServiceCategoryName; use App\Shared\Infrastructure\TransformerInterface; /** * @phpstan-import-type RowTypeAlias from DbalServiceCategoryRepository * * @implements TransformerInterface<RowTypeAlias, ServiceCategory> */ final readonly class DbalServiceCategoryTransformer implements TransformerInterface { public function transform(mixed $from): ServiceCategory { return new ServiceCategory( id: new ServiceCategoryId($from['sc_id']), name: new ServiceCategoryName($from['sc_name']), alias: new ServiceCategoryName($from['sc_description']), activated: $from['sc_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/App/MonitoringConfiguration/Infrastructure/Dbal/DbalGlobalMacroRepository.php
centreon/src/App/MonitoringConfiguration/Infrastructure/Dbal/DbalGlobalMacroRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Infrastructure\Dbal; use App\MonitoringConfiguration\Domain\Aggregate\GlobalMacro\GlobalMacro; use App\MonitoringConfiguration\Domain\Aggregate\GlobalMacro\GlobalMacroId; use App\MonitoringConfiguration\Domain\Aggregate\Poller\Poller; use App\MonitoringConfiguration\Domain\Repository\Criteria\GlobalMacroCriteria; use App\MonitoringConfiguration\Domain\Repository\GlobalMacroRepository; use App\Shared\Domain\Collection; use App\Shared\Infrastructure\Dbal\DbalRepository; use App\Shared\Infrastructure\InMemory\InMemoryPaginator; use App\Shared\Infrastructure\TransformerInterface; use Doctrine\DBAL\Connection; use Doctrine\DBAL\Query\QueryBuilder; use Symfony\Component\DependencyInjection\Attribute\Autowire; use Webmozart\Assert\Assert; /** * @phpstan-type RowTypeAlias = array{ * gm_resource_id: int, * gm_resource_name: string, * gm_resource_line: string, * gm_resource_comment: string|null, * gm_resource_activate: '0'|'1', * gm_is_password: 0|1, * } */ final readonly class DbalGlobalMacroRepository extends DbalRepository implements GlobalMacroRepository { public const TABLE_NAME = 'cfg_resource'; /** * @param TransformerInterface<RowTypeAlias, GlobalMacro> $transformer */ public function __construct( #[Autowire(service: 'doctrine.dbal.default_connection')] private Connection $connection, #[Autowire(service: DbalGlobalMacroTransformer::class)] private TransformerInterface $transformer, private DbalPollerRepository $pollerRepository, ) { } public function findAll(?GlobalMacroCriteria $criteria = null): \IteratorAggregate&\Countable { $lazyRelations = $criteria?->hasLazyRelations() ?? false; $qb = $this->connection->createQueryBuilder(); $qb->select(...self::getSelectColumns()) ->from(self::TABLE_NAME, 'gm') ->orderBy('gm.resource_id'); // required for deterministic pagination // if we have a criteria, filter the query if ($criteria instanceof GlobalMacroCriteria) { $this->filterByCriteria($qb, $criteria); } // if no pagination if ($criteria?->getPage() === null || $criteria->getItemsPerPage() === null) { /** @var array<RowTypeAlias> $rows */ $rows = $qb->executeQuery()->fetchAllAssociative(); return $this->createGlobalMacros($rows, $lazyRelations); } $this->paginate($qb, $criteria); $count = $this->countOnQueryBuilder($qb); // must be done before fetching all rows /** @var array<RowTypeAlias> $rows */ $rows = $qb->executeQuery()->fetchAllAssociative(); return new InMemoryPaginator( items: $this->createGlobalMacros($rows, $lazyRelations), totalItems: $count, currentPage: $criteria->getPage() ?? throw new \LogicException('Unexpected null page'), itemsPerPage: $criteria->getItemsPerPage() ?? throw new \LogicException('Unexpected null items per page'), ); } /** * @return array<string> */ public static function getSelectColumns(string $alias = 'gm'): array { return [ "{$alias}.resource_id AS gm_resource_id", "{$alias}.resource_name AS gm_resource_name", "{$alias}.resource_line AS gm_resource_line", "{$alias}.resource_comment AS gm_resource_comment", "{$alias}.resource_activate AS gm_resource_activate", "{$alias}.is_password AS gm_is_password", ]; } public function filterByCriteria(QueryBuilder $qb, GlobalMacroCriteria $criteria): void { if ($nameCriteria = $criteria->getNames()) { foreach ($nameCriteria as $operator => $names) { if ($operator === GlobalMacroCriteria::OPERATOR_LIKE) { $qb->andWhere($qb->expr()->or(...array_map( static fn (string $name): string => $qb->expr()->like('gm.resource_name', '"%' . $name . '%"'), $names ))); continue; } $qb->andWhere($qb->expr()->in( 'gm.resource_name', array_map(static fn (string $name): string => '"' . $name . '"', $names) )); } } } /** * @param array<RowTypeAlias> $rows * * @return Collection<GlobalMacro> */ private function createGlobalMacros(array $rows, bool $lazyRelations = true): Collection { return new Collection(array_map(fn (array $row): GlobalMacro => $this->createGlobalMacro($row, $lazyRelations), $rows), GlobalMacro::class); } /** * @param RowTypeAlias $row */ private function createGlobalMacro(array $row, bool $lazyRelations = true): GlobalMacro { $globalMacro = $this->transformer->transform($row); $pollers = $lazyRelations ? new Collection(fn (): array => $this->pollerRepository->findAllByGlobalMacro($globalMacro)->toArray(), Poller::class) : $this->pollerRepository->findAllByGlobalMacro($globalMacro); /** @var GlobalMacroId $id */ $id = $globalMacro->id(); // create a new instance with same values but with the poller collection return new GlobalMacro( id: $id, name: $globalMacro->name, expression: $globalMacro->expression, comment: $globalMacro->comment, activated: $globalMacro->activated, isPassword: $globalMacro->isPassword, pollers: $pollers, ); } private function paginate(QueryBuilder $qb, GlobalMacroCriteria $criteria): void { if ($criteria->getPage() === null || $criteria->getItemsPerPage() === null) { return; } $qb->setFirstResult(($criteria->getPage() - 1) * $criteria->getItemsPerPage()) ->setMaxResults($criteria->getItemsPerPage()); } private function countOnQueryBuilder(QueryBuilder $qb): int { $qb = clone $qb; // avoid modifying the initial query builder $count = $qb ->select('COUNT(DISTINCT gm.resource_id)') ->setFirstResult(0) // reset any pagination ->setMaxResults(null) ->executeQuery() ->fetchOne(); Assert::integer($count); return $count; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Infrastructure/Dbal/DbalOptionRepository.php
centreon/src/App/MonitoringConfiguration/Infrastructure/Dbal/DbalOptionRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Infrastructure\Dbal; use App\MonitoringConfiguration\Domain\Aggregate\Option\Option; use App\MonitoringConfiguration\Domain\Aggregate\Option\OptionName; use App\MonitoringConfiguration\Domain\Exception\OptionDoesNotExistException; use App\MonitoringConfiguration\Domain\Repository\OptionRepository; use App\Shared\Infrastructure\Dbal\DbalRepository; use App\Shared\Infrastructure\TransformerInterface; use Doctrine\DBAL\Connection; use Symfony\Component\DependencyInjection\Attribute\Autowire; /** * @phpstan-type RowTypeAlias = array{ * option_name: string, * option_value: string, * } */ final readonly class DbalOptionRepository extends DbalRepository implements OptionRepository { private const TABLE_NAME = 'options'; /** * @param TransformerInterface<RowTypeAlias, Option> $transformer */ public function __construct( #[Autowire(service: 'doctrine.dbal.default_connection')] private Connection $connection, #[Autowire(service: DbalOptionTransformer::class)] private TransformerInterface $transformer, ) { } public function getByName(OptionName $name): Option { $qb = $this->connection->createQueryBuilder(); $qb->select('`key` AS option_name', '`value` AS option_value') ->from(self::TABLE_NAME) ->where('`key` = :name') ->setParameter('name', $name->value) ->setMaxResults(1); /** @var RowTypeAlias|false $row */ $row = $qb->executeQuery()->fetchAssociative(); if ($row === false) { throw new OptionDoesNotExistException(['option_name' => $name->value]); } return $this->transformer->transform($row); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Infrastructure/Dbal/DbalOptionTransformer.php
centreon/src/App/MonitoringConfiguration/Infrastructure/Dbal/DbalOptionTransformer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Infrastructure\Dbal; use App\MonitoringConfiguration\Domain\Aggregate\Option\Option; use App\MonitoringConfiguration\Domain\Aggregate\Option\OptionName; use App\MonitoringConfiguration\Domain\Aggregate\Option\OptionValue; use App\Shared\Infrastructure\TransformerInterface; /** * @phpstan-import-type RowTypeAlias from DbalOptionRepository * * @implements TransformerInterface<RowTypeAlias, Option> */ final readonly class DbalOptionTransformer implements TransformerInterface { public function transform(mixed $from): Option { return new Option( name: new OptionName($from['option_name']), value: new OptionValue($from['option_value']), ); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Infrastructure/Dbal/DbalStandardMacroRepository.php
centreon/src/App/MonitoringConfiguration/Infrastructure/Dbal/DbalStandardMacroRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Infrastructure\Dbal; use App\MonitoringConfiguration\Domain\Aggregate\StandardMacro\StandardMacro; use App\MonitoringConfiguration\Domain\Repository\Criteria\StandardMacroCriteria; use App\MonitoringConfiguration\Domain\Repository\StandardMacroRepository; use App\Shared\Domain\Collection; use App\Shared\Infrastructure\Dbal\DbalRepository; use App\Shared\Infrastructure\InMemory\InMemoryPaginator; use App\Shared\Infrastructure\TransformerInterface; use Doctrine\DBAL\Connection; use Doctrine\DBAL\Query\QueryBuilder; use Symfony\Component\DependencyInjection\Attribute\Autowire; use Webmozart\Assert\Assert; /** * @phpstan-type RowTypeAlias = array{ * macro_id: int, * macro_name: string, * } */ final readonly class DbalStandardMacroRepository extends DbalRepository implements StandardMacroRepository { public const TABLE_NAME = 'nagios_macro'; /** * @param TransformerInterface<RowTypeAlias, StandardMacro> $transformer */ public function __construct( #[Autowire(service: 'doctrine.dbal.default_connection')] private Connection $connection, #[Autowire(service: DbalStandardMacroTransformer::class)] private TransformerInterface $transformer, ) { } public function findAll(?StandardMacroCriteria $criteria = null): \IteratorAggregate&\Countable { $qb = $this->connection->createQueryBuilder(); $qb->select('macro_id', 'macro_name') ->from(self::TABLE_NAME, 'sm') ->orderBy('sm.macro_id'); // required for deterministic pagination // if we have a criteria, filter the query if ($criteria instanceof StandardMacroCriteria) { $this->filterByCriteria($qb, $criteria); } // if no pagination if ($criteria?->getPage() === null || $criteria->getItemsPerPage() === null) { /** @var array<RowTypeAlias> $rows */ $rows = $qb->executeQuery()->fetchAllAssociative(); return $this->createStandardMacros($rows); } $this->paginate($qb, $criteria); $count = $this->countOnQueryBuilder($qb); // must be done before fetching all rows /** @var array<RowTypeAlias> $rows */ $rows = $qb->executeQuery()->fetchAllAssociative(); return new InMemoryPaginator( items: $this->createStandardMacros($rows), totalItems: $count, currentPage: $criteria->getPage() ?? throw new \LogicException('Unexpected null page'), itemsPerPage: $criteria->getItemsPerPage() ?? throw new \LogicException('Unexpected null items per page'), ); } private function filterByCriteria(QueryBuilder $qb, StandardMacroCriteria $criteria): void { if ($nameCriteria = $criteria->getNames()) { foreach ($nameCriteria as $operator => $names) { if ($operator === StandardMacroCriteria::OPERATOR_LIKE) { $qb->andWhere($qb->expr()->or(...array_map( static fn (string $name): string => $qb->expr()->like('sm.macro_name', '"%' . $name . '%"'), $names ))); continue; } $qb->andWhere($qb->expr()->in( 'sm.macro_name', array_map(static fn (string $name): string => '"' . $name . '"', $names) )); } } } /** * @param array<RowTypeAlias> $rows * * @return Collection<StandardMacro> */ private function createStandardMacros(array $rows): Collection { return new Collection( array_map( fn (array $row): StandardMacro => $this->transformer->transform($row), $rows ), StandardMacro::class ); } private function paginate(QueryBuilder $qb, StandardMacroCriteria $criteria): void { if ($criteria->getPage() === null || $criteria->getItemsPerPage() === null) { return; } $qb->setFirstResult(($criteria->getPage() - 1) * $criteria->getItemsPerPage()) ->setMaxResults($criteria->getItemsPerPage()); } private function countOnQueryBuilder(QueryBuilder $qb): int { $qb = clone $qb; // avoid modifying the initial query builder $count = $qb ->select('COUNT(DISTINCT sm.macro_id)') ->setFirstResult(0) // reset any pagination ->setMaxResults(null) ->executeQuery() ->fetchOne(); Assert::integer($count); return $count; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Infrastructure/Dbal/DbalPollerRepository.php
centreon/src/App/MonitoringConfiguration/Infrastructure/Dbal/DbalPollerRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Infrastructure\Dbal; use App\MonitoringConfiguration\Domain\Aggregate\GlobalMacro\GlobalMacro; use App\MonitoringConfiguration\Domain\Aggregate\Poller\Poller; use App\MonitoringConfiguration\Domain\Repository\PollerRepository; use App\Shared\Domain\Collection; use App\Shared\Infrastructure\Dbal\DbalRepository; use App\Shared\Infrastructure\TransformerInterface; use Doctrine\DBAL\Connection; use Symfony\Component\DependencyInjection\Attribute\Autowire; /** * @phpstan-import-type RowTypeAlias from DbalGlobalMacroRepository as GlobalMacroRowTypeAlias * * @phpstan-type RowTypeAlias = array{ * poller_id: int, * poller_name: string, * } * @phpstan-type JoinRowTypeAlias = array{ * poller_id: int, * poller_name: string, * gm_resource_id: int, * gm_resource_name: string, * gm_resource_line: string, * gm_resource_comment: string|null, * gm_resource_activate: '0'|'1', * gm_is_password: 0|1, * } */ final readonly class DbalPollerRepository extends DbalRepository implements PollerRepository { public const TABLE_NAME = 'nagios_server'; public const GLOBAL_MACRO_JOIN_TABLE_NAME = 'cfg_resource_instance_relations'; /** * @param TransformerInterface<RowTypeAlias, Poller> $pollerTransformer * @param TransformerInterface<GlobalMacroRowTypeAlias, GlobalMacro> $globalMacroTransformer */ public function __construct( #[Autowire(service: 'doctrine.dbal.default_connection')] private Connection $connection, #[Autowire(service: DbalPollerTransformer::class)] private TransformerInterface $pollerTransformer, #[Autowire(service: DbalGlobalMacroTransformer::class)] private TransformerInterface $globalMacroTransformer, ) { } public function findAllByGlobalMacro(GlobalMacro $globalMacro): Collection { $qb = $this->connection->createQueryBuilder(); $qb->select(...self::getSelectColumns(), ...DbalGlobalMacroRepository::getSelectColumns()) ->from(self::GLOBAL_MACRO_JOIN_TABLE_NAME, 'pg1') ->innerJoin('pg1', self::TABLE_NAME, 'p', 'p.id = pg1.instance_id') ->leftJoin('p', self::GLOBAL_MACRO_JOIN_TABLE_NAME, 'pg2', 'pg2.instance_id = p.id') ->leftJoin('pg2', DbalGlobalMacroRepository::TABLE_NAME, 'gm', 'gm.resource_id = pg2.resource_id') // ensures still filter on relevant pollers ->where('pg1.resource_id = :resource_id') ->setParameter('resource_id', $globalMacro->id()->value); /** * @var array<JoinRowTypeAlias> $rows */ $rows = $qb->executeQuery()->fetchAllAssociative(); $pollerRows = []; $globalMacroRows = []; foreach ($rows as $row) { $pollerId = $row['poller_id']; $globalMacroId = $row['gm_resource_id']; $pollerRows[$pollerId] ??= $row; if ($globalMacroId !== null) { /** @var GlobalMacroRowTypeAlias $globalMacroRow */ $globalMacroRow = [ 'gm_resource_id' => $row['gm_resource_id'], 'gm_resource_name' => $row['gm_resource_name'], 'gm_resource_line' => $row['gm_resource_line'], 'gm_resource_comment' => $row['gm_resource_comment'], 'gm_resource_activate' => $row['gm_resource_activate'], 'gm_is_password' => $row['gm_is_password'], ]; $globalMacroRows[$pollerId][$globalMacroId] = $globalMacroRow; } } return $this->createPollers($pollerRows, $globalMacroRows); } /** * @return array<string> */ public static function getSelectColumns(string $alias = 'p'): array { return [ "{$alias}.id AS poller_id", "{$alias}.name AS poller_name", ]; } /** * @param array<RowTypeAlias> $rows * @param array<array<GlobalMacroRowTypeAlias>>|null $globalMacroRowsByPollerId * * @return Collection<Poller> */ private function createPollers(array $rows, ?array $globalMacroRowsByPollerId = null): Collection { // fetch all global macros of given pollers if ($globalMacroRowsByPollerId !== null) { $globalMacroQb = $this->connection->createQueryBuilder(); $globalMacroQb->select('p.id AS poller_id', ...DbalGlobalMacroRepository::getSelectColumns()) ->from(self::TABLE_NAME, 'p') ->innerJoin('p', self::GLOBAL_MACRO_JOIN_TABLE_NAME, 'pg', 'p.id = pg.instance_id') ->innerJoin('pg', DbalGlobalMacroRepository::TABLE_NAME, 'gm', 'gm.resource_id = pg.resource_id') ->where($globalMacroQb->expr()->in('p.id', array_map('strval', array_column($rows, 'poller_id')))); /** * @var array<JoinRowTypeAlias> $globalMacroRows */ $globalMacroRows = $globalMacroQb->executeQuery()->fetchAllAssociative(); /** * @var array<array<GlobalMacroRowTypeAlias>> $globalMacroRowsByPollerId */ $globalMacroRowsByPollerId = []; foreach ($globalMacroRows as $globalMacrosRow) { $globalMacroRowsByPollerId['poller_id'][] = $globalMacrosRow; } } $pollers = []; foreach ($rows as $row) { $pollerId = $row['poller_id']; $pollers[$pollerId] ??= $this->createPoller( $row, $globalMacroRowsByPollerId[$pollerId] ?? null, ); } return new Collection(array_values($pollers), Poller::class); } /** * @param RowTypeAlias $row * @param array<GlobalMacroRowTypeAlias>|null $globalMacroRows */ private function createPoller(array $row, ?array $globalMacroRows = null): Poller { // fetch all global macros of a given poller if ($globalMacroRows === null) { $globalMacroQb = $this->connection->createQueryBuilder(); $globalMacroQb->select(...DbalGlobalMacroRepository::getSelectColumns()) ->from(self::GLOBAL_MACRO_JOIN_TABLE_NAME, 'pg') ->innerJoin('pg', DbalGlobalMacroRepository::TABLE_NAME, 'gm', 'gm.resource_id = pg.resource_id') ->where('pg.instance_id = :poller_id') ->setParameter('poller_id', $row['poller_id']); /** * @var array<GlobalMacroRowTypeAlias> $globalMacroRows */ $globalMacroRows = $globalMacroQb->executeQuery()->fetchAllAssociative(); } $poller = $this->pollerTransformer->transform($row); $this->hydrateToManyRelation( primaryEntity: $poller, relatedRows: $globalMacroRows, relatedIdKey: 'gm_resource_id', relatedFactoryCallback: $this->globalMacroTransformer->transform(...), relationCallback: static function (Poller $poller, GlobalMacro $globalMacro): void { $poller->addGlobalMacro($globalMacro); }, ); return $poller; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Infrastructure/Dbal/DbalPollerTransformer.php
centreon/src/App/MonitoringConfiguration/Infrastructure/Dbal/DbalPollerTransformer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Infrastructure\Dbal; use App\MonitoringConfiguration\Domain\Aggregate\GlobalMacro\GlobalMacro; use App\MonitoringConfiguration\Domain\Aggregate\Poller\Poller; use App\MonitoringConfiguration\Domain\Aggregate\Poller\PollerId; use App\MonitoringConfiguration\Domain\Aggregate\Poller\PollerName; use App\Shared\Domain\Collection; use App\Shared\Infrastructure\TransformerInterface; /** * @phpstan-import-type RowTypeAlias from DbalPollerRepository * * @implements TransformerInterface<RowTypeAlias, Poller> */ final readonly class DbalPollerTransformer implements TransformerInterface { public function transform(mixed $from): mixed { return new Poller( id: new PollerId($from['poller_id']), name: new PollerName($from['poller_name']), globalMacros: new Collection([], GlobalMacro::class), // must be filled by callers ); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Infrastructure/Dbal/DbalStandardMacroTransformer.php
centreon/src/App/MonitoringConfiguration/Infrastructure/Dbal/DbalStandardMacroTransformer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Infrastructure\Dbal; use App\MonitoringConfiguration\Domain\Aggregate\StandardMacro\StandardMacro; use App\MonitoringConfiguration\Domain\Aggregate\StandardMacro\StandardMacroId; use App\MonitoringConfiguration\Domain\Aggregate\StandardMacro\StandardMacroName; use App\Shared\Infrastructure\TransformerInterface; /** * @phpstan-import-type RowTypeAlias from DbalStandardMacroRepository * * @implements TransformerInterface<RowTypeAlias,StandardMacro> */ final readonly class DbalStandardMacroTransformer implements TransformerInterface { /** * @param RowTypeAlias $from */ public function transform(mixed $from): StandardMacro { return new StandardMacro( id: new StandardMacroId($from['macro_id']), name: new StandardMacroName($from['macro_name']), ); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Infrastructure/Dbal/DbalServiceCategoryRepository.php
centreon/src/App/MonitoringConfiguration/Infrastructure/Dbal/DbalServiceCategoryRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Infrastructure\Dbal; use App\MonitoringConfiguration\Domain\Aggregate\ServiceCategory\ServiceCategory; use App\MonitoringConfiguration\Domain\Aggregate\ServiceCategory\ServiceCategoryId; use App\MonitoringConfiguration\Domain\Aggregate\ServiceCategory\ServiceCategoryName; use App\MonitoringConfiguration\Domain\Repository\ServiceCategoryRepository; use App\Shared\Infrastructure\Dbal\DbalRepository; use App\Shared\Infrastructure\TransformerInterface; use Doctrine\DBAL\Connection; use Symfony\Component\DependencyInjection\Attribute\Autowire; /** * @phpstan-type RowTypeAlias = array{sc_id: int, sc_name: string, sc_description: string, sc_activate: '0'|'1'} */ final readonly class DbalServiceCategoryRepository extends DbalRepository implements ServiceCategoryRepository { private const TABLE_NAME = 'service_categories'; /** * @param TransformerInterface<RowTypeAlias, ServiceCategory> $transformer */ public function __construct( #[Autowire(service: 'doctrine.dbal.default_connection')] private Connection $connection, #[Autowire(service: DbalServiceCategoryTransformer::class)] private TransformerInterface $transformer, ) { } public function add(ServiceCategory $serviceCategory): void { $qb = $this->connection->createQueryBuilder(); $qb->insert(self::TABLE_NAME) ->values([ 'sc_name' => ':name', 'sc_description' => ':alias', 'sc_activate' => ':activated', ]) ->setParameter('name', $serviceCategory->name->value) ->setParameter('alias', $serviceCategory->alias->value) ->setParameter('activated', $serviceCategory->activated ? '1' : '0') ->executeStatement(); $id = (int) $this->connection->lastInsertId(); if ($id === 0) { throw new \RuntimeException(\sprintf('Unable to retrieve last insert ID for "%s".', self::TABLE_NAME)); } $this->setId($serviceCategory, new ServiceCategoryId($id)); } public function findOneByName(ServiceCategoryName $name): ?ServiceCategory { $qb = $this->connection->createQueryBuilder(); $qb->select('sc_id', 'sc_name', 'sc_description', 'sc_activate') ->from(self::TABLE_NAME) ->where('sc_name = :name') ->setParameter('name', $name->value) ->setMaxResults(1); /** * @var RowTypeAlias|false $row */ $row = $qb->executeQuery()->fetchAssociative(); if (! $row) { return null; } return $this->transformer->transform($row); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Infrastructure/Dbal/DbalGlobalMacroTransformer.php
centreon/src/App/MonitoringConfiguration/Infrastructure/Dbal/DbalGlobalMacroTransformer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\MonitoringConfiguration\Infrastructure\Dbal; use App\MonitoringConfiguration\Domain\Aggregate\GlobalMacro\GlobalMacro; use App\MonitoringConfiguration\Domain\Aggregate\GlobalMacro\GlobalMacroComment; use App\MonitoringConfiguration\Domain\Aggregate\GlobalMacro\GlobalMacroExpression; use App\MonitoringConfiguration\Domain\Aggregate\GlobalMacro\GlobalMacroId; use App\MonitoringConfiguration\Domain\Aggregate\GlobalMacro\GlobalMacroName; use App\MonitoringConfiguration\Domain\Aggregate\Poller\Poller; use App\Shared\Domain\Collection; use App\Shared\Infrastructure\TransformerInterface; /** * @phpstan-import-type RowTypeAlias from DbalGlobalMacroRepository * * @implements TransformerInterface<RowTypeAlias,GlobalMacro> */ final readonly class DbalGlobalMacroTransformer implements TransformerInterface { /** * @param RowTypeAlias $from */ public function transform(mixed $from): GlobalMacro { return new GlobalMacro( id: new GlobalMacroId($from['gm_resource_id']), name: new GlobalMacroName($from['gm_resource_name']), expression: new GlobalMacroExpression($from['gm_resource_line']), comment: $from['gm_resource_comment'] !== null ? new GlobalMacroComment($from['gm_resource_comment']) : null, activated: $from['gm_resource_activate'] === '1', isPassword: $from['gm_is_password'] === 1, pollers: new Collection([], Poller::class), // must be filled by callers ); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Shared/Application/Command/CommandBus.php
centreon/src/App/Shared/Application/Command/CommandBus.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\Shared\Application\Command; interface CommandBus { public function execute(object $command): mixed; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Shared/Application/Command/AsCommandHandler.php
centreon/src/App/Shared/Application/Command/AsCommandHandler.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\Shared\Application\Command; #[\Attribute(\Attribute::TARGET_CLASS)] final readonly class AsCommandHandler { }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Shared/Domain/Collection.php
centreon/src/App/Shared/Domain/Collection.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\Shared\Domain; use Webmozart\Assert\Assert; /** * @template T of object * * @implements \IteratorAggregate<int, T> */ final class Collection implements \IteratorAggregate, \Countable { /** @var array<T>|null */ private ?array $elements = null; /** @var (\Closure(): array<T>)|null */ private ?\Closure $initializer = null; /** * @param array<T>|\Closure(): array<T> $elements * @param class-string<T> $className */ public function __construct( array|\Closure $elements, private readonly string $className, ) { if (\is_array($elements)) { foreach ($elements as $element) { Assert::isInstanceOf($element, $this->className); } $this->elements = $elements; } else { $this->initializer = $elements; } } /** * @return \Traversable<int, T> */ public function getIterator(): \Traversable { $this->initialize(); Assert::notNull($this->elements); return new \ArrayIterator($this->elements); } public function count(): int { $this->initialize(); Assert::notNull($this->elements); return \count($this->elements); } /** * @return array<T> */ public function toArray(): array { $this->initialize(); Assert::notNull($this->elements); return $this->elements; } /** * @param T $element */ public function contains(object $element): bool { $this->initialize(); Assert::notNull($this->elements); return in_array($element, $this->elements, true); } /** * @param T $element */ public function add(object $element): void { Assert::isInstanceOf($element, $this->className); $this->initialize(); Assert::notNull($this->elements); $this->elements[] = $element; } public function remove(string|int $key): void { $this->initialize(); Assert::notNull($this->elements); if (! isset($this->elements[$key]) && ! \array_key_exists($key, $this->elements)) { return; } unset($this->elements[$key]); } /** * @param T $element */ public function removeElement(object $element): void { $this->initialize(); Assert::notNull($this->elements); /** @var int|string|false $key */ $key = array_search($element, $this->elements, true); if ($key === false) { return; } $this->remove($key); } private function initialize(): void { if ($this->elements !== null || ! $this->initializer instanceof \Closure) { return; } $elements = ($this->initializer)(); foreach ($elements as $element) { Assert::isInstanceOf($element, $this->className); } $this->elements = $elements; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Shared/Domain/Event/AggregateCreated.php
centreon/src/App/Shared/Domain/Event/AggregateCreated.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\Shared\Domain\Event; use App\Shared\Domain\Aggregate\AggregateRoot; abstract readonly class AggregateCreated implements EventInterface { public function __construct( public AggregateRoot $aggregate, public int $creatorId, public \DateTimeImmutable $firedAt = new \DateTimeImmutable(), ) { } public function firedAt(): \DateTimeImmutable { return $this->firedAt; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Shared/Domain/Event/AsEventHandler.php
centreon/src/App/Shared/Domain/Event/AsEventHandler.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\Shared\Domain\Event; #[\Attribute(\Attribute::TARGET_CLASS)] final class AsEventHandler { }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Shared/Domain/Event/EventInterface.php
centreon/src/App/Shared/Domain/Event/EventInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\Shared\Domain\Event; interface EventInterface { public function firedAt(): \DateTimeImmutable; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Shared/Domain/Event/EventBus.php
centreon/src/App/Shared/Domain/Event/EventBus.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\Shared\Domain\Event; interface EventBus { public function fire(EventInterface $event): void; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Shared/Domain/Exception/AggregateAlreadyExistsException.php
centreon/src/App/Shared/Domain/Exception/AggregateAlreadyExistsException.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\Shared\Domain\Exception; abstract class AggregateAlreadyExistsException extends \RuntimeException { /** * @param array<string, mixed> $criteria */ public function __construct( public readonly array $criteria, string $message = 'Resource already exists.', int $code = 0, ?\Throwable $previous = null, ) { parent::__construct($message, $code, $previous); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Shared/Domain/Exception/MissingIdException.php
centreon/src/App/Shared/Domain/Exception/MissingIdException.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\Shared\Domain\Exception; final class MissingIdException extends \RuntimeException { /** * @param class-string $className */ public function __construct(string $className) { parent::__construct(\sprintf('Id of "%s" is not defined. Maybe it has not been inserted in database yet?', $className)); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Shared/Domain/Exception/AggregateDoesNotExistException.php
centreon/src/App/Shared/Domain/Exception/AggregateDoesNotExistException.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\Shared\Domain\Exception; abstract class AggregateDoesNotExistException extends \RuntimeException { /** * @param array<string, mixed> $criteria */ public function __construct( public readonly array $criteria, string $message = 'Resource does not exists.', ?\Throwable $previous = null, ) { parent::__construct($message, previous: $previous); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Shared/Domain/Aggregate/AggregateRootId.php
centreon/src/App/Shared/Domain/Aggregate/AggregateRootId.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\Shared\Domain\Aggregate; use Webmozart\Assert\Assert; abstract readonly class AggregateRootId { public function __construct( public int $value, ) { Assert::positiveInteger($value); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Shared/Domain/Aggregate/AggregateRoot.php
centreon/src/App/Shared/Domain/Aggregate/AggregateRoot.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\Shared\Domain\Aggregate; use App\Shared\Domain\Exception\MissingIdException; abstract class AggregateRoot { public function __construct( private ?AggregateRootId $id, ) { } public function id(): AggregateRootId { if (! $this->id instanceof AggregateRootId) { throw new MissingIdException(static::class); } return $this->id; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Shared/Domain/Repository/Paginator.php
centreon/src/App/Shared/Domain/Repository/Paginator.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\Shared\Domain\Repository; /** * @template T of object * * @extends \IteratorAggregate<array-key, T> */ interface Paginator extends \IteratorAggregate, \Countable { public function getCurrentPage(): int; public function getItemsPerPage(): int; public function getLastPage(): int; public function getTotalItems(): int; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Shared/Infrastructure/TransformerInterface.php
centreon/src/App/Shared/Infrastructure/TransformerInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\Shared\Infrastructure; /** * @template TFrom * @template TTo */ interface TransformerInterface { /** * @param TFrom $from * * @return TTo */ public function transform(mixed $from): mixed; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Shared/Infrastructure/InMemory/InMemoryPaginator.php
centreon/src/App/Shared/Infrastructure/InMemory/InMemoryPaginator.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\Shared\Infrastructure\InMemory; use App\Shared\Domain\Collection; use App\Shared\Domain\Repository\Paginator; use Webmozart\Assert\Assert; /** * @template T of object * * @implements Paginator<T> */ final readonly class InMemoryPaginator implements Paginator { private int $lastPage; /** * @param Collection<T> $items */ public function __construct( private Collection $items, private int $totalItems, private int $currentPage, private int $itemsPerPage, ) { Assert::greaterThanEq($totalItems, 0); Assert::positiveInteger($currentPage); Assert::positiveInteger($itemsPerPage); $this->lastPage = (int) max(1, ceil($totalItems / $itemsPerPage)); } public function getItemsPerPage(): int { return $this->itemsPerPage; } public function getCurrentPage(): int { return $this->currentPage; } public function getLastPage(): int { return $this->lastPage; } public function getTotalItems(): int { return $this->totalItems; } public function count(): int { return count($this->items); } public function getIterator(): \Traversable { return $this->items; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Shared/Infrastructure/Legacy/LegacyHttpExceptionListener.php
centreon/src/App/Shared/Infrastructure/Legacy/LegacyHttpExceptionListener.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\Shared\Infrastructure\Legacy; use ApiPlatform\Validator\Exception\ValidationException; use Centreon\Domain\Exception\EntityNotFoundException; use Symfony\Component\DependencyInjection\Attribute\Autowire; use Symfony\Component\EventDispatcher\Attribute\AsEventListener; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpKernel\Event\ExceptionEvent; use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException; use Symfony\Component\Security\Core\Exception\AccessDeniedException; #[AsEventListener] final readonly class LegacyHttpExceptionListener { /** * @var array<class-string, int> */ private const LEGACY_EXCEPTION_TO_STATUS = [ AccessDeniedException::class => 403, EntityNotFoundException::class => 404, MethodNotAllowedHttpException::class => 404, ]; /** * @param array<class-string, int> $exceptionToStatus */ public function __construct( #[Autowire(param: 'api_platform.exception_to_status')] private array $exceptionToStatus, ) { } public function __invoke(ExceptionEvent $event): void { $exception = $event->getThrowable(); // this case is handled by LegacyValidationExceptionNormalizer if ($exception instanceof ValidationException) { return; } // get status code from exception $statusCode = $exception instanceof HttpExceptionInterface ? $exception->getStatusCode() : null; // try to override status code by API Platform foreach ($this->exceptionToStatus as $class => $status) { if (is_a($exception::class, $class, true)) { $statusCode = $status; break; } } // if still no status code, try to fetch it from legacy exception mapping if (! $statusCode) { foreach (self::LEGACY_EXCEPTION_TO_STATUS as $class => $status) { if (is_a($exception::class, $class, true)) { $statusCode = $status; break; } } } // if still no status code, compute it from the exception (legacy way) if (! $statusCode) { $errorCode = $exception->getCode(); $statusCode = (is_int($errorCode) && $errorCode >= 100 && $errorCode < 600) ? $errorCode : 500; } $event->setResponse(new JsonResponse( status: $statusCode, data: [ 'code' => $exception->getCode(), 'message' => $exception->getMessage(), ], )); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Shared/Infrastructure/Legacy/LegacySessionApiAuthenticatorWrapper.php
centreon/src/App/Shared/Infrastructure/Legacy/LegacySessionApiAuthenticatorWrapper.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\Shared\Infrastructure\Legacy; use Security\SessionAPIAuthenticator; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface; use Symfony\Component\Security\Http\Authenticator\Passport\Passport; use Webmozart\Assert\Assert; final readonly class LegacySessionApiAuthenticatorWrapper implements AuthenticatorInterface { private SessionAPIAuthenticator $legacyAuthenticator; public function __construct(LegacyContainer $legacyContainer) { $legacyAuthenticator = $legacyContainer->get('security.provider.sessionapi'); Assert::isInstanceOf($legacyAuthenticator, SessionAPIAuthenticator::class); $this->legacyAuthenticator = $legacyAuthenticator; } public function supports(Request $request): bool { return $this->legacyAuthenticator->supports($request); } public function authenticate(Request $request): Passport { return $this->legacyAuthenticator->authenticate($request); } public function createToken(Passport $passport, string $firewallName): TokenInterface { return $this->legacyAuthenticator->createToken($passport, $firewallName); } public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response { return $this->legacyAuthenticator->onAuthenticationSuccess($request, $token, $firewallName); } public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response { return $this->legacyAuthenticator->onAuthenticationFailure($request, $exception); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Shared/Infrastructure/Legacy/LegacyContainer.php
centreon/src/App/Shared/Infrastructure/Legacy/LegacyContainer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\Shared\Infrastructure\Legacy; use App\Kernel as LegacyKernel; use Symfony\Component\DependencyInjection\Attribute\Lazy; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpKernel\KernelInterface; /** * This class should be used **exceptionally**. * In most cases, the new app should never call the legacy. */ #[Lazy] class LegacyContainer { private ContainerInterface $legacyContainer; public function __construct( private KernelInterface $kernel, ) { $kernel = new LegacyKernel($this->kernel->getEnvironment(), $this->kernel->isDebug()); $kernel->boot(); $this->legacyContainer = $kernel->getContainer(); } public function get(string $id): object { return $this->legacyContainer->get($id, ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Shared/Infrastructure/Legacy/LegacyWebSsoAuthenticatorWrapper.php
centreon/src/App/Shared/Infrastructure/Legacy/LegacyWebSsoAuthenticatorWrapper.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\Shared\Infrastructure\Legacy; use Security\WebSSOAuthenticator; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface; use Symfony\Component\Security\Http\Authenticator\Passport\Passport; use Webmozart\Assert\Assert; final readonly class LegacyWebSsoAuthenticatorWrapper implements AuthenticatorInterface { private WebSSOAuthenticator $legacyAuthenticator; public function __construct(LegacyContainer $legacyContainer) { $legacyAuthenticator = $legacyContainer->get('security.provider.websso'); Assert::isInstanceOf($legacyAuthenticator, WebSSOAuthenticator::class); $this->legacyAuthenticator = $legacyAuthenticator; } public function supports(Request $request): bool { return $this->legacyAuthenticator->supports($request); } public function authenticate(Request $request): Passport { return $this->legacyAuthenticator->authenticate($request); } public function createToken(Passport $passport, string $firewallName): TokenInterface { return $this->legacyAuthenticator->createToken($passport, $firewallName); } public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response { return $this->legacyAuthenticator->onAuthenticationSuccess($request, $token, $firewallName); } public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response { return $this->legacyAuthenticator->onAuthenticationFailure($request, $exception); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Shared/Infrastructure/Legacy/LegacyValidationExceptionNormalizer.php
centreon/src/App/Shared/Infrastructure/Legacy/LegacyValidationExceptionNormalizer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\Shared\Infrastructure\Legacy; use ApiPlatform\Validator\Exception\ValidationException; use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface; use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait; use Symfony\Component\Serializer\Normalizer\NormalizerInterface; /** * Converts ValidationException in order to have a legacy compliant shape. */ final class LegacyValidationExceptionNormalizer implements NormalizerInterface, NormalizerAwareInterface { use NormalizerAwareTrait; private const ALREADY_CALLED = self::class . '_called'; /** * @param array<string, mixed> $context * * @return array{code: int, message: string} */ public function normalize(mixed $data, ?string $format = null, array $context = []): array { $context[self::ALREADY_CALLED] = true; /** @var array{violations: list<array{propertyPath: string, message: string, code: string}>} $normalized */ $normalized = $this->normalizer->normalize($data, $format, $context); $messages = array_map($this->convertViolationToLegacy(...), $normalized['violations']); return [ 'code' => 400, 'message' => implode("\n", $messages) . "\n", ]; } /** * @param array<string, mixed> $context */ public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool { if ($context[self::ALREADY_CALLED] ?? false) { return false; } return $data instanceof ValidationException; } public function getSupportedTypes(?string $format): array { return [ ValidationException::class => false, ]; } /** * @param array{propertyPath: string, message: string, code: string} $violation */ private function convertViolationToLegacy(array $violation): string { return sprintf('[%s] %s', $violation['propertyPath'], $violation['message']); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Shared/Infrastructure/Legacy/LegacySessionSyncListener.php
centreon/src/App/Shared/Infrastructure/Legacy/LegacySessionSyncListener.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\Shared\Infrastructure\Legacy; use Symfony\Component\DependencyInjection\Attribute\Autowire; use Symfony\Component\EventDispatcher\Attribute\AsEventListener; use Symfony\Component\HttpFoundation\Session\Session; use Symfony\Component\HttpFoundation\Session\Storage\SessionStorageFactoryInterface; use Symfony\Component\HttpKernel\Event\RequestEvent; #[AsEventListener(priority: 1024)] final readonly class LegacySessionSyncListener { public function __construct( #[Autowire(service: 'session.storage.factory.native')] private SessionStorageFactoryInterface $sessionStorageFactory, ) { } public function __invoke(RequestEvent $event): void { if (PHP_SAPI === 'cli') { return; } // If session is already started by legacy, attach it to Symfony if (session_status() === PHP_SESSION_ACTIVE) { $request = $event->getRequest(); if (! $request->hasSession()) { $session = new Session($this->sessionStorageFactory->createStorage($request)); $request->setSession($session); } } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Shared/Infrastructure/Legacy/LegacySecurity.php
centreon/src/App/Shared/Infrastructure/Legacy/LegacySecurity.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\Shared\Infrastructure\Legacy; use Centreon\Domain\Contact\Contact; use Symfony\Bundle\SecurityBundle\Security; use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException; final readonly class LegacySecurity { public function __construct( private Security $security, ) { } public function getUserId(): int { $user = $this->security->getUser(); if (! $user instanceof Contact) { throw new AuthenticationCredentialsNotFoundException('The user is not authenticated.'); } return $user->getId(); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Shared/Infrastructure/Legacy/LegacyContactProviderWrapper.php
centreon/src/App/Shared/Infrastructure/Legacy/LegacyContactProviderWrapper.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\Shared\Infrastructure\Legacy; use Centreon\Domain\Contact\ContactProvider; use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Core\User\UserProviderInterface; use Webmozart\Assert\Assert; /** * @implements UserProviderInterface<UserInterface> */ final readonly class LegacyContactProviderWrapper implements UserProviderInterface { private ContactProvider $legacyContactProvider; public function __construct(LegacyContainer $legacyContainer) { $legacyAuthenticator = $legacyContainer->get('contact.provider'); Assert::isInstanceOf($legacyAuthenticator, ContactProvider::class); $this->legacyContactProvider = $legacyAuthenticator; } public function refreshUser(UserInterface $user): UserInterface { return $this->legacyContactProvider->refreshUser($user); } public function supportsClass(string $class): bool { return $this->legacyContactProvider->supportsClass($class); } public function loadUserByIdentifier(string $identifier): UserInterface { return $this->legacyContactProvider->loadUserByIdentifier($identifier); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Shared/Infrastructure/Legacy/ForwardLegacyRoutesListener.php
centreon/src/App/Shared/Infrastructure/Legacy/ForwardLegacyRoutesListener.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\Shared\Infrastructure\Legacy; use Symfony\Component\DependencyInjection\Attribute\Autowire; use Symfony\Component\EventDispatcher\Attribute\AsEventListener; use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\HttpKernel\EventListener\RouterListener; use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; #[AsEventListener(priority: 32)] final readonly class ForwardLegacyRoutesListener { public function __construct( #[Autowire(service: 'router_listener')] private RouterListener $routerListener, private LegacyKernelWrapper $legacyKernel, ) { } public function __invoke(RequestEvent $event): void { try { // try to handle the request using the current app $this->routerListener->onKernelRequest($event); } catch (NotFoundHttpException|MethodNotAllowedHttpException) { // if the route is not found with the given method in the current app, // it may be available in the legacy. Therefore, handle the request // using the legacy app $response = $this->legacyKernel->handle($event->getRequest(), $event->getRequestType(), catch: false); $event->setResponse($response); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Shared/Infrastructure/Legacy/LegacyKernelWrapper.php
centreon/src/App/Shared/Infrastructure/Legacy/LegacyKernelWrapper.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\Shared\Infrastructure\Legacy; use App\Kernel as LegacyKernel; use App\Shared\Infrastructure\Symfony\Kernel; use Symfony\Component\DependencyInjection\Attribute\Autowire; use Symfony\Component\Dotenv\Dotenv; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\HttpKernel\KernelInterface; final readonly class LegacyKernelWrapper implements HttpKernelInterface { public function __construct( #[Autowire(service: Kernel::class)] private KernelInterface $kernel, #[Autowire(param: 'kernel.project_dir')] private string $projectDir, ) { } public function handle(Request $request, int $type = 1, bool $catch = true): Response { // make the current container available in the legacy $newContainer = $this->kernel->getContainer(); global $newContainer; $this->bootstrapLegacy(); $legacyKernel = new LegacyKernel($this->kernel->getEnvironment(), $this->kernel->isDebug()); // handle the request by the legacy $legacyResponse = $legacyKernel->handle($request, $type, $catch); $legacyKernel->terminate($request, $legacyResponse); return $legacyResponse; } private function bootstrapLegacy(): void { global $constants, $conf_centreon, $centreon_path, $classdir; $constants = []; $conf_centreon = []; require $this->projectDir . '/config/centreon.config.php'; (new Dotenv())->bootEnv($this->projectDir . '/.env'); (new Dotenv())->populate($constants); (new Dotenv())->populate($conf_centreon); require_once $this->projectDir . '/container.php'; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Shared/Infrastructure/Legacy/LegacyTokenApiAuthenticatorWrapper.php
centreon/src/App/Shared/Infrastructure/Legacy/LegacyTokenApiAuthenticatorWrapper.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\Shared\Infrastructure\Legacy; use Security\TokenAPIAuthenticator; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface; use Symfony\Component\Security\Http\Authenticator\Passport\Passport; use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface; use Webmozart\Assert\Assert; final readonly class LegacyTokenApiAuthenticatorWrapper implements AuthenticatorInterface, AuthenticationEntryPointInterface { private TokenAPIAuthenticator $legacyAuthenticator; public function __construct(LegacyContainer $legacyContainer) { $legacyAuthenticator = $legacyContainer->get('security.provider.tokenapi'); Assert::isInstanceOf($legacyAuthenticator, TokenAPIAuthenticator::class); $this->legacyAuthenticator = $legacyAuthenticator; } public function supports(Request $request): bool { return $this->legacyAuthenticator->supports($request); } public function authenticate(Request $request): Passport { return $this->legacyAuthenticator->authenticate($request); } public function createToken(Passport $passport, string $firewallName): TokenInterface { return $this->legacyAuthenticator->createToken($passport, $firewallName); } public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response { return $this->legacyAuthenticator->onAuthenticationSuccess($request, $token, $firewallName); } public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response { return $this->legacyAuthenticator->onAuthenticationFailure($request, $exception); } public function start(Request $request, ?AuthenticationException $authException = null): Response { return $this->legacyAuthenticator->start($request, $authException); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Shared/Infrastructure/ApiPlatform/MergeDocumentationCommand.php
centreon/src/App/Shared/Infrastructure/ApiPlatform/MergeDocumentationCommand.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\Shared\Infrastructure\ApiPlatform; use ApiPlatform\OpenApi\Factory\OpenApiFactoryInterface; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Attribute\Option; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Style\SymfonyStyle; use Symfony\Component\DependencyInjection\Attribute\Autowire; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Serializer\Encoder\DecoderInterface; use Symfony\Component\Serializer\Normalizer\NormalizerInterface; use Symfony\Component\Yaml\Yaml; #[AsCommand(name: 'app:open-api:merge')] final readonly class MergeDocumentationCommand { private string $documentationPath; public function __construct( #[Autowire(param: 'kernel.project_dir')] private string $projectDir, private readonly OpenApiFactoryInterface $openApiFactory, private DecoderInterface $decoder, private readonly NormalizerInterface $normalizer, ) { $this->documentationPath = $this->projectDir . '/doc/API/centreon-api.yaml'; } public function __invoke(SymfonyStyle $io, #[Option] bool $override = false): int { $filesystem = new Filesystem(); $io->title('Merge new OpenAPI documentation'); /** * @var array{ * paths: array<string, mixed>, * tags: array<array{name: string, ...}>, * components: array{ * parameters: array<string, mixed>, * responses: array<string, mixed>, * schemas: array<string, mixed>, * }, * } */ $doc = $this->decoder->decode($filesystem->readFile($this->documentationPath), 'yaml'); /** * @var array{ * paths: array{paths: array<string, mixed>}, * tags: array<array{name: string, ...}>, * components: array{ * parameters: array<string, mixed>, * responses: array<string, mixed>, * schemas: array<string, mixed>, * }, * } */ $newDoc = $this->normalizer->normalize(($this->openApiFactory)()); $io->section('Paths...'); foreach ($newDoc['paths']['paths'] as $url => $path) { /** @var string $url */ $url = preg_replace('#/api/latest#', '', (string) $url); $io->text($url); if (! $override && isset($doc['paths'][$url]) && ! $this->askOverride($io, $url)) { continue; } $doc['paths'][$url] = $path; } $io->section('Tags...'); $actualTagNames = array_column($doc['tags'], 'name'); foreach ($newDoc['tags'] as $newTag) { $tagName = $newTag['name']; $io->text($tagName); if (! $override && \in_array($tagName, $actualTagNames, true) && ! $this->askOverride($io, $tagName)) { continue; } $found = false; foreach ($doc['tags'] as $key => $tag) { if ($tag['name'] === $tagName) { $doc['tags'][$key] = $newTag; $found = true; break; } } if (! $found) { $doc['tags'][] = $newTag; $actualTagNames[] = $tagName; } } $io->section('Parameters...'); foreach ($newDoc['components']['parameters'] as $name => $parameter) { $io->text($name); if (! $override && isset($doc['components']['parameters'][$name]) && ! $this->askOverride($io, $name)) { continue; } $doc['components']['parameters'][$name] = $parameter; } $io->section('Responses...'); foreach ($newDoc['components']['responses'] as $name => $response) { $io->text($name); if (! $override && isset($doc['components']['responses'][$name]) && ! $this->askOverride($io, $name)) { continue; } $doc['components']['responses'][$name] = $response; } $io->section('Schemas...'); foreach ($newDoc['components']['schemas'] as $name => $schema) { $io->text($name); if (! $override && isset($doc['components']['schemas'][$name]) && ! $this->askOverride($io, $name)) { continue; } $doc['components']['schemas'][$name] = $schema; } $yaml = Yaml::dump($doc, 10, 2, Yaml::DUMP_OBJECT_AS_MAP | Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE | Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK | Yaml::DUMP_NUMERIC_KEY_AS_STRING); $filesystem->dumpFile($this->documentationPath, $yaml); return Command::SUCCESS; } private function askOverride(SymfonyStyle $io, string $subject): bool { return $io->choice(\sprintf('"%s" already exist.', $subject), ['skip', 'override'], 'override') === 'override'; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Shared/Infrastructure/Symfony/Kernel.php
centreon/src/App/Shared/Infrastructure/Symfony/Kernel.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\Shared\Infrastructure\Symfony; use App\Shared\Application\Command\AsCommandHandler; use App\Shared\Domain\Event\AsEventHandler; use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait; use Symfony\Component\DependencyInjection\ChildDefinition; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; use Symfony\Component\HttpKernel\Kernel as BaseKernel; final class Kernel extends BaseKernel { use MicroKernelTrait; public function getCacheDir(): string { return '/var/cache/centreon/symfony.new'; } public function getLogDir(): string { return '/var/log/centreon/symfony.new'; } public function getProjectDir(): string { return \dirname(__DIR__, 5); } protected function configureContainer(ContainerConfigurator $container): void { $configDir = $this->getConfigDir(); $container->import($configDir . '/{packages}/*.yaml'); $container->import($configDir . '/{packages}/' . $this->environment . '/*.yaml'); $container->import($configDir . '/{services}/*.php'); $container->import($configDir . '/{services}/' . $this->environment . '/*.php'); } protected function build(ContainerBuilder $container): void { parent::build($container); $container->registerAttributeForAutoconfiguration(AsCommandHandler::class, static function (ChildDefinition $definition): void { $definition->addTag('messenger.message_handler', ['bus' => 'command.bus']); }); $container->registerAttributeForAutoconfiguration(AsEventHandler::class, static function (ChildDefinition $definition): void { $definition->addTag('messenger.message_handler', ['bus' => 'event.bus']); }); } private function getConfigDir(): string { return $this->getProjectDir() . '/config.new'; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Shared/Infrastructure/Messenger/MessengerEventBus.php
centreon/src/App/Shared/Infrastructure/Messenger/MessengerEventBus.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\Shared\Infrastructure\Messenger; use App\Shared\Domain\Event\EventBus; use App\Shared\Domain\Event\EventInterface; use Symfony\Component\Messenger\Exception\HandlerFailedException; use Symfony\Component\Messenger\MessageBusInterface; final readonly class MessengerEventBus implements EventBus { public function __construct( private MessageBusInterface $eventBus, ) { } public function fire(EventInterface $event): void { try { $this->eventBus->dispatch($event); } catch (HandlerFailedException $e) { /** @var array{0: \Throwable} $exceptions */ $exceptions = $e->getWrappedExceptions(); throw current($exceptions); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Shared/Infrastructure/Messenger/MessengerCommandBus.php
centreon/src/App/Shared/Infrastructure/Messenger/MessengerCommandBus.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\Shared\Infrastructure\Messenger; use App\Shared\Application\Command\CommandBus; use Symfony\Component\Messenger\Exception\HandlerFailedException; use Symfony\Component\Messenger\HandleTrait; use Symfony\Component\Messenger\MessageBusInterface; final class MessengerCommandBus implements CommandBus { use HandleTrait; public function __construct(MessageBusInterface $commandBus) { $this->messageBus = $commandBus; } public function execute(object $command): mixed { try { return $this->handle($command); } catch (HandlerFailedException $e) { /** @var list<\Throwable> $exceptions */ $exceptions = $e->getWrappedExceptions(); $exception = $exceptions[0] ?? $e->getPrevious() ?? $e; throw $exception; } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Shared/Infrastructure/Messenger/DoctrineTransactionMiddleware.php
centreon/src/App/Shared/Infrastructure/Messenger/DoctrineTransactionMiddleware.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\Shared\Infrastructure\Messenger; use Doctrine\DBAL\Connection; use Symfony\Component\DependencyInjection\Attribute\Autowire; use Symfony\Component\Messenger\Envelope; use Symfony\Component\Messenger\Middleware\MiddlewareInterface; use Symfony\Component\Messenger\Middleware\StackInterface; final readonly class DoctrineTransactionMiddleware implements MiddlewareInterface { public function __construct( #[Autowire(service: 'doctrine.dbal.default_connection')] private Connection $connection, ) { } public function handle(Envelope $envelope, StackInterface $stack): Envelope { $this->connection->beginTransaction(); try { $envelope = $stack->next()->handle($envelope, $stack); $this->connection->commit(); return $envelope; } catch (\Throwable $th) { $this->connection->rollBack(); throw $th; } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Shared/Infrastructure/Dbal/DbalRepository.php
centreon/src/App/Shared/Infrastructure/Dbal/DbalRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace App\Shared\Infrastructure\Dbal; abstract readonly class DbalRepository { final protected function setId(object $object, mixed $id): void { $reflectionClass = new \ReflectionClass($object); while ($reflectionClass) { if ($reflectionClass->hasProperty('id')) { $reflectionProperty = $reflectionClass->getProperty('id'); $reflectionProperty->setAccessible(true); if ($reflectionProperty->isStatic()) { throw new \LogicException(\sprintf('Property "%s::$id" must not be static.', $reflectionClass->getName())); } if ($reflectionProperty->isReadOnly()) { throw new \LogicException(\sprintf('Cannot set readonly property "%s::$id".', $reflectionClass->getName())); } $reflectionProperty->setValue($object, $id); return; } $reflectionClass = $reflectionClass->getParentClass(); } throw new \LogicException(\sprintf('Property "id" not found in "%s" hierarchy.', $object::class)); } /** * Hydrate a "to many" relation of a primary entity. * * @template TPrimary of object * @template TRelated of object * @template TRelatedRow of array<string, mixed> * * @param TPrimary $primaryEntity The entity to be hydrated * @param array<TRelatedRow> $relatedRows Raw joined rows * @param callable(TRelatedRow): TRelated $relatedFactoryCallback Callback to create related entity * @param callable(TPrimary, TRelated): void $relationCallback Callback to set relationship */ final protected function hydrateToManyRelation( object $primaryEntity, array $relatedRows, string $relatedIdKey, callable $relatedFactoryCallback, callable $relationCallback, ): void { $relatedEntities = []; foreach ($relatedRows as $row) { $relatedId = $row[$relatedIdKey]; $relatedEntities[$relatedId] ??= $relatedFactoryCallback($row); $relationCallback($primaryEntity, $relatedEntities[$relatedId]); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostTemplate/Application/UseCase/PartialUpdateHostTemplate/PartialUpdateHostTemplate.php
centreon/src/Core/HostTemplate/Application/UseCase/PartialUpdateHostTemplate/PartialUpdateHostTemplate.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostTemplate\Application\UseCase\PartialUpdateHostTemplate; 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\Application\Common\UseCase\NoContentResponse; use Core\Application\Common\UseCase\NotFoundResponse; use Core\Application\Common\UseCase\PresenterInterface; use Core\Command\Domain\Model\CommandType; use Core\CommandMacro\Application\Repository\ReadCommandMacroRepositoryInterface; use Core\CommandMacro\Domain\Model\CommandMacro; use Core\CommandMacro\Domain\Model\CommandMacroType; use Core\Common\Application\Converter\YesNoDefaultConverter; 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\Host\Application\Converter\HostEventConverter; use Core\Host\Application\InheritanceManager; use Core\Host\Domain\Model\SnmpVersion; use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface; use Core\HostCategory\Application\Repository\WriteHostCategoryRepositoryInterface; use Core\HostCategory\Domain\Model\HostCategory; use Core\HostTemplate\Application\Exception\HostTemplateException; use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface; use Core\HostTemplate\Application\Repository\WriteHostTemplateRepositoryInterface; use Core\HostTemplate\Domain\Model\HostTemplate; use Core\Macro\Application\Repository\ReadHostMacroRepositoryInterface; use Core\Macro\Application\Repository\WriteHostMacroRepositoryInterface; 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\Security\Vault\Domain\Model\VaultConfiguration; use Utility\Difference\BasicDifference; final class PartialUpdateHostTemplate { use LoggerTrait; use VaultTrait; /** @var AccessGroup[] */ private array $accessGroups = []; public function __construct( private readonly ReadHostTemplateRepositoryInterface $readHostTemplateRepository, private readonly ReadHostMacroRepositoryInterface $readHostMacroRepository, private readonly ReadCommandMacroRepositoryInterface $readCommandMacroRepository, private readonly WriteHostMacroRepositoryInterface $writeHostMacroRepository, private readonly ReadHostCategoryRepositoryInterface $readHostCategoryRepository, private readonly WriteHostCategoryRepositoryInterface $writeHostCategoryRepository, private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository, private readonly WriteHostTemplateRepositoryInterface $writeHostTemplateRepository, private readonly PartialUpdateHostTemplateValidation $validation, private readonly OptionService $optionService, private readonly DataStorageEngineInterface $dataStorageEngine, private readonly ContactInterface $user, private readonly WriteVaultRepositoryInterface $writeVaultRepository, private readonly ReadVaultRepositoryInterface $readVaultRepository, ) { $this->writeVaultRepository->setCustomPath(AbstractVaultRepository::HOST_VAULT_PATH); } /** * @param PresenterInterface $presenter * @param PartialUpdateHostTemplateRequest $request * @param int $hostTemplateId */ public function __invoke( PartialUpdateHostTemplateRequest $request, PresenterInterface $presenter, int $hostTemplateId, ): void { try { if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_HOSTS_TEMPLATES_READ_WRITE)) { $this->error( "User doesn't have sufficient rights to edit host templates", ['user_id' => $this->user->getId()] ); $presenter->setResponseStatus( new ForbiddenResponse(HostTemplateException::writeActionsNotAllowed()) ); return; } if (! $this->user->isAdmin()) { $this->accessGroups = $this->readAccessGroupRepository->findByContact($this->user); $this->validation->accessGroups = $this->accessGroups; $hostTemplate = $this->readHostTemplateRepository->findByIdAndAccessGroups( $hostTemplateId, $this->accessGroups ); } else { $hostTemplate = $this->readHostTemplateRepository->findById($hostTemplateId); } if ($hostTemplate === null) { $this->error( 'Host template not found', ['host_template_id' => $hostTemplateId] ); $presenter->setResponseStatus(new NotFoundResponse('Host template')); return; } if ($hostTemplate->isLocked()) { $this->error( 'Host template is locked, partial update refused.', ['host_template_id' => $hostTemplateId] ); $presenter->setResponseStatus( new InvalidArgumentResponse(HostTemplateException::hostIsLocked($hostTemplateId)) ); return; } $this->updatePropertiesInTransaction($request, $hostTemplate); $presenter->setResponseStatus(new NoContentResponse()); } catch (HostTemplateException $ex) { $presenter->setResponseStatus( match ($ex->getCode()) { HostTemplateException::CODE_CONFLICT => new ConflictResponse($ex), default => new ErrorResponse($ex), } ); $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); } catch (\Throwable $ex) { $presenter->setResponseStatus(new ErrorResponse(HostTemplateException::partialUpdateHostTemplate())); $this->error($ex->getMessage()); } } /** * @param PartialUpdateHostTemplateRequest $request * @param HostTemplate $hostTemplate * * @throws \Throwable */ private function updatePropertiesInTransaction( PartialUpdateHostTemplateRequest $request, HostTemplate $hostTemplate, ): void { try { $this->dataStorageEngine->startTransaction(); if ($this->writeVaultRepository->isVaultConfigured()) { $this->retrieveHostUuidFromVault($hostTemplate); } $this->updateHostTemplate($request, $hostTemplate); // Note: parent templates must be updated before macros for macro inheritance resolution $this->updateParentTemplates($request, $hostTemplate->getId()); $this->updateMacros($request, $hostTemplate); $this->updateCategories($request, $hostTemplate); $this->dataStorageEngine->commitTransaction(); } catch (\Throwable $ex) { $this->error("Rollback of 'PartialUpdateHostTemplate' transaction."); $this->dataStorageEngine->rollbackTransaction(); throw $ex; } } /** * @param PartialUpdateHostTemplateRequest $request * @param HostTemplate $hostTemplate * * @throws \Throwable|AssertionFailedException|HostTemplateException */ private function updateHostTemplate(PartialUpdateHostTemplateRequest $request, HostTemplate $hostTemplate): void { $this->info('PartialUpdateHostTemplate: update host template', ['host_template_id' => $hostTemplate->getId()]); $inheritanceMode = $this->optionService->findSelectedOptions(['inheritance_mode']); $inheritanceMode = isset($inheritanceMode[0]) ? (int) $inheritanceMode[0]->getValue() : 0; if (! $request->name instanceof NoValue) { $this->validation->assertIsValidName($request->name, $hostTemplate); $hostTemplate->setName($request->name); } if (! $request->alias instanceof NoValue) { $hostTemplate->setAlias($request->alias); } if (! $request->snmpVersion instanceof NoValue) { $hostTemplate->setSnmpVersion( $request->snmpVersion === '' ? null : SnmpVersion::from($request->snmpVersion) ); } if (! $request->timezoneId instanceof NoValue) { $this->validation->assertIsValidTimezone($request->timezoneId); $hostTemplate->setTimezoneId($request->timezoneId); } if (! $request->severityId instanceof NoValue) { $this->validation->assertIsValidSeverity($request->severityId); $hostTemplate->setSeverityId($request->severityId); } if (! $request->checkCommandId instanceof NoValue) { $this->validation->assertIsValidCommand($request->checkCommandId, CommandType::Check, 'checkCommandId'); $hostTemplate->setCheckCommandId($request->checkCommandId); } if (! $request->checkCommandArgs instanceof NoValue) { $hostTemplate->setCheckCommandArgs($request->checkCommandArgs); } if (! $request->checkTimeperiodId instanceof NoValue) { $this->validation->assertIsValidTimePeriod($request->checkTimeperiodId, 'checkTimeperiodId'); $hostTemplate->setCheckTimeperiodId($request->checkTimeperiodId); } if (! $request->maxCheckAttempts instanceof NoValue) { $hostTemplate->setMaxCheckAttempts($request->maxCheckAttempts); } if (! $request->normalCheckInterval instanceof NoValue) { $hostTemplate->setNormalCheckInterval($request->normalCheckInterval); } if (! $request->retryCheckInterval instanceof NoValue) { $hostTemplate->setRetryCheckInterval($request->retryCheckInterval); } if (! $request->activeCheckEnabled instanceof NoValue) { $hostTemplate->setActiveCheckEnabled(YesNoDefaultConverter::fromScalar($request->activeCheckEnabled)); } if (! $request->passiveCheckEnabled instanceof NoValue) { $hostTemplate->setPassiveCheckEnabled(YesNoDefaultConverter::fromScalar($request->passiveCheckEnabled)); } if (! $request->notificationEnabled instanceof NoValue) { $hostTemplate->setNotificationEnabled(YesNoDefaultConverter::fromScalar($request->notificationEnabled)); } if (! $request->notificationOptions instanceof NoValue) { $hostTemplate->setNotificationOptions( $request->notificationOptions === null ? [] : HostEventConverter::fromBitFlag($request->notificationOptions) ); } if (! $request->notificationInterval instanceof NoValue) { $hostTemplate->setNotificationInterval($request->notificationInterval); } if (! $request->notificationTimeperiodId instanceof NoValue) { $this->validation->assertIsValidTimePeriod($request->notificationTimeperiodId, 'notificationTimeperiodId'); $hostTemplate->setNotificationTimeperiodId($request->notificationTimeperiodId); } if (! $request->addInheritedContactGroup instanceof NoValue) { $hostTemplate->setAddInheritedContactGroup( $inheritanceMode === 1 ? $request->addInheritedContactGroup : false ); } if (! $request->addInheritedContact instanceof NoValue) { $hostTemplate->setAddInheritedContact( $inheritanceMode === 1 ? $request->addInheritedContact : false ); } if (! $request->firstNotificationDelay instanceof NoValue) { $hostTemplate->setFirstNotificationDelay($request->firstNotificationDelay); } if (! $request->recoveryNotificationDelay instanceof NoValue) { $hostTemplate->setRecoveryNotificationDelay($request->recoveryNotificationDelay); } if (! $request->acknowledgementTimeout instanceof NoValue) { $hostTemplate->setAcknowledgementTimeout($request->acknowledgementTimeout); } if (! $request->freshnessChecked instanceof NoValue) { $hostTemplate->setFreshnessChecked(YesNoDefaultConverter::fromScalar($request->freshnessChecked)); } if (! $request->freshnessThreshold instanceof NoValue) { $hostTemplate->setFreshnessThreshold($request->freshnessThreshold); } if (! $request->flapDetectionEnabled instanceof NoValue) { $hostTemplate->setFlapDetectionEnabled(YesNoDefaultConverter::fromScalar($request->flapDetectionEnabled)); } if (! $request->lowFlapThreshold instanceof NoValue) { $hostTemplate->setLowFlapThreshold($request->lowFlapThreshold); } if (! $request->highFlapThreshold instanceof NoValue) { $hostTemplate->setHighFlapThreshold($request->highFlapThreshold); } if (! $request->eventHandlerEnabled instanceof NoValue) { $hostTemplate->setEventHandlerEnabled(YesNoDefaultConverter::fromScalar($request->eventHandlerEnabled)); } if (! $request->eventHandlerCommandId instanceof NoValue) { $this->validation->assertIsValidCommand($request->eventHandlerCommandId, null, 'eventHandlerCommandId'); $hostTemplate->setEventHandlerCommandId($request->eventHandlerCommandId); } if (! $request->eventHandlerCommandArgs instanceof NoValue) { $hostTemplate->setEventHandlerCommandArgs($request->eventHandlerCommandArgs); } if (! $request->noteUrl instanceof NoValue) { $hostTemplate->setNoteUrl($request->noteUrl); } if (! $request->note instanceof NoValue) { $hostTemplate->setNote($request->note); } if (! $request->actionUrl instanceof NoValue) { $hostTemplate->setActionUrl($request->actionUrl); } if (! $request->iconId instanceof NoValue) { $this->validation->assertIsValidIcon($request->iconId); $hostTemplate->setIconId($request->iconId); } if (! $request->iconAlternative instanceof NoValue) { $hostTemplate->setIconAlternative($request->iconAlternative); } if (! $request->comment instanceof NoValue) { $hostTemplate->setComment($request->comment); } $this->updateSnmpCommunity($hostTemplate, $request->snmpCommunity); $this->writeHostTemplateRepository->update($hostTemplate); } /** * @param PartialUpdateHostTemplateRequest $request * @param HostTemplate $hostTemplate * * @throws \Throwable */ private function updateMacros(PartialUpdateHostTemplateRequest $request, HostTemplate $hostTemplate): void { $this->info( 'PartialUpdateHostTemplate: update macros', ['host_template_id' => $hostTemplate->getId(), 'macros' => $request->macros] ); if ($request->macros instanceof NoValue) { $this->info('Macros not provided, nothing to update'); return; } /** * @var array<string,Macro> $directMacros * @var array<string,Macro> $inheritedMacros * @var array<string,CommandMacro> $commandMacros */ [$directMacros, $inheritedMacros, $commandMacros] = $this->findOriginalMacros($hostTemplate); $macros = []; foreach ($request->macros as $data) { $macro = HostMacroFactory::create($data, $hostTemplate->getId(), $directMacros, $inheritedMacros); $macros[$macro->getName()] = $macro; } $macrosDiff = new MacroDifference(); $macrosDiff->compute($directMacros, $inheritedMacros, $commandMacros, $macros); MacroManager::setOrder($macrosDiff, $macros, $directMacros); foreach ($macrosDiff->removedMacros as $macro) { $this->updateMacroInVault($macro, 'DELETE'); $this->writeHostMacroRepository->delete($macro); } foreach ($macrosDiff->updatedMacros as $macro) { $macro = $this->updateMacroInVault($macro, 'INSERT'); $this->writeHostMacroRepository->update($macro); } foreach ($macrosDiff->addedMacros as $macro) { if ($macro->getDescription() === '') { $commandMacro = $commandMacros[$macro->getName()] ?? null; $macro->setDescription( $commandMacro ? $commandMacro->getDescription() : '' ); } $macro = $this->updateMacroInVault($macro, 'INSERT'); $this->writeHostMacroRepository->add($macro); } } /** * Find macros of a host template: * - macros linked directly, * - macros linked through template inheritance, * - macros linked through command inheritance. * * @param HostTemplate $hostTemplate * * @throws \Throwable * * @return array{ * array<string,Macro>, * array<string,Macro>, * array<string,CommandMacro> * } */ private function findOriginalMacros(HostTemplate $hostTemplate): array { $templateParents = $this->readHostTemplateRepository->findParents($hostTemplate->getId()); $inheritanceLine = InheritanceManager::findInheritanceLine($hostTemplate->getId(), $templateParents); $existingHostMacros = $this->readHostMacroRepository->findByHostIds(array_merge([$hostTemplate->getId()], $inheritanceLine)); [$directMacros, $inheritedMacros] = Macro::resolveInheritance( $existingHostMacros, $inheritanceLine, $hostTemplate->getId() ); /** @var array<string,CommandMacro> */ $commandMacros = []; if ($hostTemplate->getCheckCommandId() !== null) { $existingCommandMacros = $this->readCommandMacroRepository->findByCommandIdAndType( $hostTemplate->getCheckCommandId(), CommandMacroType::Host ); $commandMacros = MacroManager::resolveInheritanceForCommandMacro($existingCommandMacros); } return [ $this->writeVaultRepository->isVaultConfigured() ? $this->retrieveMacrosVaultValues($directMacros) : $directMacros, $this->writeVaultRepository->isVaultConfigured() ? $this->retrieveMacrosVaultValues($inheritedMacros) : $inheritedMacros, $commandMacros, ]; } private function updateCategories(PartialUpdateHostTemplateRequest $request, HostTemplate $hostTemplate): void { $this->info( 'PartialUpdateHostTemplate: update categories', ['host_template_id' => $hostTemplate->getId(), 'categories' => $request->categories] ); if ($request->categories instanceof NoValue) { $this->info('Categories not provided, nothing to update'); return; } $categoryIds = array_unique($request->categories); $this->validation->assertAreValidCategories($categoryIds); if ($this->user->isAdmin()) { $originalCategories = $this->readHostCategoryRepository->findByHost($hostTemplate->getId()); } else { $originalCategories = $this->readHostCategoryRepository->findByHostAndAccessGroups( $hostTemplate->getId(), $this->accessGroups ); } $originalCategoryIds = array_map( static fn (HostCategory $category): int => $category->getId(), $originalCategories ); $categoryDiff = new BasicDifference($originalCategoryIds, $categoryIds); $addedCategories = $categoryDiff->getAdded(); $removedCategories = $categoryDiff->getRemoved(); $this->writeHostCategoryRepository->linkToHost($hostTemplate->getId(), $addedCategories); $this->writeHostCategoryRepository->unlinkFromHost($hostTemplate->getId(), $removedCategories); } /** * @param PartialUpdateHostTemplateRequest $dto * @param int $hostTemplateId * * @throws HostTemplateException * @throws \Throwable */ private function updateParentTemplates(PartialUpdateHostTemplateRequest $dto, int $hostTemplateId): void { $this->info( 'PartialUpdateHostTemplate: Update parent templates', ['host_template_id' => $hostTemplateId, 'template_ids' => $dto->templates] ); if ($dto->templates instanceof NoValue) { $this->info('Parent templates not provided, nothing to update'); return; } /** @var int[] $parentTemplateIds */ $parentTemplateIds = array_unique($dto->templates); $this->validation->assertAreValidTemplates($parentTemplateIds, $hostTemplateId); $this->info('Remove parent templates from a host template', ['child_id' => $hostTemplateId]); $this->writeHostTemplateRepository->deleteParents($hostTemplateId); foreach ($parentTemplateIds as $order => $templateId) { $this->info('Add a parent template to a host template', [ 'child_id' => $hostTemplateId, 'parent_id' => $templateId, 'order' => $order, ]); $this->writeHostTemplateRepository->addParent($hostTemplateId, $templateId, $order); } } /** * @param HostTemplate $hostTemplate * * @throws \Throwable */ private function retrieveHostUuidFromVault(HostTemplate $hostTemplate): void { $this->uuid = $this->getUuidFromPath($hostTemplate->getSnmpCommunity()); if ($this->uuid === null) { $macros = $this->readHostMacroRepository->findByHostId($hostTemplate->getId()); 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) { $macroPrefixedName = '_HOST' . $macro->getName(); $vaultPaths = $this->writeVaultRepository->upsert( $this->uuid ?? null, $action === 'INSERT' ? [$macroPrefixedName => $macro->getValue()] : [], $action === 'DELETE' ? [$macroPrefixedName => $macro->getValue()] : [], ); $vaultPath = $vaultPaths[$macroPrefixedName]; // No need to update the macro if it is being deleted if ($action === 'DELETE') { return $macro; } $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 = '_HOST' . $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; } /** * Update SNMP community for a host template, handling vault storage and clearing logic. * * @param HostTemplate $hostTemplate * @param NoValue|string $snmpCommunity * * @throws \Throwable */ private function updateSnmpCommunity(HostTemplate $hostTemplate, NoValue|string $snmpCommunity): void { if ($snmpCommunity instanceof NoValue) { return; } // If vault is not configured, just set the value directly if (! $this->writeVaultRepository->isVaultConfigured()) { $hostTemplate->setSnmpCommunity($snmpCommunity); return; } // If the value is already a vault path, do nothing if ($this->isAVaultPath($snmpCommunity)) { return; } // If the current value is a vault path and we want to clear it if ($this->isAVaultPath($hostTemplate->getSnmpCommunity()) && empty($snmpCommunity)) { $this->writeVaultRepository->upsert( uuid: $this->getUuidFromPath($hostTemplate->getSnmpCommunity()), deletes: [VaultConfiguration::HOST_SNMP_COMMUNITY_KEY => $snmpCommunity] ); $hostTemplate->setSnmpCommunity($snmpCommunity); return; } // If the new value is empty, do nothing if (empty($snmpCommunity)) { return; } // Otherwise, store in vault and update host template $vaultPaths = $this->writeVaultRepository->upsert( uuid: $this->uuid ?? null, inserts: [VaultConfiguration::HOST_SNMP_COMMUNITY_KEY => $snmpCommunity], ); $this->uuid ??= $this->getUuidFromPath($vaultPaths[VaultConfiguration::HOST_SNMP_COMMUNITY_KEY]); $hostTemplate->setSnmpCommunity($vaultPaths[VaultConfiguration::HOST_SNMP_COMMUNITY_KEY]); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostTemplate/Application/UseCase/PartialUpdateHostTemplate/PartialUpdateHostTemplateValidation.php
centreon/src/Core/HostTemplate/Application/UseCase/PartialUpdateHostTemplate/PartialUpdateHostTemplateValidation.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostTemplate\Application\UseCase\PartialUpdateHostTemplate; 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\Host\Application\InheritanceManager; use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface; use Core\HostSeverity\Application\Repository\ReadHostSeverityRepositoryInterface; use Core\HostTemplate\Application\Exception\HostTemplateException; use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface; use Core\HostTemplate\Domain\Model\HostTemplate; use Core\Security\AccessGroup\Domain\Model\AccessGroup; use Core\TimePeriod\Application\Repository\ReadTimePeriodRepositoryInterface; use Core\Timezone\Application\Repository\ReadTimezoneRepositoryInterface; use Core\ViewImg\Application\Repository\ReadViewImgRepositoryInterface; class PartialUpdateHostTemplateValidation { use LoggerTrait; /** * @param ReadHostTemplateRepositoryInterface $readHostTemplateRepository * @param ReadViewImgRepositoryInterface $readViewImgRepository * @param ReadTimePeriodRepositoryInterface $readTimePeriodRepository * @param ReadHostSeverityRepositoryInterface $readHostSeverityRepository * @param ReadTimezoneRepositoryInterface $readTimezoneRepository * @param ReadCommandRepositoryInterface $readCommandRepository * @param ReadHostCategoryRepositoryInterface $readHostCategoryRepository * @param InheritanceManager $inheritanceManager * @param ContactInterface $user * @param AccessGroup[] $accessGroups */ public function __construct( private readonly ReadHostTemplateRepositoryInterface $readHostTemplateRepository, private readonly ReadViewImgRepositoryInterface $readViewImgRepository, private readonly ReadTimePeriodRepositoryInterface $readTimePeriodRepository, private readonly ReadHostSeverityRepositoryInterface $readHostSeverityRepository, private readonly ReadTimezoneRepositoryInterface $readTimezoneRepository, private readonly ReadCommandRepositoryInterface $readCommandRepository, private readonly ReadHostCategoryRepositoryInterface $readHostCategoryRepository, private readonly InheritanceManager $inheritanceManager, private readonly ContactInterface $user, public array $accessGroups = [], ) { } /** * Assert name is not already used. * * @param string $name * @param HostTemplate $hostTemplate * * @throws HostTemplateException|\Throwable */ public function assertIsValidName(string $name, HostTemplate $hostTemplate): void { if ($hostTemplate->isNameIdentical($name)) { return; } $formattedName = HostTemplate::formatName($name); if ($this->readHostTemplateRepository->existsByName($formattedName)) { $this->error('Host template name already exists', compact('name', 'formattedName')); throw HostTemplateException::nameAlreadyExists($formattedName, $name); } } /** * Assert icon ID is valid. * * @param ?int $iconId * * @throws HostTemplateException|\Throwable */ public function assertIsValidIcon(?int $iconId): void { if ($iconId !== null && $this->readViewImgRepository->existsOne($iconId) === false) { $this->error('Icon does not exist', ['icon_id' => $iconId]); throw HostTemplateException::idDoesNotExist('iconId', $iconId); } } /** * Assert time period ID is valid. * * @param ?int $timePeriodId * @param ?string $propertyName * * @throws HostTemplateException|\Throwable */ public function assertIsValidTimePeriod(?int $timePeriodId, ?string $propertyName = null): void { if ($timePeriodId !== null && $this->readTimePeriodRepository->exists($timePeriodId) === false) { $this->error('Time period does not exist', ['time_period_id' => $timePeriodId]); throw HostTemplateException::idDoesNotExist($propertyName ?? 'timePeriodId', $timePeriodId); } } /** * Assert host severity ID is valid. * * @param ?int $severityId * * @throws HostTemplateException|\Throwable */ public function assertIsValidSeverity(?int $severityId): void { if ($severityId !== null) { $exists = ($this->accessGroups === []) ? $this->readHostSeverityRepository->exists($severityId) : $this->readHostSeverityRepository->existsByAccessGroups($severityId, $this->accessGroups); if (! $exists) { $this->error('Host severity does not exist', ['severity_id' => $severityId]); throw HostTemplateException::idDoesNotExist('severityId', $severityId); } } } /** * Assert timezone ID is valid. * * @param ?int $timezoneId * * @throws HostTemplateException */ public function assertIsValidTimezone(?int $timezoneId): void { if ($timezoneId !== null && $this->readTimezoneRepository->exists($timezoneId) === false) { $this->error('Timezone does not exist', ['timezone_id' => $timezoneId]); throw HostTemplateException::idDoesNotExist('timezoneId', $timezoneId); } } /** * Assert command ID is valid. * * @param ?int $commandId * @param ?CommandType $commandType * @param ?string $propertyName * * @throws HostTemplateException */ public function assertIsValidCommand( ?int $commandId, ?CommandType $commandType = null, ?string $propertyName = null, ): void { if ($commandId === null) { return; } if ($commandType === null && $this->readCommandRepository->exists($commandId) === false) { $this->error('Command does not exist', ['command_id' => $commandId]); throw HostTemplateException::idDoesNotExist($propertyName ?? 'commandId', $commandId); } if ( $commandType !== null && $this->readCommandRepository->existsByIdAndCommandType($commandId, $commandType) === false ) { $this->error('Command does not exist', ['command_id' => $commandId, 'command_type' => $commandType]); throw HostTemplateException::idDoesNotExist($propertyName ?? 'commandId', $commandId); } } /** * Assert category IDs are valid. * * @param int[] $categoryIds * * @throws HostTemplateException * @throws \Throwable */ public function assertAreValidCategories(array $categoryIds): void { if ($this->user->isAdmin()) { $validCategoryIds = $this->readHostCategoryRepository->exist($categoryIds); } else { $validCategoryIds = $this->readHostCategoryRepository->existByAccessGroups($categoryIds, $this->accessGroups); } if ([] !== ($invalidIds = array_diff($categoryIds, $validCategoryIds))) { throw HostTemplateException::idsDoNotExist('categories', $invalidIds); } } /** * Assert template IDs are valid. * * @param int[] $templateIds * @param int $hostTemplateId * * @throws HostTemplateException * @throws \Throwable */ public function assertAreValidTemplates(array $templateIds, int $hostTemplateId): void { if ($templateIds === []) { return; } $validTemplateIds = $this->readHostTemplateRepository->exist($templateIds); if ([] !== ($invalidIds = array_diff($templateIds, $validTemplateIds))) { throw HostTemplateException::idsDoNotExist('templates', $invalidIds); } if ( in_array($hostTemplateId, $templateIds, true) || $this->inheritanceManager->isValidInheritanceTree($hostTemplateId, $templateIds) === false ) { throw HostTemplateException::circularTemplateInheritance(); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostTemplate/Application/UseCase/PartialUpdateHostTemplate/PartialUpdateHostTemplateRequest.php
centreon/src/Core/HostTemplate/Application/UseCase/PartialUpdateHostTemplate/PartialUpdateHostTemplateRequest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostTemplate\Application\UseCase\PartialUpdateHostTemplate; use Core\Common\Application\Type\NoValue; final class PartialUpdateHostTemplateRequest { /** * @param NoValue|array<array{name:string,value:string|null,is_password:bool,description:null|string}> $macros * @param NoValue|int[] $categories * @param NoValue|int[] $templates * @param NoValue|string $name * @param NoValue|string $alias * @param NoValue|string $snmpVersion * @param NoValue|string $snmpCommunity * @param NoValue|null|int $timezoneId * @param NoValue|null|int $severityId * @param NoValue|null|int $checkCommandId * @param NoValue|string[] $checkCommandArgs * @param NoValue|null|int $checkTimeperiodId * @param NoValue|null|int $maxCheckAttempts * @param NoValue|null|int $normalCheckInterval * @param NoValue|null|int $retryCheckInterval * @param NoValue|int $activeCheckEnabled * @param NoValue|int $passiveCheckEnabled * @param NoValue|int $notificationEnabled * @param NoValue|null|int $notificationOptions * @param NoValue|null|int $notificationInterval * @param NoValue|null|int $notificationTimeperiodId * @param NoValue|bool $addInheritedContactGroup * @param NoValue|bool $addInheritedContact * @param NoValue|null|int $firstNotificationDelay * @param NoValue|null|int $recoveryNotificationDelay * @param NoValue|null|int $acknowledgementTimeout * @param NoValue|int $freshnessChecked * @param NoValue|null|int $freshnessThreshold * @param NoValue|int $flapDetectionEnabled * @param NoValue|null|int $lowFlapThreshold * @param NoValue|null|int $highFlapThreshold * @param NoValue|int $eventHandlerEnabled * @param NoValue|null|int $eventHandlerCommandId * @param NoValue|string[] $eventHandlerCommandArgs * @param NoValue|string $noteUrl * @param NoValue|string $note * @param NoValue|string $actionUrl * @param NoValue|null|int $iconId * @param NoValue|string $iconAlternative * @param NoValue|string $comment */ public function __construct( public NoValue|array $macros = new NoValue(), public NoValue|array $categories = new NoValue(), public NoValue|array $templates = new NoValue(), public NoValue|string $name = new NoValue(), public NoValue|string $alias = new NoValue(), public NoValue|string $snmpVersion = new NoValue(), public NoValue|string $snmpCommunity = new NoValue(), public NoValue|null|int $timezoneId = new NoValue(), public NoValue|null|int $severityId = new NoValue(), public NoValue|null|int $checkCommandId = new NoValue(), public NoValue|array $checkCommandArgs = new NoValue(), public NoValue|null|int $checkTimeperiodId = new NoValue(), public NoValue|null|int $maxCheckAttempts = new NoValue(), public NoValue|null|int $normalCheckInterval = new NoValue(), public NoValue|null|int $retryCheckInterval = new NoValue(), public NoValue|int $activeCheckEnabled = new NoValue(), public NoValue|int $passiveCheckEnabled = new NoValue(), public NoValue|int $notificationEnabled = new NoValue(), public NoValue|null|int $notificationOptions = new NoValue(), public NoValue|null|int $notificationInterval = new NoValue(), public NoValue|null|int $notificationTimeperiodId = new NoValue(), public NoValue|bool $addInheritedContactGroup = new NoValue(), public NoValue|bool $addInheritedContact = new NoValue(), public NoValue|null|int $firstNotificationDelay = new NoValue(), public NoValue|null|int $recoveryNotificationDelay = new NoValue(), public NoValue|null|int $acknowledgementTimeout = new NoValue(), public NoValue|int $freshnessChecked = new NoValue(), public NoValue|null|int $freshnessThreshold = new NoValue(), public NoValue|int $flapDetectionEnabled = new NoValue(), public NoValue|null|int $lowFlapThreshold = new NoValue(), public NoValue|null|int $highFlapThreshold = new NoValue(), public NoValue|int $eventHandlerEnabled = new NoValue(), public NoValue|null|int $eventHandlerCommandId = new NoValue(), public NoValue|array $eventHandlerCommandArgs = new NoValue(), public NoValue|string $noteUrl = new NoValue(), public NoValue|string $note = new NoValue(), public NoValue|string $actionUrl = new NoValue(), public NoValue|null|int $iconId = new NoValue(), public NoValue|string $iconAlternative = new NoValue(), public NoValue|string $comment = 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/HostTemplate/Application/UseCase/PartialUpdateHostTemplate/HostMacroFactory.php
centreon/src/Core/HostTemplate/Application/UseCase/PartialUpdateHostTemplate/HostMacroFactory.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostTemplate\Application\UseCase\PartialUpdateHostTemplate; use Assert\AssertionFailedException; use Core\Macro\Domain\Model\Macro; final class HostMacroFactory { /** * 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 array{id?:int|null,name:string,value:string|null,is_password:bool,description:string|null} $data * @param int $hostTemplateId * @param array<string,Macro> $directMacros * @param array<string,Macro> $inheritedMacros * * @throws \Throwable * @throws AssertionFailedException * * @return Macro */ public static function create( array $data, int $hostTemplateId, array $directMacros, array $inheritedMacros, ): Macro { $macroName = mb_strtoupper($data['name']); $macroValue = $data['value'] ?? ''; $passwordHasNotChanged = ($data['value'] === null) && $data['is_password']; 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( $data['id'] ?? null, $hostTemplateId, $data['name'], $macroValue, ); $macro->setIsPassword($data['is_password']); $macro->setDescription($data['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/HostTemplate/Application/UseCase/AddHostTemplate/NewHostTemplateFactory.php
centreon/src/Core/HostTemplate/Application/UseCase/AddHostTemplate/NewHostTemplateFactory.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostTemplate\Application\UseCase\AddHostTemplate; use Core\Common\Application\Converter\YesNoDefaultConverter; use Core\Host\Application\Converter\HostEventConverter; use Core\Host\Domain\Model\SnmpVersion; use Core\HostTemplate\Domain\Model\NewHostTemplate; final class NewHostTemplateFactory { /** * @param AddHostTemplateRequest $dto * @param int $inheritanceMode * * @throws \Assert\AssertionFailedException * @throws \Throwable * * @return NewHostTemplate */ public static function create(AddHostTemplateRequest $dto, int $inheritanceMode): NewHostTemplate { return new NewHostTemplate( $dto->name, $dto->alias, $dto->snmpVersion === '' ? null : SnmpVersion::from($dto->snmpVersion), $dto->snmpCommunity, $dto->timezoneId, $dto->severityId, $dto->checkCommandId, $dto->checkCommandArgs, $dto->checkTimeperiodId, $dto->maxCheckAttempts, $dto->normalCheckInterval, $dto->retryCheckInterval, YesNoDefaultConverter::fromScalar($dto->activeCheckEnabled), YesNoDefaultConverter::fromScalar($dto->passiveCheckEnabled), YesNoDefaultConverter::fromScalar($dto->notificationEnabled), $dto->notificationOptions === null ? [] : HostEventConverter::fromBitFlag($dto->notificationOptions), $dto->notificationInterval, $dto->notificationTimeperiodId, $inheritanceMode === 1 ? $dto->addInheritedContactGroup : false, $inheritanceMode === 1 ? $dto->addInheritedContact : false, $dto->firstNotificationDelay, $dto->recoveryNotificationDelay, $dto->acknowledgementTimeout, YesNoDefaultConverter::fromScalar($dto->freshnessChecked), $dto->freshnessThreshold, YesNoDefaultConverter::fromScalar($dto->flapDetectionEnabled), $dto->lowFlapThreshold, $dto->highFlapThreshold, $dto->eventHandlerEnabled, $dto->eventHandlerCommandId, $dto->eventHandlerCommandArgs, $dto->noteUrl, $dto->note, $dto->actionUrl, $dto->iconId, $dto->iconAlternative, $dto->comment, ); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostTemplate/Application/UseCase/AddHostTemplate/AddHostTemplatePresenterInterface.php
centreon/src/Core/HostTemplate/Application/UseCase/AddHostTemplate/AddHostTemplatePresenterInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostTemplate\Application\UseCase\AddHostTemplate; use Core\Application\Common\UseCase\ResponseStatusInterface; interface AddHostTemplatePresenterInterface { public function presentResponse(AddHostTemplateResponse|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/HostTemplate/Application/UseCase/AddHostTemplate/AddHostTemplateFactory.php
centreon/src/Core/HostTemplate/Application/UseCase/AddHostTemplate/AddHostTemplateFactory.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostTemplate\Application\UseCase\AddHostTemplate; use Core\Common\Application\Converter\YesNoDefaultConverter; use Core\Host\Application\Converter\HostEventConverter; use Core\HostCategory\Domain\Model\HostCategory; use Core\HostTemplate\Domain\Model\HostTemplate; use Core\Macro\Domain\Model\Macro; final class AddHostTemplateFactory { /** * @param HostTemplate $hostTemplate * @param HostCategory[] $hostCategories * @param array<array{id:int,name:string}> $parentTemplates * @param Macro[] $macros * * @throws \Throwable * * @return AddHostTemplateResponse */ public static function createResponse( HostTemplate $hostTemplate, array $hostCategories, array $parentTemplates, array $macros, ): AddHostTemplateResponse { $dto = new AddHostTemplateResponse(); $dto->id = $hostTemplate->getId(); $dto->name = $hostTemplate->getName(); $dto->alias = $hostTemplate->getAlias(); $dto->snmpVersion = $hostTemplate->getSnmpVersion()?->value; $dto->snmpCommunity = $hostTemplate->getSnmpCommunity(); $dto->timezoneId = $hostTemplate->getTimezoneId(); $dto->severityId = $hostTemplate->getSeverityId(); $dto->checkCommandId = $hostTemplate->getCheckCommandId(); $dto->checkCommandArgs = $hostTemplate->getCheckCommandArgs(); $dto->checkTimeperiodId = $hostTemplate->getCheckTimeperiodId(); $dto->maxCheckAttempts = $hostTemplate->getMaxCheckAttempts(); $dto->normalCheckInterval = $hostTemplate->getNormalCheckInterval(); $dto->retryCheckInterval = $hostTemplate->getRetryCheckInterval(); $dto->activeCheckEnabled = YesNoDefaultConverter::toInt($hostTemplate->getActiveCheckEnabled()); $dto->passiveCheckEnabled = YesNoDefaultConverter::toInt($hostTemplate->getPassiveCheckEnabled()); $dto->notificationEnabled = YesNoDefaultConverter::toInt($hostTemplate->getNotificationEnabled()); $dto->notificationOptions = HostEventConverter::toBitFlag($hostTemplate->getNotificationOptions()); $dto->notificationInterval = $hostTemplate->getNotificationInterval(); $dto->notificationTimeperiodId = $hostTemplate->getNotificationTimeperiodId(); $dto->addInheritedContactGroup = $hostTemplate->addInheritedContactGroup(); $dto->addInheritedContact = $hostTemplate->addInheritedContact(); $dto->firstNotificationDelay = $hostTemplate->getFirstNotificationDelay(); $dto->recoveryNotificationDelay = $hostTemplate->getRecoveryNotificationDelay(); $dto->acknowledgementTimeout = $hostTemplate->getAcknowledgementTimeout(); $dto->freshnessChecked = YesNoDefaultConverter::toInt($hostTemplate->getFreshnessChecked()); $dto->freshnessThreshold = $hostTemplate->getFreshnessThreshold(); $dto->flapDetectionEnabled = YesNoDefaultConverter::toInt($hostTemplate->getFlapDetectionEnabled()); $dto->lowFlapThreshold = $hostTemplate->getLowFlapThreshold(); $dto->highFlapThreshold = $hostTemplate->getHighFlapThreshold(); $dto->eventHandlerEnabled = YesNoDefaultConverter::toInt($hostTemplate->getEventHandlerEnabled()); $dto->eventHandlerCommandId = $hostTemplate->getEventHandlerCommandId(); $dto->eventHandlerCommandArgs = $hostTemplate->getEventHandlerCommandArgs(); $dto->noteUrl = $hostTemplate->getNoteUrl(); $dto->note = $hostTemplate->getNote(); $dto->actionUrl = $hostTemplate->getActionUrl(); $dto->iconId = $hostTemplate->getIconId(); $dto->iconAlternative = $hostTemplate->getIconAlternative(); $dto->comment = $hostTemplate->getComment(); $dto->isLocked = $hostTemplate->isLocked(); $dto->categories = array_map( fn (HostCategory $category) => ['id' => $category->getId(), 'name' => $category->getName()], $hostCategories ); $dto->templates = array_map( fn ($template) => ['id' => $template['id'], 'name' => $template['name']], $parentTemplates ); $dto->macros = array_map( static fn (Macro $macro): array => [ 'id' => $macro->getId(), 'name' => $macro->getName(), 'value' => $macro->getValue(), 'isPassword' => $macro->isPassword(), 'description' => $macro->getDescription(), ], $macros ); 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/HostTemplate/Application/UseCase/AddHostTemplate/AddHostTemplateRequest.php
centreon/src/Core/HostTemplate/Application/UseCase/AddHostTemplate/AddHostTemplateRequest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostTemplate\Application\UseCase\AddHostTemplate; use Core\Common\Domain\YesNoDefault; final class AddHostTemplateRequest { public string $name = ''; public string $alias = ''; public string $snmpVersion = ''; public string $snmpCommunity = ''; public ?int $timezoneId = null; public ?int $severityId = null; public ?int $checkCommandId = null; /** @var string[] */ public array $checkCommandArgs = []; public ?int $checkTimeperiodId = null; public ?int $maxCheckAttempts = null; public ?int $normalCheckInterval = null; public ?int $retryCheckInterval = null; public int $activeCheckEnabled = 2; public int $passiveCheckEnabled = 2; public int $notificationEnabled = 2; public ?int $notificationOptions = null; public ?int $notificationInterval = null; public ?int $notificationTimeperiodId = null; public bool $addInheritedContactGroup = false; public bool $addInheritedContact = false; public ?int $firstNotificationDelay = null; public ?int $recoveryNotificationDelay = null; public ?int $acknowledgementTimeout = null; public int $freshnessChecked = 2; public ?int $freshnessThreshold = null; public int $flapDetectionEnabled = 2; public ?int $lowFlapThreshold = null; public ?int $highFlapThreshold = null; public YesNoDefault $eventHandlerEnabled = YesNoDefault::Default; public ?int $eventHandlerCommandId = null; /** @var string[] */ public array $eventHandlerCommandArgs = []; public string $noteUrl = ''; public string $note = ''; public string $actionUrl = ''; public ?int $iconId = null; public string $iconAlternative = ''; public string $comment = ''; /** @var int[] */ public array $categories = []; /** @var int[] */ public array $templates = []; /** @var array<array{id?:int|null,name:string,value:null|string,is_password:bool,description:null|string}> */ 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/HostTemplate/Application/UseCase/AddHostTemplate/AddHostTemplate.php
centreon/src/Core/HostTemplate/Application/UseCase/AddHostTemplate/AddHostTemplate.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostTemplate\Application\UseCase\AddHostTemplate; 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\Command\Domain\Model\CommandType; 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\Infrastructure\Repository\AbstractVaultRepository; use Core\Host\Application\InheritanceManager; use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface; use Core\HostCategory\Application\Repository\WriteHostCategoryRepositoryInterface; use Core\HostTemplate\Application\Exception\HostTemplateException; use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface; use Core\HostTemplate\Application\Repository\WriteHostTemplateRepositoryInterface; use Core\Macro\Application\Repository\ReadHostMacroRepositoryInterface; use Core\Macro\Application\Repository\WriteHostMacroRepositoryInterface; 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\Vault\Domain\Model\VaultConfiguration; final class AddHostTemplate { use LoggerTrait; use VaultTrait; public function __construct( private readonly WriteHostTemplateRepositoryInterface $writeHostTemplateRepository, private readonly ReadHostTemplateRepositoryInterface $readHostTemplateRepository, private readonly ReadHostCategoryRepositoryInterface $readHostCategoryRepository, private readonly WriteHostCategoryRepositoryInterface $writeHostCategoryRepository, private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository, private readonly ReadHostMacroRepositoryInterface $readHostMacroRepository, private readonly ReadCommandMacroRepositoryInterface $readCommandMacroRepository, private readonly WriteHostMacroRepositoryInterface $writeHostMacroRepository, private readonly DataStorageEngineInterface $dataStorageEngine, private readonly OptionService $optionService, private readonly ContactInterface $user, private readonly AddHostTemplateValidation $validation, private readonly WriteVaultRepositoryInterface $writeVaultRepository, private readonly ReadVaultRepositoryInterface $readVaultRepository, ) { $this->writeVaultRepository->setCustomPath(AbstractVaultRepository::HOST_VAULT_PATH); } /** * @param AddHostTemplateRequest $request * @param AddHostTemplatePresenterInterface $presenter */ public function __invoke(AddHostTemplateRequest $request, AddHostTemplatePresenterInterface $presenter): void { try { if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_HOSTS_TEMPLATES_READ_WRITE)) { $this->error( "User doesn't have sufficient rights to add a host template", ['user_id' => $this->user->getId()] ); $presenter->presentResponse( new ForbiddenResponse(HostTemplateException::addNotAllowed()->getMessage()) ); return; } try { $this->dataStorageEngine->startTransaction(); $hostTemplateId = $this->createHostTemplate($request); $this->linkHostCategories($request, $hostTemplateId); $this->linkParentTemplates($request, $hostTemplateId); $this->addMacros($request, $hostTemplateId); $this->dataStorageEngine->commitTransaction(); } catch (\Throwable $ex) { $this->error("Rollback of 'Add Host Template' transaction."); $this->dataStorageEngine->rollbackTransaction(); throw $ex; } $presenter->presentResponse( $this->createResponse($hostTemplateId, $request->templates) ); } catch (AssertionFailedException|\ValueError $ex) { $presenter->presentResponse(new InvalidArgumentResponse($ex)); $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); } catch (HostTemplateException $ex) { $presenter->presentResponse( match ($ex->getCode()) { HostTemplateException::CODE_CONFLICT => new ConflictResponse($ex), default => new ErrorResponse($ex), } ); $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); } catch (\Throwable $ex) { $presenter->presentResponse( new ErrorResponse(HostTemplateException::addHostTemplate()) ); $this->error((string) $ex); } } /** * @param AddHostTemplateRequest $request * * @throws AssertionFailedException * @throws HostTemplateException * @throws \Throwable * * @return int */ private function createHostTemplate(AddHostTemplateRequest $request): int { $this->validation->assertIsValidName($request->name); $this->validation->assertIsValidSeverity($request->severityId); $this->validation->assertIsValidTimezone($request->timezoneId); $this->validation->assertIsValidTimePeriod($request->checkTimeperiodId, 'checkTimeperiodId'); $this->validation->assertIsValidTimePeriod($request->notificationTimeperiodId, 'notificationTimeperiodId'); $this->validation->assertIsValidCommand($request->checkCommandId, CommandType::Check, 'checkCommandId'); $this->validation->assertIsValidCommand($request->eventHandlerCommandId, null, 'eventHandlerCommandId'); $this->validation->assertIsValidIcon($request->iconId); $inheritanceMode = $this->optionService->findSelectedOptions(['inheritance_mode']); $inheritanceMode = isset($inheritanceMode[0]) ? (int) ($inheritanceMode[0])->getValue() : 0; if ($this->writeVaultRepository->isVaultConfigured() === true && $request->snmpCommunity !== '') { $vaultPaths = $this->writeVaultRepository->upsert( null, [VaultConfiguration::HOST_SNMP_COMMUNITY_KEY => $request->snmpCommunity] ); $vaultPath = $vaultPaths[VaultConfiguration::HOST_SNMP_COMMUNITY_KEY]; $this->uuid ??= $this->getUuidFromPath($vaultPath); $request->snmpCommunity = $vaultPath; } $newHostTemplate = NewHostTemplateFactory::create($request, $inheritanceMode); $hostTemplateId = $this->writeHostTemplateRepository->add($newHostTemplate); $this->info('AddHostTemplate: Adding new host template', ['host_template_id' => $hostTemplateId]); return $hostTemplateId; } /** * @param AddHostTemplateRequest $dto * @param int $hostTemplateId * * @throws HostTemplateException * @throws \Throwable */ private function linkHostCategories(AddHostTemplateRequest $dto, int $hostTemplateId): void { $categoryIds = array_unique($dto->categories); if ($categoryIds === []) { return; } $this->validation->assertAreValidCategories($categoryIds); $this->info( 'AddHostTemplate: Linking host categories', ['host_template_id' => $hostTemplateId, 'category_ids' => $categoryIds] ); $this->writeHostCategoryRepository->linkToHost($hostTemplateId, $categoryIds); } /** * @param AddHostTemplateRequest $dto * @param int $hostTemplateId * * @throws HostTemplateException * @throws \Throwable */ private function linkParentTemplates(AddHostTemplateRequest $dto, int $hostTemplateId): void { $parentTemplateIds = array_unique($dto->templates); if ($parentTemplateIds === []) { return; } $this->validation->assertAreValidTemplates($parentTemplateIds, $hostTemplateId); $this->info( 'AddHostTemplate: Linking parent templates', ['host_template_id' => $hostTemplateId, 'template_ids' => $parentTemplateIds] ); foreach ($parentTemplateIds as $order => $templateId) { $this->writeHostTemplateRepository->addParent($hostTemplateId, $templateId, $order); } } /** * @param int[] $templateIds * * @throws HostTemplateException * @throws \Throwable * * @return array<array{id:int,name:string}> */ private function findParentTemplates(array $templateIds): array { $templateNames = $this->readHostTemplateRepository->findNamesByIds($templateIds); $parentTemplates = []; foreach ($templateIds as $templateId) { $parentTemplates[] = [ 'id' => $templateId, 'name' => $templateNames[$templateId], ]; } return $parentTemplates; } /** * @param AddHostTemplateRequest $dto * @param int $hostTemplateId * * @throws \Throwable */ private function addMacros(AddHostTemplateRequest $dto, int $hostTemplateId): void { $this->info( 'AddHostTemplate: Add macros', ['host_template_id' => $hostTemplateId, 'macros' => $dto->macros] ); /** * @var array<string,Macro> $inheritedMacros * @var array<string,CommandMacro> $commandMacros */ [$inheritedMacros, $commandMacros] = $this->findAllInheritedMacros($hostTemplateId, $dto->checkCommandId); $macros = []; foreach ($dto->macros as $data) { $macro = HostMacroFactory::create($data, $hostTemplateId, $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() : '' ); } if ($this->writeVaultRepository->isVaultConfigured() === true && $macro->isPassword() === true) { $vaultPaths = $this->writeVaultRepository->upsert( $this->uuid ?? null, ['_HOST' . $macro->getName() => $macro->getValue()], ); $vaultPath = $vaultPaths['_HOST' . $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->writeHostMacroRepository->add($macro); } } /** * Find macros of a host template: * macros linked through template inheritance, macros linked through command inheritance. * * @param int $hostTemplateId * @param ?int $checkCommandId * * @throws \Throwable * * @return array{ * array<string,Macro>, * array<string,CommandMacro> * } */ private function findAllInheritedMacros(int $hostTemplateId, ?int $checkCommandId): array { $templateParents = $this->readHostTemplateRepository->findParents($hostTemplateId); $inheritanceLine = InheritanceManager::findInheritanceLine($hostTemplateId, $templateParents); $existingHostMacros = $this->readHostMacroRepository->findByHostIds($inheritanceLine); [, $inheritedMacros] = Macro::resolveInheritance( $existingHostMacros, $inheritanceLine, $hostTemplateId ); /** @var array<string,CommandMacro> $commandMacros */ $commandMacros = []; if ($checkCommandId !== null) { $existingCommandMacros = $this->readCommandMacroRepository->findByCommandIdAndType( $checkCommandId, CommandMacroType::Host ); $commandMacros = MacroManager::resolveInheritanceForCommandMacro($existingCommandMacros); } return [ $this->writeVaultRepository->isVaultConfigured() ? $this->retrieveMacrosVaultValues($inheritedMacros) : $inheritedMacros, $commandMacros, ]; } /** * @param int $hostTemplateId * @param int[] $parentTemplateIds * * @throws AssertionFailedException * @throws HostTemplateException * @throws \Throwable * * @return AddHostTemplateResponse */ private function createResponse(int $hostTemplateId, array $parentTemplateIds): AddHostTemplateResponse { $hostTemplate = $this->readHostTemplateRepository->findById($hostTemplateId); if (! $hostTemplate) { throw HostTemplateException::errorWhileRetrievingObject(); } if ($this->user->isAdmin()) { $hostCategories = $this->readHostCategoryRepository->findByHost($hostTemplateId); } else { $accessGroups = $this->readAccessGroupRepository->findByContact($this->user); $hostCategories = $this->readHostCategoryRepository->findByHostAndAccessGroups( $hostTemplateId, $accessGroups ); } $parentTemplates = $this->findParentTemplates($parentTemplateIds); $macros = $this->readHostMacroRepository->findByHostId($hostTemplateId); return AddHostTemplateFactory::createResponse($hostTemplate, $hostCategories, $parentTemplates, $macros); } /** * @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 = '_HOST' . $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/HostTemplate/Application/UseCase/AddHostTemplate/AddHostTemplateValidation.php
centreon/src/Core/HostTemplate/Application/UseCase/AddHostTemplate/AddHostTemplateValidation.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostTemplate\Application\UseCase\AddHostTemplate; 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\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface; use Core\HostSeverity\Application\Repository\ReadHostSeverityRepositoryInterface; use Core\HostTemplate\Application\Exception\HostTemplateException; use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface; use Core\HostTemplate\Domain\Model\HostTemplate; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\TimePeriod\Application\Repository\ReadTimePeriodRepositoryInterface; use Core\Timezone\Application\Repository\ReadTimezoneRepositoryInterface; use Core\ViewImg\Application\Repository\ReadViewImgRepositoryInterface; class AddHostTemplateValidation { use LoggerTrait; public function __construct( private readonly ReadHostTemplateRepositoryInterface $readHostTemplateRepository, private readonly ReadViewImgRepositoryInterface $readViewImgRepository, private readonly ReadTimePeriodRepositoryInterface $readTimePeriodRepository, private readonly ReadHostSeverityRepositoryInterface $readHostSeverityRepository, private readonly ReadTimezoneRepositoryInterface $readTimezoneRepository, private readonly ReadCommandRepositoryInterface $readCommandRepository, private readonly ReadHostCategoryRepositoryInterface $readHostCategoryRepository, private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository, private readonly ContactInterface $user, ) { } /** * Assert name is not already used. * * @param string $name * * @throws HostTemplateException|\Throwable */ public function assertIsValidName(string $name): void { $formattedName = HostTemplate::formatName($name); if ($this->readHostTemplateRepository->existsByName($formattedName)) { $this->error('Host template name already exists', compact('name', 'formattedName')); throw HostTemplateException::nameAlreadyExists($formattedName, $name); } } /** * Assert icon ID is valid. * * @param ?int $iconId * * @throws HostTemplateException|\Throwable */ public function assertIsValidIcon(?int $iconId): void { if ($iconId !== null && $this->readViewImgRepository->existsOne($iconId) === false) { $this->error('Icon does not exist', ['icon_id' => $iconId]); throw HostTemplateException::idDoesNotExist('iconId', $iconId); } } /** * Assert time period ID is valid. * * @param ?int $timePeriodId * @param ?string $propertyName * * @throws HostTemplateException|\Throwable */ public function assertIsValidTimePeriod(?int $timePeriodId, ?string $propertyName = null): void { if ($timePeriodId !== null && $this->readTimePeriodRepository->exists($timePeriodId) === false) { $this->error('Time period does not exist', ['time_period_id' => $timePeriodId]); throw HostTemplateException::idDoesNotExist($propertyName ?? 'timePeriodId', $timePeriodId); } } /** * Assert host severity ID is valid. * * @param ?int $severityId * * @throws HostTemplateException|\Throwable */ public function assertIsValidSeverity(?int $severityId): void { $accessGroups = $this->readAccessGroupRepository->findByContact($this->user); if ($severityId !== null) { $exists = ($accessGroups === []) ? $this->readHostSeverityRepository->exists($severityId) : $this->readHostSeverityRepository->existsByAccessGroups($severityId, $accessGroups); if (! $exists) { $this->error('Host severity does not exist', ['severity_id' => $severityId]); throw HostTemplateException::idDoesNotExist('severityId', $severityId); } } } /** * Assert timezone ID is valid. * * @param ?int $timezoneId * * @throws HostTemplateException */ public function assertIsValidTimezone(?int $timezoneId): void { if ($timezoneId !== null && $this->readTimezoneRepository->exists($timezoneId) === false) { $this->error('Timezone does not exist', ['timezone_id' => $timezoneId]); throw HostTemplateException::idDoesNotExist('timezoneId', $timezoneId); } } /** * Assert command ID is valid. * * @param ?int $commandId * @param ?CommandType $commandType * @param ?string $propertyName * * @throws HostTemplateException */ public function assertIsValidCommand( ?int $commandId, ?CommandType $commandType = null, ?string $propertyName = null, ): void { if ($commandId === null) { return; } if ($commandType === null && $this->readCommandRepository->exists($commandId) === false) { $this->error('Command does not exist', ['command_id' => $commandId]); throw HostTemplateException::idDoesNotExist($propertyName ?? 'commandId', $commandId); } if ( $commandType !== null && $this->readCommandRepository->existsByIdAndCommandType($commandId, $commandType) === false ) { $this->error('Command does not exist', ['command_id' => $commandId, 'command_type' => $commandType]); throw HostTemplateException::idDoesNotExist($propertyName ?? 'commandId', $commandId); } } /** * Assert category IDs are valid. * * @param int[] $categoryIds * * @throws HostTemplateException * @throws \Throwable */ public function assertAreValidCategories(array $categoryIds): void { if ($this->user->isAdmin()) { $validCategoryIds = $this->readHostCategoryRepository->exist($categoryIds); } else { $accessGroups = $this->readAccessGroupRepository->findByContact($this->user); $validCategoryIds = $this->readHostCategoryRepository->existByAccessGroups($categoryIds, $accessGroups); } if ([] !== ($invalidIds = array_diff($categoryIds, $validCategoryIds))) { throw HostTemplateException::idsDoNotExist('categories', $invalidIds); } } /** * Assert template IDs are valid. * * @param int[] $templateIds * @param int $hostTemplateId * * @throws HostTemplateException * @throws \Throwable */ public function assertAreValidTemplates(array $templateIds, int $hostTemplateId): void { if (in_array($hostTemplateId, $templateIds, true)) { throw HostTemplateException::circularTemplateInheritance(); } $validTemplateIds = $this->readHostTemplateRepository->exist($templateIds); if ([] !== ($invalidIds = array_diff($templateIds, $validTemplateIds))) { throw HostTemplateException::idsDoNotExist('templates', $invalidIds); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostTemplate/Application/UseCase/AddHostTemplate/AddHostTemplateResponse.php
centreon/src/Core/HostTemplate/Application/UseCase/AddHostTemplate/AddHostTemplateResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostTemplate\Application\UseCase\AddHostTemplate; final class AddHostTemplateResponse { public int $id = 0; public string $name = ''; public string $alias = ''; public ?string $snmpVersion = null; public string $snmpCommunity = ''; public ?int $timezoneId = null; public ?int $severityId = null; public ?int $checkCommandId = null; /** @var string[] */ public array $checkCommandArgs = []; public ?int $checkTimeperiodId = null; public ?int $maxCheckAttempts = null; public ?int $normalCheckInterval = null; public ?int $retryCheckInterval = null; public int $activeCheckEnabled = 2; public int $passiveCheckEnabled = 2; public int $notificationEnabled = 2; public ?int $notificationOptions = null; public ?int $notificationInterval = null; public ?int $notificationTimeperiodId = null; public bool $addInheritedContactGroup = false; public bool $addInheritedContact = false; public ?int $firstNotificationDelay = null; public ?int $recoveryNotificationDelay = null; public ?int $acknowledgementTimeout = null; public int $freshnessChecked = 2; public ?int $freshnessThreshold = null; public int $flapDetectionEnabled = 2; public ?int $lowFlapThreshold = null; public ?int $highFlapThreshold = null; public int $eventHandlerEnabled = 2; public ?int $eventHandlerCommandId = null; /** @var string[] */ public array $eventHandlerCommandArgs = []; public string $noteUrl = ''; public string $note = ''; public string $actionUrl = ''; public ?int $iconId = null; public string $iconAlternative = ''; public string $comment = ''; public bool $isLocked = false; /** @var array<array{id:int,name:string}> */ public array $categories = []; /** @var array<array{id:int,name:string}> */ public array $templates = []; /** @var array<array{id:int|null,name:string,value:null|string,isPassword:bool,description:string}> */ 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/HostTemplate/Application/UseCase/AddHostTemplate/HostMacroFactory.php
centreon/src/Core/HostTemplate/Application/UseCase/AddHostTemplate/HostMacroFactory.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostTemplate\Application\UseCase\AddHostTemplate; use Assert\AssertionFailedException; use Core\Macro\Domain\Model\Macro; final class HostMacroFactory { /** * 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 array{id?:int|null,name:string,value:string|null,is_password:bool,description:string|null} $data * @param int $hostTemplateId * @param array<string,Macro> $inheritedMacros * * @throws \Throwable * @throws AssertionFailedException * * @return Macro */ public static function create( array $data, int $hostTemplateId, array $inheritedMacros, ): Macro { $macroName = mb_strtoupper($data['name']); $macroValue = $data['value'] ?? ''; $passwordHasNotChanged = ($data['value'] === null) && $data['is_password']; if ($passwordHasNotChanged) { $macroValue = match (true) { // retrieve actual password value isset($inheritedMacros[$macroName]) => $inheritedMacros[$macroName]->getValue(), default => $macroValue, }; } $macro = new Macro( $data['id'] ?? null, $hostTemplateId, $data['name'], $macroValue, ); $macro->setIsPassword($data['is_password']); $macro->setDescription($data['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/HostTemplate/Application/UseCase/DeleteHostTemplate/DeleteHostTemplate.php
centreon/src/Core/HostTemplate/Application/UseCase/DeleteHostTemplate/DeleteHostTemplate.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostTemplate\Application\UseCase\DeleteHostTemplate; 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\InvalidArgumentResponse; 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\HostTemplate\Application\Exception\HostTemplateException; use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface; use Core\HostTemplate\Application\Repository\WriteHostTemplateRepositoryInterface; use Core\HostTemplate\Domain\Model\HostTemplate; use Core\Macro\Application\Repository\ReadHostMacroRepositoryInterface; final class DeleteHostTemplate { use LoggerTrait; use VaultTrait; public function __construct( private readonly WriteHostTemplateRepositoryInterface $writeHostTemplateRepository, private readonly ReadHostTemplateRepositoryInterface $readHostTemplateRepository, private readonly ContactInterface $user, private readonly WriteVaultRepositoryInterface $writeVaultRepository, private readonly ReadHostMacroRepositoryInterface $readHostMacroRepository, ) { $this->writeVaultRepository->setCustomPath(AbstractVaultRepository::HOST_VAULT_PATH); } /** * @param int $hostTemplateId * @param PresenterInterface $presenter */ public function __invoke(int $hostTemplateId, PresenterInterface $presenter): void { try { if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_HOSTS_TEMPLATES_READ_WRITE)) { $this->error( "User doesn't have sufficient rights to delete host templates", ['user_id' => $this->user->getId()] ); $presenter->setResponseStatus( new ForbiddenResponse(HostTemplateException::deleteNotAllowed()) ); return; } if (! ($hostTemplate = $this->readHostTemplateRepository->findById($hostTemplateId))) { $this->error( 'Host template not found', ['host_template_id' => $hostTemplateId] ); $presenter->setResponseStatus(new NotFoundResponse('Host template')); return; } if ($this->readHostTemplateRepository->isLocked($hostTemplateId)) { $this->error( 'Host template is locked, deletion refused.', ['host_template_id' => $hostTemplateId] ); $presenter->setResponseStatus( new InvalidArgumentResponse(HostTemplateException::hostIsLocked($hostTemplateId)) ); return; } if ($this->writeVaultRepository->isVaultConfigured()) { $this->retrieveHostTemplateUuidFromVault($hostTemplate); if ($this->uuid !== null) { $this->writeVaultRepository->delete($this->uuid); } } $this->writeHostTemplateRepository->delete($hostTemplateId); $presenter->setResponseStatus(new NoContentResponse()); } catch (\Throwable $ex) { $presenter->setResponseStatus( new ErrorResponse(HostTemplateException::deleteHostTemplate()) ); $this->error((string) $ex); } } /** * @param HostTemplate $hostTemplate * * @throws \Throwable */ private function retrieveHostTemplateUuidFromVault(HostTemplate $hostTemplate): void { $this->uuid = $this->getUuidFromPath($hostTemplate->getSnmpCommunity()); if ($this->uuid === null) { $macros = $this->readHostMacroRepository->findByHostId($hostTemplate->getId()); 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/HostTemplate/Application/UseCase/FindHostTemplates/FindHostTemplates.php
centreon/src/Core/HostTemplate/Application/UseCase/FindHostTemplates/FindHostTemplates.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostTemplate\Application\UseCase\FindHostTemplates; 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\Common\Application\Converter\YesNoDefaultConverter; use Core\Host\Application\Converter\HostEventConverter; use Core\HostTemplate\Application\Exception\HostTemplateException; use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface; use Core\HostTemplate\Domain\Model\HostTemplate; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; final class FindHostTemplates { use LoggerTrait; public function __construct( private readonly ReadHostTemplateRepositoryInterface $readHostTemplateRepository, private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository, private readonly RequestParametersInterface $requestParameters, private readonly ContactInterface $user, ) { } /** * @param FindHostTemplatesPresenterInterface $presenter */ public function __invoke(FindHostTemplatesPresenterInterface $presenter): void { try { if ( ! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_HOSTS_TEMPLATES_READ) && ! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_HOSTS_TEMPLATES_READ_WRITE) ) { $this->error( "User doesn't have sufficient rights to see host templates", ['user_id' => $this->user->getId()] ); $presenter->presentResponse( new ForbiddenResponse(HostTemplateException::accessNotAllowed()) ); return; } if ($this->user->isAdmin()) { $hostTemplates = $this->readHostTemplateRepository->findByRequestParameter($this->requestParameters); } else { $accessGroups = $this->readAccessGroupRepository->findByContact($this->user); $hostTemplates = $this->readHostTemplateRepository->findByRequestParametersAndAccessGroups( $this->requestParameters, $accessGroups ); } $presenter->presentResponse($this->createResponse($hostTemplates)); } catch (\Throwable $ex) { $presenter->presentResponse(new ErrorResponse(HostTemplateException::findHostTemplates())); $this->error($ex->getMessage()); } } /** * @param HostTemplate[] $hostTemplates * * @return FindHostTemplatesResponse */ private function createResponse(array $hostTemplates): FindHostTemplatesResponse { $response = new FindHostTemplatesResponse(); foreach ($hostTemplates as $hostTemplate) { $response->hostTemplates[] = [ 'id' => $hostTemplate->getId(), 'name' => $hostTemplate->getName(), 'alias' => $hostTemplate->getAlias(), 'snmpVersion' => $hostTemplate->getSnmpVersion() ? $hostTemplate->getSnmpVersion()->value : null, 'snmpCommunity' => $hostTemplate->getSnmpCommunity(), 'timezoneId' => $hostTemplate->getTimezoneId(), 'severityId' => $hostTemplate->getSeverityId(), 'checkCommandId' => $hostTemplate->getCheckCommandId(), 'checkCommandArgs' => $hostTemplate->getCheckCommandArgs(), 'checkTimeperiodId' => $hostTemplate->getCheckTimeperiodId(), 'maxCheckAttempts' => $hostTemplate->getMaxCheckAttempts(), 'normalCheckInterval' => $hostTemplate->getNormalCheckInterval(), 'retryCheckInterval' => $hostTemplate->getRetryCheckInterval(), 'activeCheckEnabled' => YesNoDefaultConverter::toInt($hostTemplate->getActiveCheckEnabled()), 'passiveCheckEnabled' => YesNoDefaultConverter::toInt($hostTemplate->getPassiveCheckEnabled()), 'notificationEnabled' => YesNoDefaultConverter::toInt($hostTemplate->getNotificationEnabled()), 'notificationOptions' => HostEventConverter::toBitFlag($hostTemplate->getNotificationOptions()), 'notificationInterval' => $hostTemplate->getNotificationInterval(), 'notificationTimeperiodId' => $hostTemplate->getNotificationTimeperiodId(), 'addInheritedContactGroup' => $hostTemplate->addInheritedContactGroup(), 'addInheritedContact' => $hostTemplate->addInheritedContact(), 'firstNotificationDelay' => $hostTemplate->getFirstNotificationDelay(), 'recoveryNotificationDelay' => $hostTemplate->getRecoveryNotificationDelay(), 'acknowledgementTimeout' => $hostTemplate->getAcknowledgementTimeout(), 'freshnessChecked' => YesNoDefaultConverter::toInt($hostTemplate->getFreshnessChecked()), 'freshnessThreshold' => $hostTemplate->getfreshnessThreshold(), 'flapDetectionEnabled' => YesNoDefaultConverter::toInt($hostTemplate->getFlapDetectionEnabled()), 'lowFlapThreshold' => $hostTemplate->getLowFlapThreshold(), 'highFlapThreshold' => $hostTemplate->getHighFlapThreshold(), 'eventHandlerEnabled' => YesNoDefaultConverter::toInt($hostTemplate->getEventHandlerEnabled()), 'eventHandlerCommandId' => $hostTemplate->getEventHandlerCommandId(), 'eventHandlerCommandArgs' => $hostTemplate->getEventHandlerCommandArgs(), 'noteUrl' => $hostTemplate->getNoteUrl(), 'note' => $hostTemplate->getNote(), 'actionUrl' => $hostTemplate->getActionUrl(), 'iconId' => $hostTemplate->getIconId(), 'iconAlternative' => $hostTemplate->getIconAlternative(), 'comment' => $hostTemplate->getComment(), 'isLocked' => $hostTemplate->isLocked(), ]; } 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/HostTemplate/Application/UseCase/FindHostTemplates/FindHostTemplatesPresenterInterface.php
centreon/src/Core/HostTemplate/Application/UseCase/FindHostTemplates/FindHostTemplatesPresenterInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostTemplate\Application\UseCase\FindHostTemplates; use Core\Application\Common\UseCase\ResponseStatusInterface; interface FindHostTemplatesPresenterInterface { public function presentResponse(FindHostTemplatesResponse|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/HostTemplate/Application/UseCase/FindHostTemplates/FindHostTemplatesResponse.php
centreon/src/Core/HostTemplate/Application/UseCase/FindHostTemplates/FindHostTemplatesResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostTemplate\Application\UseCase\FindHostTemplates; final class FindHostTemplatesResponse { /** @var array< * array{ * id: int, * name: string, * alias: string, * snmpVersion: string|null, * snmpCommunity: string, * timezoneId: int|null, * severityId: int|null, * checkCommandId: int|null, * checkCommandArgs: string[], * checkTimeperiodId: int|null, * maxCheckAttempts: int|null, * normalCheckInterval: int|null, * retryCheckInterval: int|null, * activeCheckEnabled: int, * passiveCheckEnabled: int, * notificationEnabled: int, * notificationOptions: ?int, * notificationInterval: int|null, * notificationTimeperiodId: int|null, * addInheritedContactGroup: bool, * addInheritedContact: bool, * firstNotificationDelay: int|null, * recoveryNotificationDelay: int|null, * acknowledgementTimeout: int|null, * freshnessChecked: int, * freshnessThreshold: int|null, * flapDetectionEnabled: int, * lowFlapThreshold: int|null, * highFlapThreshold: int|null, * eventHandlerEnabled: int, * eventHandlerCommandId: int|null, * eventHandlerCommandArgs: string[], * noteUrl: string, * note: string, * actionUrl: string, * iconId: int|null, * iconAlternative: string, * comment: string, * isLocked: bool * } * > */ public array $hostTemplates = []; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostTemplate/Application/Exception/HostTemplateException.php
centreon/src/Core/HostTemplate/Application/Exception/HostTemplateException.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostTemplate\Application\Exception; class HostTemplateException extends \Exception { public const CODE_CONFLICT = 1; /** * @return self */ public static function findHostTemplates(): self { return new self(_('Error while searching for host templates')); } /** * @return self */ public static function deleteHostTemplate(): self { return new self(_('Error while deleting a host template')); } /** * @return self */ public static function addHostTemplate(): self { return new self(_('Error while adding a host template')); } /** * @param \Throwable $ex * * @return self */ public static function linkHostCategories(\Throwable $ex): self { return new self(_('Error while linking host categories to a host template'), 0, $ex); } /** * @return self */ public static function partialUpdateHostTemplate(): self { return new self(_('Error while partially updating a host template')); } /** * @return self */ public static function accessNotAllowed(): self { return new self(_('You are not allowed to access host templates')); } /** * @return self */ public static function deleteNotAllowed(): self { return new self(_('You are not allowed to delete host templates')); } /** * @return self */ public static function addNotAllowed(): self { return new self(_('You are not allowed to add host templates')); } /** * @return self */ public static function writeActionsNotAllowed(): self { return new self(_('You are not allowed to perform write actions on host templates')); } /** * @param int $hostTemplateId * * @return self */ public static function notFound(int $hostTemplateId): self { return new self(sprintf(_('Host template #%d not found'), $hostTemplateId)); } /** * @param string $propertieName * @param int $propertieValue * * @return self */ public static function idDoesNotExist(string $propertieName, int $propertieValue): self { return new self(sprintf(_("The %s with value '%d' does not exist"), $propertieName, $propertieValue), self::CODE_CONFLICT); } /** * @param string $propertieName * @param int[] $propertieValues * * @return self */ public static function idsDoNotExist(string $propertieName, array $propertieValues): self { return new self( sprintf( _("The %s does not exist with ID(s) '%s'"), $propertieName, implode(',', $propertieValues) ), self::CODE_CONFLICT ); } /** * @param string $formatedName * @param string $originalName * * @return self */ public static function nameAlreadyExists(string $formatedName, string $originalName = 'undefined'): self { return new self( sprintf(_('The name %s (original name: %s) already exists'), $formatedName, $originalName), self::CODE_CONFLICT ); } /** * @return self */ public static function errorWhileRetrievingObject(): self { return new self(_('Error while retrieving a host template')); } /** * @param int $hostTemplateId * * @return self */ public static function hostIsLocked(int $hostTemplateId): self { return new self(sprintf(_('Host template #%d is locked (edition and deletion not allowed)'), $hostTemplateId)); } /** * @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/HostTemplate/Application/Repository/ReadHostTemplateRepositoryInterface.php
centreon/src/Core/HostTemplate/Application/Repository/ReadHostTemplateRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostTemplate\Application\Repository; use Centreon\Domain\Repository\RepositoryException; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Core\HostTemplate\Domain\Model\HostTemplate; use Core\Security\AccessGroup\Domain\Model\AccessGroup; interface ReadHostTemplateRepositoryInterface { /** * Find all host templates. * * @param RequestParametersInterface $requestParameters * * @throws \Throwable * * @return HostTemplate[] */ public function findByRequestParameter(RequestParametersInterface $requestParameters): array; /** * Find all host templates by access groups. * * @param RequestParametersInterface $requestParameters * @param AccessGroup[] $accessGroups * * @throws \Throwable * * @return HostTemplate[] */ public function findByRequestParametersAndAccessGroups(RequestParametersInterface $requestParameters, array $accessGroups): array; /** * Find a host template by its id. * * @param int $hostTemplateId * * @throws \Throwable * * @return ?HostTemplate */ public function findById(int $hostTemplateId): ?HostTemplate; /** * Find a host template by id and access groups. * * @param int $hostTemplateId * @param AccessGroup[] $accessGroups * * @throws \Throwable * * @return HostTemplate|null */ public function findByIdAndAccessGroups(int $hostTemplateId, array $accessGroups): ?HostTemplate; /** * Find a host template by its id. * * @param int ...$hostTemplateIds * * @throws \Throwable * * @return list<HostTemplate> */ public function findByIds(int ...$hostTemplateIds): array; /** * Retrieve all parent template ids of a host template. * * @param int $hostTemplateId * * @throws \Throwable * * @return array<array{parent_id:int,child_id:int,order:int}> */ public function findParents(int $hostTemplateId): array; /** * Find all existing host templates ids. * * @param list<int> $hostTemplateIds * * @return list<int> */ public function findAllExistingIds(array $hostTemplateIds): array; /** * Determine if a host template exists by its ID. * * @param int $hostTemplateId * * @throws \Throwable * * @return bool */ public function exists(int $hostTemplateId): bool; /** * Check existence of a list of host templates. * Return the ids of the existing templates. * * @param int[] $hostTemplateIds * * @throws \Throwable * * @return int[] */ public function exist(array $hostTemplateIds): array; /** * Determine if a host template exists by its name. * (include both host templates and hosts names). * * @param string $hostTemplateName * * @throws \Throwable * * @return bool */ public function existsByName(string $hostTemplateName): bool; /** * Determine if a host template is_locked properties is set at true. * It means edition and suppression is not allowed for the host template. * * @param int $hostTemplateId * * @throws \Throwable * * @return bool */ public function isLocked(int $hostTemplateId): bool; /** * Retrieve the name of a list of template ids. * Return an array with ids as keys. * * @param int[] $templateIds * * @throws \Throwable * * @return array<int,string> */ public function findNamesByIds(array $templateIds): array; /** * Find all host templates. * * @throws \Throwable * * @return HostTemplate[] */ public function findAll(): array; /** * Find direct parent templates of a host id. * * @param int $hostId * * @throws RepositoryException * * @return array<int, int> */ 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/HostTemplate/Application/Repository/WriteHostTemplateRepositoryInterface.php
centreon/src/Core/HostTemplate/Application/Repository/WriteHostTemplateRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostTemplate\Application\Repository; use Core\HostTemplate\Domain\Model\HostTemplate; use Core\HostTemplate\Domain\Model\NewHostTemplate; interface WriteHostTemplateRepositoryInterface { /** * Delete host template by id. * * @param int $hostTemplateId * * @throws \Throwable */ public function delete(int $hostTemplateId): void; /** * Add host template. * * @param NewHostTemplate $hostTemplate * * @throws \Throwable * * @return int */ public function add(NewHostTemplate $hostTemplate): int; /** * Update host template. * * @param HostTemplate $hostTemplate * * @throws \Throwable */ public function update(HostTemplate $hostTemplate): void; /** * Link a parent template to a child host(or another hostTemplate). * * @param int $childId host or host template to be linked as a child * @param int $parentId host template to be linked as a parent * @param int $order order of inheritance of the parent * * @throws \Throwable */ public function addParent(int $childId, int $parentId, int $order): void; /** * Unlink parent templates from a child host(or another host template). * * @param int $childId host or host template to be unlinked as a child * * @throws \Throwable */ public function deleteParents(int $childId): 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/HostTemplate/Domain/Model/NewHostTemplate.php
centreon/src/Core/HostTemplate/Domain/Model/NewHostTemplate.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostTemplate\Domain\Model; use Assert\AssertionFailedException; use Centreon\Domain\Common\Assertion\Assertion; use Core\Common\Domain\YesNoDefault; use Core\Host\Domain\Model\HostEvent; use Core\Host\Domain\Model\SnmpVersion; class NewHostTemplate { public const MAX_NAME_LENGTH = 200; public const MAX_ALIAS_LENGTH = 200; public const MAX_SNMP_COMMUNITY_LENGTH = 255; public const MAX_NOTE_URL_LENGTH = 65535; public const MAX_NOTE_LENGTH = 65535; public const MAX_ACTION_URL_LENGTH = 65535; public const MAX_ICON_ALT_LENGTH = 200; public const MAX_COMMENT_LENGTH = 65535; /** * @param string $name * @param string $alias * @param null|SnmpVersion $snmpVersion * @param string $snmpCommunity * @param null|int $timezoneId * @param null|int $severityId * @param null|int $checkCommandId * @param string[] $checkCommandArgs * @param null|int $checkTimeperiodId * @param null|int $maxCheckAttempts * @param null|int $normalCheckInterval * @param null|int $retryCheckInterval * @param YesNoDefault $activeCheckEnabled * @param YesNoDefault $passiveCheckEnabled * @param YesNoDefault $notificationEnabled * @param HostEvent[] $notificationOptions * @param null|int $notificationInterval * @param null|int $notificationTimeperiodId * @param bool $addInheritedContactGroup * @param bool $addInheritedContact * @param null|int $firstNotificationDelay * @param null|int $recoveryNotificationDelay * @param null|int $acknowledgementTimeout * @param YesNoDefault $freshnessChecked * @param null|int $freshnessThreshold * @param YesNoDefault $flapDetectionEnabled * @param null|int $lowFlapThreshold * @param null|int $highFlapThreshold * @param YesNoDefault $eventHandlerEnabled * @param null|int $eventHandlerCommandId * @param string[] $eventHandlerCommandArgs * @param string $noteUrl * @param string $note * @param string $actionUrl * @param null|int $iconId * @param string $iconAlternative * @param string $comment * @param bool $isLocked * * @throws AssertionFailedException */ public function __construct( protected string $name, protected string $alias, protected ?SnmpVersion $snmpVersion = null, protected string $snmpCommunity = '', protected ?int $timezoneId = null, protected ?int $severityId = null, protected ?int $checkCommandId = null, protected array $checkCommandArgs = [], protected ?int $checkTimeperiodId = null, protected ?int $maxCheckAttempts = null, protected ?int $normalCheckInterval = null, protected ?int $retryCheckInterval = null, protected YesNoDefault $activeCheckEnabled = YesNoDefault::Default, protected YesNoDefault $passiveCheckEnabled = YesNoDefault::Default, protected YesNoDefault $notificationEnabled = YesNoDefault::Default, protected array $notificationOptions = [], protected ?int $notificationInterval = null, protected ?int $notificationTimeperiodId = null, protected bool $addInheritedContactGroup = false, protected bool $addInheritedContact = false, protected ?int $firstNotificationDelay = null, protected ?int $recoveryNotificationDelay = null, protected ?int $acknowledgementTimeout = null, protected YesNoDefault $freshnessChecked = YesNoDefault::Default, protected ?int $freshnessThreshold = null, protected YesNoDefault $flapDetectionEnabled = YesNoDefault::Default, protected ?int $lowFlapThreshold = null, protected ?int $highFlapThreshold = null, protected YesNoDefault $eventHandlerEnabled = YesNoDefault::Default, protected ?int $eventHandlerCommandId = null, protected array $eventHandlerCommandArgs = [], protected string $noteUrl = '', protected string $note = '', protected string $actionUrl = '', protected ?int $iconId = null, protected string $iconAlternative = '', protected string $comment = '', protected readonly bool $isLocked = false, ) { $shortName = (new \ReflectionClass($this))->getShortName(); // Formating and assertions on string properties $this->name = self::formatName($name); $this->checkCommandArgs = array_map(trim(...), $checkCommandArgs); $this->eventHandlerCommandArgs = array_map(trim(...), $eventHandlerCommandArgs); $this->alias = trim($alias); $this->snmpCommunity = trim($snmpCommunity); $this->note = trim($note); $this->noteUrl = trim($noteUrl); $this->actionUrl = trim($actionUrl); $this->iconAlternative = trim($iconAlternative); $this->comment = trim($comment); Assertion::notEmptyString($this->name, "{$shortName}::name"); Assertion::notEmptyString($this->alias, "{$shortName}::alias"); Assertion::maxLength($this->name, self::MAX_NAME_LENGTH, "{$shortName}::name"); Assertion::maxLength($this->alias, self::MAX_ALIAS_LENGTH, "{$shortName}::alias"); Assertion::maxLength($this->snmpCommunity, self::MAX_SNMP_COMMUNITY_LENGTH, "{$shortName}::snmpCommunity"); Assertion::maxLength($this->noteUrl, self::MAX_NOTE_URL_LENGTH, "{$shortName}::noteUrl"); Assertion::maxLength($this->note, self::MAX_NOTE_LENGTH, "{$shortName}::note"); Assertion::maxLength($this->actionUrl, self::MAX_ACTION_URL_LENGTH, "{$shortName}::actionUrl"); Assertion::maxLength($this->iconAlternative, self::MAX_ICON_ALT_LENGTH, "{$shortName}::iconAlternative"); Assertion::maxLength($this->comment, self::MAX_COMMENT_LENGTH, "{$shortName}::comment"); // Assertions on ForeignKeys $foreignKeys = [ 'timezoneId' => $timezoneId, 'severityId' => $severityId, 'checkCommandId' => $checkCommandId, 'checkTimeperiodId' => $checkTimeperiodId, 'notificationTimeperiodId' => $notificationTimeperiodId, 'eventHandlerCommandId' => $eventHandlerCommandId, 'iconId' => $iconId, ]; foreach ($foreignKeys as $foreignKeyName => $foreignKeyValue) { if ($foreignKeyValue !== null) { Assertion::positiveInt($foreignKeyValue, "{$shortName}::{$foreignKeyName}"); } } // Assertion on integer properties Assertion::min($maxCheckAttempts ?? 0, 0, "{$shortName}::maxCheckAttempts"); Assertion::min($normalCheckInterval ?? 0, 0, "{$shortName}::normalCheckInterval"); Assertion::min($retryCheckInterval ?? 0, 0, "{$shortName}::retryCheckInterval"); Assertion::min($notificationInterval ?? 0, 0, "{$shortName}::notificationInterval"); Assertion::min($firstNotificationDelay ?? 0, 0, "{$shortName}::firstNotificationDelay"); Assertion::min($recoveryNotificationDelay ?? 0, 0, "{$shortName}::recoveryNotificationDelay"); Assertion::min($acknowledgementTimeout ?? 0, 0, "{$shortName}::acknowledgementTimeout"); Assertion::min($freshnessThreshold ?? 0, 0, "{$shortName}::freshnessThreshold"); Assertion::min($lowFlapThreshold ?? 0, 0, "{$shortName}::lowFlapThreshold"); Assertion::min($highFlapThreshold ?? 0, 0, "{$shortName}::highFlapThreshold"); } /** * Format a string as per domain rules for a host template name. * * @param string $name */ final public static function formatName(string $name): string { return str_replace(' ', '_', trim($name)); } public function getName(): string { return $this->name; } public function getAlias(): string { return $this->alias; } public function getSnmpCommunity(): string { return $this->snmpCommunity; } /** * @return string[] */ public function getCheckCommandArgs(): array { return $this->checkCommandArgs; } /** * @return string[] */ public function getEventHandlerCommandArgs(): array { return $this->eventHandlerCommandArgs; } public function getNoteUrl(): string { return $this->noteUrl; } public function getNote(): string { return $this->note; } public function getActionUrl(): string { return $this->actionUrl; } public function getIconAlternative(): string { return $this->iconAlternative; } public function getComment(): string { return $this->comment; } public function getTimezoneId(): ?int { return $this->timezoneId; } public function getSeverityId(): ?int { return $this->severityId; } public function getCheckCommandId(): ?int { return $this->checkCommandId; } public function getCheckTimeperiodId(): ?int { return $this->checkTimeperiodId; } public function getNotificationTimeperiodId(): ?int { return $this->notificationTimeperiodId; } public function getEventHandlerCommandId(): ?int { return $this->eventHandlerCommandId; } public function getIconId(): ?int { return $this->iconId; } public function getMaxCheckAttempts(): ?int { return $this->maxCheckAttempts; } public function getNormalCheckInterval(): ?int { return $this->normalCheckInterval; } public function getRetryCheckInterval(): ?int { return $this->retryCheckInterval; } public function getNotificationInterval(): ?int { return $this->notificationInterval; } public function getFirstNotificationDelay(): ?int { return $this->firstNotificationDelay; } public function getRecoveryNotificationDelay(): ?int { return $this->recoveryNotificationDelay; } public function getAcknowledgementTimeout(): ?int { return $this->acknowledgementTimeout; } public function getFreshnessThreshold(): ?int { return $this->freshnessThreshold; } public function getLowFlapThreshold(): ?int { return $this->lowFlapThreshold; } public function getHighFlapThreshold(): ?int { return $this->highFlapThreshold; } public function getSnmpVersion(): ?SnmpVersion { return $this->snmpVersion; } /** * @return HostEvent[] */ public function getNotificationOptions(): array { return $this->notificationOptions; } public function getActiveCheckEnabled(): YesNoDefault { return $this->activeCheckEnabled; } public function getPassiveCheckEnabled(): YesNoDefault { return $this->passiveCheckEnabled; } public function getNotificationEnabled(): YesNoDefault { return $this->notificationEnabled; } public function getFreshnessChecked(): YesNoDefault { return $this->freshnessChecked; } public function getFlapDetectionEnabled(): YesNoDefault { return $this->flapDetectionEnabled; } public function getEventHandlerEnabled(): YesNoDefault { return $this->eventHandlerEnabled; } public function addInheritedContactGroup(): bool { return $this->addInheritedContactGroup; } public function addInheritedContact(): bool { return $this->addInheritedContact; } public function isLocked(): bool { return $this->isLocked; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostTemplate/Domain/Model/HostTemplate.php
centreon/src/Core/HostTemplate/Domain/Model/HostTemplate.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\HostTemplate\Domain\Model; use Assert\AssertionFailedException; use Centreon\Domain\Common\Assertion\Assertion; use Core\Common\Domain\YesNoDefault; use Core\Host\Domain\Model\HostEvent; use Core\Host\Domain\Model\SnmpVersion; class HostTemplate extends NewHostTemplate { private string $shortName = ''; /** * @param int $id * @param string $name * @param string $alias * @param null|SnmpVersion $snmpVersion * @param string $snmpCommunity * @param null|int $timezoneId * @param null|int $severityId * @param null|int $checkCommandId * @param string[] $checkCommandArgs * @param null|int $checkTimeperiodId * @param null|int $maxCheckAttempts * @param null|int $normalCheckInterval * @param null|int $retryCheckInterval * @param YesNoDefault $activeCheckEnabled * @param YesNoDefault $passiveCheckEnabled * @param YesNoDefault $notificationEnabled * @param HostEvent[] $notificationOptions * @param null|int $notificationInterval * @param null|int $notificationTimeperiodId * @param bool $addInheritedContactGroup * @param bool $addInheritedContact * @param null|int $firstNotificationDelay * @param null|int $recoveryNotificationDelay * @param null|int $acknowledgementTimeout * @param YesNoDefault $freshnessChecked * @param null|int $freshnessThreshold * @param YesNoDefault $flapDetectionEnabled * @param null|int $lowFlapThreshold * @param null|int $highFlapThreshold * @param YesNoDefault $eventHandlerEnabled * @param null|int $eventHandlerCommandId * @param string[] $eventHandlerCommandArgs * @param string $noteUrl * @param string $note * @param string $actionUrl * @param null|int $iconId * @param string $iconAlternative * @param string $comment * @param bool $isLocked * * @throws AssertionFailedException */ public function __construct( private readonly int $id, string $name, string $alias, ?SnmpVersion $snmpVersion = null, string $snmpCommunity = '', ?int $timezoneId = null, ?int $severityId = null, ?int $checkCommandId = null, array $checkCommandArgs = [], ?int $checkTimeperiodId = null, ?int $maxCheckAttempts = null, ?int $normalCheckInterval = null, ?int $retryCheckInterval = null, YesNoDefault $activeCheckEnabled = YesNoDefault::Default, YesNoDefault $passiveCheckEnabled = YesNoDefault::Default, YesNoDefault $notificationEnabled = YesNoDefault::Default, array $notificationOptions = [], ?int $notificationInterval = null, ?int $notificationTimeperiodId = null, bool $addInheritedContactGroup = false, bool $addInheritedContact = false, ?int $firstNotificationDelay = null, ?int $recoveryNotificationDelay = null, ?int $acknowledgementTimeout = null, YesNoDefault $freshnessChecked = YesNoDefault::Default, ?int $freshnessThreshold = null, YesNoDefault $flapDetectionEnabled = YesNoDefault::Default, ?int $lowFlapThreshold = null, ?int $highFlapThreshold = null, YesNoDefault $eventHandlerEnabled = YesNoDefault::Default, ?int $eventHandlerCommandId = null, array $eventHandlerCommandArgs = [], string $noteUrl = '', string $note = '', string $actionUrl = '', ?int $iconId = null, string $iconAlternative = '', string $comment = '', bool $isLocked = false, ) { $this->shortName = (new \ReflectionClass($this))->getShortName(); Assertion::positiveInt($id, '{$this->shortName}::id'); parent::__construct( $name, $alias, $snmpVersion, $snmpCommunity, $timezoneId, $severityId, $checkCommandId, $checkCommandArgs, $checkTimeperiodId, $maxCheckAttempts, $normalCheckInterval, $retryCheckInterval, $activeCheckEnabled, $passiveCheckEnabled, $notificationEnabled, $notificationOptions, $notificationInterval, $notificationTimeperiodId, $addInheritedContactGroup, $addInheritedContact, $firstNotificationDelay, $recoveryNotificationDelay, $acknowledgementTimeout, $freshnessChecked, $freshnessThreshold, $flapDetectionEnabled, $lowFlapThreshold, $highFlapThreshold, $eventHandlerEnabled, $eventHandlerCommandId, $eventHandlerCommandArgs, $noteUrl, $note, $actionUrl, $iconId, $iconAlternative, $comment, $isLocked ); } public function getId(): int { return $this->id; } public function isNameIdentical(string $testName): bool { return $this->name === self::formatName($testName); } /** * @param string $name * * @throws AssertionFailedException */ public function setName(string $name): void { $this->name = $this->formatName($name); Assertion::notEmptyString($this->name, "{$this->shortName}::name"); Assertion::maxLength($this->name, self::MAX_NAME_LENGTH, "{$this->shortName}::name"); } /** * @param string $alias * * @throws AssertionFailedException */ public function setAlias(string $alias): void { $this->alias = trim($alias); Assertion::notEmptyString($this->alias, "{$this->shortName}::alias"); Assertion::maxLength($this->alias, self::MAX_ALIAS_LENGTH, "{$this->shortName}::alias"); } /** * @param string[] $checkCommandArgs */ public function setCheckCommandArgs(array $checkCommandArgs): void { $this->checkCommandArgs = array_map(trim(...), $checkCommandArgs); } /** * @param string[] $eventHandlerCommandArgs */ public function setEventHandlerCommandArgs(array $eventHandlerCommandArgs): void { $this->eventHandlerCommandArgs = array_map(trim(...), $eventHandlerCommandArgs); } /** * @param SnmpVersion|null $snmpVersion * * @throws AssertionFailedException */ public function setSnmpVersion(SnmpVersion|null $snmpVersion): void { $this->snmpVersion = $snmpVersion; } /** * @param string $snmpCommunity * * @throws AssertionFailedException */ public function setSnmpCommunity(string $snmpCommunity): void { $this->snmpCommunity = trim($snmpCommunity); Assertion::maxLength($this->snmpCommunity, self::MAX_SNMP_COMMUNITY_LENGTH, "{$this->shortName}::snmpCommunity"); } /** * @param string $note * * @throws AssertionFailedException */ public function setNote(string $note): void { $this->note = trim($note); Assertion::maxLength($this->note, self::MAX_NOTE_LENGTH, "{$this->shortName}::note"); } /** * @param string $noteUrl * * @throws AssertionFailedException */ public function setNoteUrl(string $noteUrl): void { $this->noteUrl = trim($noteUrl); Assertion::maxLength($this->noteUrl, self::MAX_NOTE_URL_LENGTH, "{$this->shortName}::noteUrl"); } /** * @param string $actionUrl * * @throws AssertionFailedException */ public function setActionUrl(string $actionUrl): void { $this->actionUrl = trim($actionUrl); Assertion::maxLength($this->actionUrl, self::MAX_ACTION_URL_LENGTH, "{$this->shortName}::actionUrl"); } /** * @param string $iconAlternative * * @throws AssertionFailedException */ public function setIconAlternative(string $iconAlternative): void { $this->iconAlternative = trim($iconAlternative); Assertion::maxLength($this->iconAlternative, self::MAX_ICON_ALT_LENGTH, "{$this->shortName}::iconAlternative"); } /** * @param string $comment * * @throws AssertionFailedException */ public function setComment(string $comment): void { $this->comment = trim($comment); Assertion::maxLength($this->comment, self::MAX_COMMENT_LENGTH, "{$this->shortName}::comment"); } /** * @param int|null $timezoneId * * @throws AssertionFailedException */ public function setTimezoneId(int|null $timezoneId): void { $this->timezoneId = $timezoneId; if ($this->timezoneId !== null) { Assertion::positiveInt($this->timezoneId, "{$this->shortName}::timezoneId"); } } /** * @param int|null $severityId * * @throws AssertionFailedException */ public function setSeverityId(int|null $severityId): void { $this->severityId = $severityId; if ($this->severityId !== null) { Assertion::positiveInt($this->severityId, "{$this->shortName}::severityId"); } } /** * @param int|null $checkCommandId * * @throws AssertionFailedException */ public function setCheckCommandId(int|null $checkCommandId): void { $this->checkCommandId = $checkCommandId; if ($this->checkCommandId !== null) { Assertion::positiveInt($this->checkCommandId, "{$this->shortName}::checkCommandId"); } } /** * @param int|null $checkTimeperiodId * * @throws AssertionFailedException */ public function setCheckTimeperiodId(int|null $checkTimeperiodId): void { $this->checkTimeperiodId = $checkTimeperiodId; if ($this->checkTimeperiodId !== null) { Assertion::positiveInt($this->checkTimeperiodId, "{$this->shortName}::checkTimeperiodId"); } } /** * @param int|null $notificationTimeperiodId * * @throws AssertionFailedException */ public function setNotificationTimeperiodId(int|null $notificationTimeperiodId): void { $this->notificationTimeperiodId = $notificationTimeperiodId; if ($this->notificationTimeperiodId !== null) { Assertion::positiveInt($this->notificationTimeperiodId, "{$this->shortName}::notificationTimeperiodId"); } } /** * @param int|null $eventHandlerCommandId * * @throws AssertionFailedException */ public function setEventHandlerCommandId(int|null $eventHandlerCommandId): void { $this->eventHandlerCommandId = $eventHandlerCommandId; if ($this->eventHandlerCommandId !== null) { Assertion::positiveInt($this->eventHandlerCommandId, "{$this->shortName}::eventHandlerCommandId"); } } /** * @param int|null $iconId * * @throws AssertionFailedException */ public function setIconId(int|null $iconId): void { $this->iconId = $iconId; if ($this->iconId !== null) { Assertion::positiveInt($this->iconId, "{$this->shortName}::iconId"); } } /** * @param int|null $maxCheckAttempts * * @throws AssertionFailedException */ public function setMaxCheckAttempts(int|null $maxCheckAttempts): void { $this->maxCheckAttempts = $maxCheckAttempts; Assertion::min($this->maxCheckAttempts ?? 0, 0, "{$this->shortName}::maxCheckAttempts"); } /** * @param int|null $normalCheckInterval * * @throws AssertionFailedException */ public function setNormalCheckInterval(int|null $normalCheckInterval): void { $this->normalCheckInterval = $normalCheckInterval; Assertion::min($this->normalCheckInterval ?? 0, 0, "{$this->shortName}::normalCheckInterval"); } /** * @param int|null $retryCheckInterval * * @throws AssertionFailedException */ public function setRetryCheckInterval(int|null $retryCheckInterval): void { $this->retryCheckInterval = $retryCheckInterval; Assertion::min($this->retryCheckInterval ?? 0, 0, "{$this->shortName}::retryCheckInterval"); } /** * @param int|null $notificationInterval * * @throws AssertionFailedException */ public function setNotificationInterval(int|null $notificationInterval): void { $this->notificationInterval = $notificationInterval; Assertion::min($this->notificationInterval ?? 0, 0, "{$this->shortName}::notificationInterval"); } /** * @param int|null $firstNotificationDelay * * @throws AssertionFailedException */ public function setFirstNotificationDelay(int|null $firstNotificationDelay): void { $this->firstNotificationDelay = $firstNotificationDelay; Assertion::min($this->firstNotificationDelay ?? 0, 0, "{$this->shortName}::firstNotificationDelay"); } /** * @param int|null $recoveryNotificationDelay * * @throws AssertionFailedException */ public function setRecoveryNotificationDelay(int|null $recoveryNotificationDelay): void { $this->recoveryNotificationDelay = $recoveryNotificationDelay; Assertion::min($this->recoveryNotificationDelay ?? 0, 0, "{$this->shortName}::recoveryNotificationDelay"); } /** * @param int|null $acknowledgementTimeout * * @throws AssertionFailedException */ public function setAcknowledgementTimeout(int|null $acknowledgementTimeout): void { $this->acknowledgementTimeout = $acknowledgementTimeout; Assertion::min($this->acknowledgementTimeout ?? 0, 0, "{$this->shortName}::acknowledgementTimeout"); } /** * @param int|null $freshnessThreshold * * @throws AssertionFailedException */ public function setFreshnessThreshold(int|null $freshnessThreshold): void { $this->freshnessThreshold = $freshnessThreshold; Assertion::min($this->freshnessThreshold ?? 0, 0, "{$this->shortName}::freshnessThreshold"); } /** * @param int|null $lowFlapThreshold * * @throws AssertionFailedException */ public function setLowFlapThreshold(int|null $lowFlapThreshold): void { $this->lowFlapThreshold = $lowFlapThreshold; Assertion::min($this->lowFlapThreshold ?? 0, 0, "{$this->shortName}::lowFlapThreshold"); } /** * @param int|null $highFlapThreshold * * @throws AssertionFailedException */ public function setHighFlapThreshold(int|null $highFlapThreshold): void { $this->highFlapThreshold = $highFlapThreshold; Assertion::min($this->highFlapThreshold ?? 0, 0, "{$this->shortName}::highFlapThreshold"); } /** * @param HostEvent[] $notificationOptions */ public function setNotificationOptions(array $notificationOptions): void { $this->notificationOptions = $notificationOptions; } public function setActiveCheckEnabled(YesNoDefault $activeCheckEnabled): void { $this->activeCheckEnabled = $activeCheckEnabled; } public function setPassiveCheckEnabled(YesNoDefault $passiveCheckEnabled): void { $this->passiveCheckEnabled = $passiveCheckEnabled; } public function setNotificationEnabled(YesNoDefault $notificationEnabled): void { $this->notificationEnabled = $notificationEnabled; } public function setFreshnessChecked(YesNoDefault $freshnessChecked): void { $this->freshnessChecked = $freshnessChecked; } public function setFlapDetectionEnabled(YesNoDefault $flapDetectionEnabled): void { $this->flapDetectionEnabled = $flapDetectionEnabled; } public function setEventHandlerEnabled(YesNoDefault $eventHandlerEnabled): void { $this->eventHandlerEnabled = $eventHandlerEnabled; } public function setAddInheritedContactGroup(bool $addInheritedContactGroup): void { $this->addInheritedContactGroup = $addInheritedContactGroup; } public function setAddInheritedContact(bool $addInheritedContact): void { $this->addInheritedContact = $addInheritedContact; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false