repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostTemplate/Infrastructure/Repository/DbReadHostTemplateRepository.php
centreon/src/Core/HostTemplate/Infrastructure/Repository/DbReadHostTemplateRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Infrastructure\Repository; use Centreon\Domain\Log\LoggerTrait; use Centreon\Domain\Repository\RepositoryException; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Centreon\Infrastructure\DatabaseConnection; use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator; use Core\Common\Application\Converter\YesNoDefaultConverter; use Core\Common\Domain\HostType; use Core\Common\Domain\YesNoDefault; use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB; use Core\Common\Infrastructure\RequestParameters\Normalizer\BoolToEnumNormalizer; use Core\Host\Application\Converter\HostEventConverter; use Core\Host\Domain\Model\SnmpVersion; use Core\HostCategory\Infrastructure\Repository\HostCategoryRepositoryTrait; use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface; use Core\HostTemplate\Domain\Model\HostTemplate; use Utility\SqlConcatenator; /** * @phpstan-type _HostTemplate array{ * host_id: int, * host_name: string, * host_alias: string, * host_snmp_version: string|null, * host_snmp_community: string|null, * host_location: int|null, * command_command_id: int|null, * command_command_id_arg1: string|null, * timeperiod_tp_id: int|null, * host_max_check_attempts: int|null, * host_check_interval: int|null, * host_retry_check_interval: int|null, * host_active_checks_enabled: string|null, * host_passive_checks_enabled: string|null, * host_notifications_enabled: string|null, * host_notification_options: string|null, * host_notification_interval: int|null, * timeperiod_tp_id2: int|null, * cg_additive_inheritance: int|null, * contact_additive_inheritance: int|null, * host_first_notification_delay: int|null, * host_recovery_notification_delay: int|null, * host_acknowledgement_timeout: int|null, * host_check_freshness: string|null, * host_freshness_threshold: int|null, * host_flap_detection_enabled: string|null, * host_low_flap_threshold: int|null, * host_high_flap_threshold: int|null, * host_event_handler_enabled: string|null, * command_command_id2: int|null, * command_command_id_arg2: string|null, * host_comment: string|null, * host_locked: int|null, * ehi_notes_url: string|null, * ehi_notes: string|null, * ehi_action_url: string|null, * ehi_icon_image: int|null, * ehi_icon_image_alt: string|null, * severity_id: int|null * } */ class DbReadHostTemplateRepository extends AbstractRepositoryRDB implements ReadHostTemplateRepositoryInterface { use LoggerTrait; use HostCategoryRepositoryTrait; /** * @param DatabaseConnection $db */ public function __construct(DatabaseConnection $db) { $this->db = $db; } /** * @inheritDoc */ public function findByRequestParameter(RequestParametersInterface $requestParameters): array { $this->info('Getting all host templates'); $concatenator = new SqlConcatenator(); $concatenator->withCalcFoundRows(true); $concatenator->defineSelect( <<<'SQL' SELECT h.host_id, h.host_name, h.host_alias, h.host_snmp_version, h.host_snmp_community, h.host_location, h.command_command_id, h.command_command_id_arg1, h.timeperiod_tp_id, h.host_max_check_attempts, h.host_check_interval, h.host_retry_check_interval, h.host_active_checks_enabled, h.host_passive_checks_enabled, h.host_notifications_enabled, h.host_notification_options, h.host_notification_interval, h.timeperiod_tp_id2, h.cg_additive_inheritance, h.contact_additive_inheritance, h.host_first_notification_delay, h.host_recovery_notification_delay, h.host_acknowledgement_timeout, h.host_check_freshness, h.host_freshness_threshold, h.host_flap_detection_enabled, h.host_low_flap_threshold, h.host_high_flap_threshold, h.host_event_handler_enabled, h.command_command_id2, h.command_command_id_arg2, h.host_comment, h.host_locked, ehi.ehi_notes_url, ehi.ehi_notes, ehi.ehi_action_url, ehi.ehi_icon_image, ehi.ehi_icon_image_alt, ( SELECT hc.hc_id FROM `:db`.hostcategories hc INNER JOIN `:db`.hostcategories_relation hcr ON hc.hc_id = hcr.hostcategories_hc_id WHERE hc.level IS NOT NULL AND hcr.host_host_id = h.host_id ORDER BY hc.level, hc.hc_id LIMIT 1 ) AS severity_id FROM `:db`.host h LEFT JOIN `:db`.extended_host_information ehi ON h.host_id = ehi.host_host_id SQL ); $concatenator->appendGroupBy('GROUP BY h.host_id'); // Filter on host templates $concatenator->appendWhere('h.host_register = :hostTemplateType'); $concatenator->storeBindValue(':hostTemplateType', HostType::Template->value, \PDO::PARAM_STR); // Settup for search, pagination, order $sqlTranslator = new SqlRequestParametersTranslator($requestParameters); $sqlTranslator->setConcordanceArray([ 'id' => 'h.host_id', 'name' => 'h.host_name', 'alias' => 'h.host_alias', 'is_locked' => 'h.host_locked', ]); $sqlTranslator->addNormalizer('is_locked', new BoolToEnumNormalizer()); $sqlTranslator->translateForConcatenator($concatenator); $statement = $this->db->prepare($this->translateDbName($concatenator->__toString())); $sqlTranslator->bindSearchValues($statement); $concatenator->bindValuesToStatement($statement); $statement->execute(); $sqlTranslator->calculateNumberOfRows($this->db); $hostTemplates = []; while (is_array($result = $statement->fetch(\PDO::FETCH_ASSOC))) { /** @var _HostTemplate $result */ $hostTemplates[] = $this->createHostTemplateFromArray($result); } return $hostTemplates; } /** * @inheritDoc */ public function findByRequestParametersAndAccessGroups( RequestParametersInterface $requestParameters, array $accessGroups, ): array { $this->info('Getting all host templates'); if ($accessGroups === []) { return []; } $accessGroupIds = array_map( static fn ($accessGroup) => $accessGroup->getId(), $accessGroups ); $subRequest = $this->generateHostCategoryAclSubRequest($accessGroupIds); $categoryAcls = empty($subRequest) ? '' : <<<SQL AND hc.hc_id IN ({$subRequest}) SQL; $request = <<<SQL SELECT SQL_CALC_FOUND_ROWS h.host_id, h.host_name, h.host_alias, h.host_snmp_version, h.host_snmp_community, h.host_location, h.command_command_id, h.command_command_id_arg1, h.timeperiod_tp_id, h.host_max_check_attempts, h.host_check_interval, h.host_retry_check_interval, h.host_active_checks_enabled, h.host_passive_checks_enabled, h.host_notifications_enabled, h.host_notification_options, h.host_notification_interval, h.timeperiod_tp_id2, h.cg_additive_inheritance, h.contact_additive_inheritance, h.host_first_notification_delay, h.host_recovery_notification_delay, h.host_acknowledgement_timeout, h.host_check_freshness, h.host_freshness_threshold, h.host_flap_detection_enabled, h.host_low_flap_threshold, h.host_high_flap_threshold, h.host_event_handler_enabled, h.command_command_id2, h.command_command_id_arg2, h.host_comment, h.host_locked, ehi.ehi_notes_url, ehi.ehi_notes, ehi.ehi_action_url, ehi.ehi_icon_image, ehi.ehi_icon_image_alt, ( SELECT hc.hc_id FROM `:db`.hostcategories hc INNER JOIN `:db`.hostcategories_relation hcr ON hc.hc_id = hcr.hostcategories_hc_id WHERE hc.level IS NOT NULL AND hcr.host_host_id = h.host_id ORDER BY hc.level, hc.hc_id LIMIT 1 ) AS severity_id FROM `:db`.host h LEFT JOIN `:db`.extended_host_information ehi ON h.host_id = ehi.host_host_id LEFT JOIN `:db`.hostcategories_relation hcr ON hcr.host_host_id = h.host_id LEFT JOIN `:db`.hostcategories hc ON hc.hc_id = hcr.hostcategories_hc_id AND hc.level IS NOT NULL WHERE h.host_register = :host_template_type {$categoryAcls} SQL; $sqlTranslator = new SqlRequestParametersTranslator($requestParameters); $sqlTranslator->setConcordanceArray([ 'id' => 'h.host_id', 'name' => 'h.host_name', 'alias' => 'h.host_alias', 'is_locked' => 'h.host_locked', ]); $sqlTranslator->addNormalizer('is_locked', new BoolToEnumNormalizer()); if ($search = $sqlTranslator->translateSearchParameterToSql()) { $request .= str_replace('WHERE', 'AND', $search); } $request .= <<<'SQL' GROUP BY h.host_id SQL; if ($sort = $sqlTranslator->translateSortParameterToSql()) { $request .= $sort; } if ($pagination = $sqlTranslator->translatePaginationToSql()) { $request .= $pagination; } $statement = $this->db->prepare($this->translateDbName($request)); $statement->bindValue(':host_template_type', HostType::Template->value, \PDO::PARAM_STR); if ($this->hasRestrictedAccessToHostCategories($accessGroupIds)) { foreach ($accessGroupIds as $index => $accessGroupId) { $statement->bindValue(':access_group_id_' . $index, $accessGroupId, \PDO::PARAM_INT); } } $sqlTranslator->bindSearchValues($statement); $statement->execute(); $sqlTranslator->calculateNumberOfRows($this->db); $hostTemplates = []; while (is_array($result = $statement->fetch(\PDO::FETCH_ASSOC))) { /** @var _HostTemplate $result */ $hostTemplates[] = $this->createHostTemplateFromArray($result); } return $hostTemplates; } /** * @inheritDoc */ public function findById(int $hostTemplateId): ?HostTemplate { $this->info('Get a host template with ID #' . $hostTemplateId); $request = $this->translateDbName( <<<'SQL' SELECT h.host_id, h.host_name, h.host_alias, h.host_snmp_version, h.host_snmp_community, h.host_location, h.command_command_id, h.command_command_id_arg1, h.timeperiod_tp_id, h.host_max_check_attempts, h.host_check_interval, h.host_retry_check_interval, h.host_active_checks_enabled, h.host_passive_checks_enabled, h.host_notifications_enabled, h.host_notification_options, h.host_notification_interval, h.timeperiod_tp_id2, h.cg_additive_inheritance, h.contact_additive_inheritance, h.host_first_notification_delay, h.host_recovery_notification_delay, h.host_acknowledgement_timeout, h.host_check_freshness, h.host_freshness_threshold, h.host_flap_detection_enabled, h.host_low_flap_threshold, h.host_high_flap_threshold, h.host_event_handler_enabled, h.command_command_id2, h.command_command_id_arg2, h.host_comment, h.host_locked, ehi.ehi_notes_url, ehi.ehi_notes, ehi.ehi_action_url, ehi.ehi_icon_image, ehi.ehi_icon_image_alt, hc.hc_id AS severity_id FROM `:db`.host h LEFT JOIN `:db`.extended_host_information ehi ON h.host_id = ehi.host_host_id LEFT JOIN `:db`.hostcategories_relation hcr ON hcr.host_host_id = h.host_id LEFT JOIN `:db`.hostcategories hc ON hc.hc_id = hcr.hostcategories_hc_id AND hc.level IS NOT NULL WHERE h.host_id = :hostTemplateId AND h.host_register = :hostTemplateType SQL ); $statement = $this->db->prepare($request); $statement->bindValue(':hostTemplateId', $hostTemplateId, \PDO::PARAM_INT); $statement->bindValue(':hostTemplateType', HostType::Template->value, \PDO::PARAM_STR); $statement->execute(); $result = $statement->fetch(\PDO::FETCH_ASSOC); if ($result === false) { return null; } /** @var _HostTemplate $result */ return $this->createHostTemplateFromArray($result); } /** * @inheritDoc */ public function findByIdAndAccessGroups(int $hostTemplateId, array $accessGroups): ?HostTemplate { $this->info('Get a host template with ID #' . $hostTemplateId); $accessGroupIds = array_map( static fn ($accessGroup) => $accessGroup->getId(), $accessGroups ); $subRequest = $this->generateHostCategoryAclSubRequest($accessGroupIds); $categoryAcls = empty($subRequest) ? '' : <<<SQL AND hc.hc_id IN ({$subRequest}) SQL; $request = $this->translateDbName( <<<SQL SELECT h.host_id, h.host_name, h.host_alias, h.host_snmp_version, h.host_snmp_community, h.host_location, h.command_command_id, h.command_command_id_arg1, h.timeperiod_tp_id, h.host_max_check_attempts, h.host_check_interval, h.host_retry_check_interval, h.host_active_checks_enabled, h.host_passive_checks_enabled, h.host_notifications_enabled, h.host_notification_options, h.host_notification_interval, h.timeperiod_tp_id2, h.cg_additive_inheritance, h.contact_additive_inheritance, h.host_first_notification_delay, h.host_recovery_notification_delay, h.host_acknowledgement_timeout, h.host_check_freshness, h.host_freshness_threshold, h.host_flap_detection_enabled, h.host_low_flap_threshold, h.host_high_flap_threshold, h.host_event_handler_enabled, h.command_command_id2, h.command_command_id_arg2, h.host_comment, h.host_locked, ehi.ehi_notes_url, ehi.ehi_notes, ehi.ehi_action_url, ehi.ehi_icon_image, ehi.ehi_icon_image_alt, hc.hc_id AS severity_id FROM `:db`.host h LEFT JOIN `:db`.extended_host_information ehi ON h.host_id = ehi.host_host_id LEFT JOIN `:db`.hostcategories_relation hcr ON hcr.host_host_id = h.host_id LEFT JOIN `:db`.hostcategories hc ON hc.hc_id = hcr.hostcategories_hc_id AND hc.level IS NOT NULL WHERE h.host_id = :host_template_id AND h.host_register = :host_template_type {$categoryAcls} SQL ); $statement = $this->db->prepare($this->translateDbName($request)); $statement->bindValue(':host_template_id', $hostTemplateId, \PDO::PARAM_INT); $statement->bindValue(':host_template_type', HostType::Template->value, \PDO::PARAM_STR); if ($this->hasRestrictedAccessToHostCategories($accessGroupIds)) { foreach ($accessGroupIds as $index => $accessGroupId) { $statement->bindValue(':access_group_id_' . $index, $accessGroupId, \PDO::PARAM_INT); } } $statement->execute(); if ($result = $statement->fetch(\PDO::FETCH_ASSOC)) { /** @var _HostTemplate $result */ return $this->createHostTemplateFromArray($result); } return null; } /** * @inheritDoc */ public function findByIds(int ...$hostTemplateIds): array { if ($hostTemplateIds === []) { return []; } $bindValues = []; foreach ($hostTemplateIds as $index => $templateId) { $bindValues[':tpl_' . $index] = $templateId; } $hostTemplateIdsQuery = implode(', ', array_keys($bindValues)); $request = $this->translateDbName( <<<SQL SELECT h.host_id, h.host_name, h.host_alias, h.host_snmp_version, h.host_snmp_community, h.host_location, h.command_command_id, h.command_command_id_arg1, h.timeperiod_tp_id, h.host_max_check_attempts, h.host_check_interval, h.host_retry_check_interval, h.host_active_checks_enabled, h.host_passive_checks_enabled, h.host_notifications_enabled, h.host_notification_options, h.host_notification_interval, h.timeperiod_tp_id2, h.cg_additive_inheritance, h.contact_additive_inheritance, h.host_first_notification_delay, h.host_recovery_notification_delay, h.host_acknowledgement_timeout, h.host_check_freshness, h.host_freshness_threshold, h.host_flap_detection_enabled, h.host_low_flap_threshold, h.host_high_flap_threshold, h.host_event_handler_enabled, h.command_command_id2, h.command_command_id_arg2, h.host_comment, h.host_locked, ehi.ehi_notes_url, ehi.ehi_notes, ehi.ehi_action_url, ehi.ehi_icon_image, ehi.ehi_icon_image_alt, ( SELECT hc.hc_id FROM `:db`.hostcategories hc INNER JOIN `:db`.hostcategories_relation hcr ON hc.hc_id = hcr.hostcategories_hc_id WHERE hc.level IS NOT NULL AND hcr.host_host_id = h.host_id ORDER BY hc.level, hc.hc_id LIMIT 1 ) AS severity_id FROM `:db`.host h LEFT JOIN `:db`.extended_host_information ehi ON h.host_id = ehi.host_host_id WHERE h.host_register = '0' AND h.host_id IN ({$hostTemplateIdsQuery}) GROUP BY h.host_id SQL ); $statement = $this->db->prepare($request); foreach ($bindValues as $bindKey => $categoryId) { $statement->bindValue($bindKey, $categoryId, \PDO::PARAM_INT); } $statement->setFetchMode(\PDO::FETCH_ASSOC); $statement->execute(); $hostTemplates = []; foreach ($statement as $result) { /** @var _HostTemplate $result */ $hostTemplates[] = $this->createHostTemplateFromArray($result); } return $hostTemplates; } /** * @inheritDoc */ public function findParents(int $hostTemplateId): array { $this->info('Find parents IDs of host template with ID #' . $hostTemplateId); $request = $this->translateDbName( <<<'SQL' WITH RECURSIVE parents AS ( SELECT 1 as counter, host_template_relation.* FROM `:db`.`host_template_relation` WHERE `host_host_id` = :hostTemplateId UNION SELECT p.counter + 1, rel.* FROM `:db`.`host_template_relation` AS rel, parents AS p WHERE rel.`host_host_id` = p.`host_tpl_id` ) SELECT counter, `host_host_id` AS child_id, `host_tpl_id` AS parent_id, `order` FROM parents order by counter, `order`; SQL ); $statement = $this->db->prepare($request); $statement->bindValue(':hostTemplateId', $hostTemplateId, \PDO::PARAM_INT); $statement->execute(); return $statement->fetchAll(\PDO::FETCH_ASSOC); } /** * @inheritDoc */ public function findAllExistingIds(array $hostTemplateIds): array { if ($hostTemplateIds === []) { return []; } $hostTemplateIdsFound = []; $concatenator = new SqlConcatenator(); $request = $this->translateDbName( <<<'SQL' SELECT host_id FROM `:db`.host WHERE host_register = '0' AND host_id IN (:host_ids) SQL ); $concatenator->defineSelect($request); $concatenator->storeBindValueMultiple(':host_ids', $hostTemplateIds, \PDO::PARAM_INT); $statement = $this->db->prepare((string) $concatenator); $concatenator->bindValuesToStatement($statement); $statement->execute(); while (($id = $statement->fetchColumn()) !== false) { $hostTemplateIdsFound[] = (int) $id; } return $hostTemplateIdsFound; } /** * @inheritDoc */ public function exists(int $hostTemplateId): bool { $this->info('Check existence of host template with ID #' . $hostTemplateId); $request = $this->translateDbName( <<<'SQL' SELECT 1 FROM `:db`.host WHERE host_id = :hostTemplateId AND host_register = :hostTemplateType SQL ); $statement = $this->db->prepare($request); $statement->bindValue(':hostTemplateId', $hostTemplateId, \PDO::PARAM_INT); $statement->bindValue(':hostTemplateType', HostType::Template->value, \PDO::PARAM_STR); $statement->execute(); return (bool) $statement->fetchColumn(); } /** * @inheritDoc */ public function exist(array $hostTemplateIds): array { $this->info('Check existence of host templates', ['host_template_ids' => $hostTemplateIds]); if ($hostTemplateIds === []) { return []; } $concatenator = new SqlConcatenator(); $concatenator ->defineSelect( <<<'SQL' SELECT `host_id` FROM `:db`.`host` SQL ) ->appendWhere('host_id IN (:host_template_ids)') ->appendWhere('host_register = :hostTemplateType') ->storeBindValueMultiple(':host_template_ids', $hostTemplateIds, \PDO::PARAM_INT) ->storeBindValue(':hostTemplateType', HostType::Template->value, \PDO::PARAM_STR); $statement = $this->db->prepare($this->translateDbName($concatenator->__toString())); $concatenator->bindValuesToStatement($statement); $statement->execute(); return $statement->fetchAll(\PDO::FETCH_COLUMN); } /** * @inheritDoc */ public function existsByName(string $hostTemplateName): bool { $this->info('Check existence of host template with name #' . $hostTemplateName); $request = $this->translateDbName( <<<'SQL' SELECT 1 FROM `:db`.host WHERE host_name = :hostTemplateName SQL ); $statement = $this->db->prepare($request); $statement->bindValue(':hostTemplateName', $hostTemplateName, \PDO::PARAM_STR); $statement->execute(); return (bool) $statement->fetchColumn(); } /** * @inheritDoc */ public function isLocked(int $hostTemplateId): bool { $this->info('Check is_locked property for host template with ID #' . $hostTemplateId); $request = $this->translateDbName( <<<'SQL' SELECT host_locked FROM `:db`.host WHERE host_id = :hostTemplateId SQL ); $statement = $this->db->prepare($request); $statement->bindValue(':hostTemplateId', $hostTemplateId, \PDO::PARAM_STR); $statement->execute(); return (bool) $statement->fetchColumn(); } /** * @inheritDoc */ public function findNamesByIds(array $hostTemplateIds): array { $this->info('Find names for host templates', ['host_template_ids' => $hostTemplateIds]); if ($hostTemplateIds === []) { return []; } $concatenator = new SqlConcatenator(); $concatenator ->defineSelect( <<<'SQL' SELECT `host_id`, `host_name` FROM `:db`.`host` SQL ) ->appendWhere('host_id IN (:host_template_ids)') ->appendWhere('host_register = :hostTemplateType') ->storeBindValueMultiple(':host_template_ids', $hostTemplateIds, \PDO::PARAM_INT) ->storeBindValue(':hostTemplateType', HostType::Template->value, \PDO::PARAM_STR); $statement = $this->db->prepare($this->translateDbName($concatenator->__toString())); $concatenator->bindValuesToStatement($statement); $statement->execute(); $results = $statement->fetchAll(\PDO::FETCH_ASSOC); $nameById = []; foreach ($results as $row) { $nameById[(int) $row['host_id']] = $row['host_name']; } return $nameById; } /** * @inheritDoc */ public function findAll(): array { $request = $this->translateDbName( <<<'SQL' SELECT h.host_id, h.host_name, h.host_alias, h.host_snmp_version, h.host_snmp_community, h.host_location, h.command_command_id, h.command_command_id_arg1, h.timeperiod_tp_id, h.host_max_check_attempts, h.host_check_interval, h.host_retry_check_interval, h.host_active_checks_enabled, h.host_passive_checks_enabled, h.host_notifications_enabled, h.host_notification_options, h.host_notification_interval, h.timeperiod_tp_id2, h.cg_additive_inheritance, h.contact_additive_inheritance, h.host_first_notification_delay, h.host_recovery_notification_delay, h.host_acknowledgement_timeout, h.host_check_freshness, h.host_freshness_threshold, h.host_flap_detection_enabled, h.host_low_flap_threshold, h.host_high_flap_threshold, h.host_event_handler_enabled, h.command_command_id2, h.command_command_id_arg2, h.host_comment, h.host_locked, ehi.ehi_notes_url, ehi.ehi_notes, ehi.ehi_action_url, ehi.ehi_icon_image, ehi.ehi_icon_image_alt, hc.hc_id AS severity_id FROM `:db`.host h LEFT JOIN `:db`.extended_host_information ehi ON h.host_id = ehi.host_host_id LEFT JOIN `:db`.hostcategories_relation hcr ON hcr.host_host_id = h.host_id LEFT JOIN `:db`.hostcategories hc ON hc.hc_id = hcr.hostcategories_hc_id AND hc.level IS NOT NULL WHERE h.host_register = :hostTemplateType SQL ); $statement = $this->db->prepare($request); $statement->bindValue(':hostTemplateType', HostType::Template->value, \PDO::PARAM_STR); $statement->execute(); $hostTemplates = []; while ($result = $statement->fetch(\PDO::FETCH_ASSOC)) { /** @var _HostTemplate $result */ $hostTemplates[] = $this->createHostTemplateFromArray($result); } return $hostTemplates; } /** * @inheritDoc */ public function findByHostId(int $hostId): array { try { $request = $this->translateDbName( <<<'SQL' SELECT host_tpl_id FROM host_template_relation WHERE host_host_id = :hostId ORDER BY `order` ASC SQL ); $statement = $this->db->prepare($request); $statement->bindValue(':hostId', $hostId, \PDO::PARAM_INT); $statement->execute(); return $statement->fetchAll(\PDO::FETCH_COLUMN);
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
true
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostTemplate/Infrastructure/Repository/DbWriteHostTemplateRepository.php
centreon/src/Core/HostTemplate/Infrastructure/Repository/DbWriteHostTemplateRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Infrastructure\Repository; use Centreon\Domain\Log\LoggerTrait; use Centreon\Infrastructure\DatabaseConnection; use Core\Common\Application\Converter\YesNoDefaultConverter; use Core\Common\Domain\HostType; use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB; use Core\Common\Infrastructure\Repository\RepositoryTrait; use Core\Common\Infrastructure\RequestParameters\Normalizer\BoolToEnumNormalizer; use Core\Host\Application\Converter\HostEventConverter; use Core\HostTemplate\Application\Repository\WriteHostTemplateRepositoryInterface; use Core\HostTemplate\Domain\Model\HostTemplate; use Core\HostTemplate\Domain\Model\NewHostTemplate; class DbWriteHostTemplateRepository extends AbstractRepositoryRDB implements WriteHostTemplateRepositoryInterface { use LoggerTrait; use RepositoryTrait; /** * @param DatabaseConnection $db */ public function __construct(DatabaseConnection $db) { $this->db = $db; } /** * @inheritDoc */ public function delete(int $hostTemplateId): void { $this->debug('Delete host template', ['host_template_id' => $hostTemplateId]); $request = $this->translateDbName( <<<'SQL' DELETE FROM `:db`.host WHERE host_id = :hostTemplateId AND host_register = :hostTemplateType SQL ); $statement = $this->db->prepare($request); $statement->bindValue(':hostTemplateId', $hostTemplateId, \PDO::PARAM_INT); $statement->bindValue(':hostTemplateType', HostType::Template->value, \PDO::PARAM_STR); $statement->execute(); } /** * @inheritDoc */ public function add(NewHostTemplate $hostTemplate): int { $this->debug('Add host template'); $alreadyInTransaction = $this->db->inTransaction(); if (! $alreadyInTransaction) { $this->db->beginTransaction(); } try { $hostTemplateId = $this->addTemplateBasicInformations($hostTemplate); $this->addExtendedInformations($hostTemplateId, $hostTemplate); if ($hostTemplate->getSeverityId() !== null) { $this->addSeverity($hostTemplateId, $hostTemplate); } if (! $alreadyInTransaction) { $this->db->commit(); } $this->debug('Host template added with ID ' . $hostTemplateId); return $hostTemplateId; } catch (\Throwable $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); if (! $alreadyInTransaction) { $this->db->rollBack(); } throw $ex; } } /** * @inheritDoc */ public function update(HostTemplate $hostTemplate): void { $alreadyInTransaction = $this->db->inTransaction(); if (! $alreadyInTransaction) { $this->db->beginTransaction(); } try { $this->updateTemplateBasicInformations($hostTemplate); $this->updateExtendedInformations($hostTemplate); $this->deleteSeverity($hostTemplate->getId()); if ($hostTemplate->getSeverityId() !== null) { $this->addSeverity($hostTemplate->getId(), $hostTemplate); } if (! $alreadyInTransaction) { $this->db->commit(); } } catch (\Throwable $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); if (! $alreadyInTransaction) { $this->db->rollBack(); } throw $ex; } } /** * @inheritDoc */ public function addParent(int $childId, int $parentId, int $order): void { $statement = $this->db->prepare($this->translateDbName( <<<'SQL' INSERT INTO `:db`.`host_template_relation` (`host_tpl_id`, `host_host_id`, `order`) VALUES (:parent_id, :child_id, :order) SQL )); $statement->bindValue(':child_id', $childId, \PDO::PARAM_INT); $statement->bindValue(':parent_id', $parentId, \PDO::PARAM_INT); $statement->bindValue(':order', $order, \PDO::PARAM_INT); $statement->execute(); } /** * @inheritDoc */ public function deleteParents(int $childId): void { $statement = $this->db->prepare($this->translateDbName( <<<'SQL' DELETE FROM `:db`.`host_template_relation` WHERE `host_host_id` = :child_id SQL )); $statement->bindValue(':child_id', $childId, \PDO::PARAM_INT); $statement->execute(); } private function addTemplateBasicInformations(NewHostTemplate $hostTemplate): int { $request = $this->translateDbName( <<<'SQL' INSERT INTO `:db`.host ( host_name, host_alias, host_snmp_version, host_snmp_community, host_location, command_command_id, command_command_id_arg1, timeperiod_tp_id, host_max_check_attempts, host_check_interval, host_retry_check_interval, host_active_checks_enabled, host_passive_checks_enabled, host_notifications_enabled, host_notification_options, host_notification_interval, timeperiod_tp_id2, cg_additive_inheritance, contact_additive_inheritance, host_first_notification_delay, host_recovery_notification_delay, host_acknowledgement_timeout, host_check_freshness, host_freshness_threshold, host_flap_detection_enabled, host_low_flap_threshold, host_high_flap_threshold, host_event_handler_enabled, command_command_id2, command_command_id_arg2, host_comment, host_activate, host_locked, host_register ) VALUES ( :name, :alias, :snmpVersion, :snmpCommunity, :timezoneId, :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, :comment, :isActivated, :isLocked, :hostType ) SQL ); $statement = $this->db->prepare($request); $this->bindHostTemplateValues($statement, $hostTemplate); $statement->execute(); return (int) $this->db->lastInsertId(); } private function addExtendedInformations(int $hostTemplateId, NewHostTemplate $hostTemplate): void { $request = $this->translateDbName( <<<'SQL' INSERT INTO `:db`.extended_host_information ( host_host_id, ehi_notes_url, ehi_notes, ehi_action_url, ehi_icon_image, ehi_icon_image_alt ) VALUES ( :hostTemplateId, :noteUrl, :note, :actionUrl, :iconId, :iconAlternative ) SQL ); $statement = $this->db->prepare($request); $statement->bindValue(':hostTemplateId', $hostTemplateId, \PDO::PARAM_INT); $statement->bindValue( ':noteUrl', $hostTemplate->getNoteUrl() === '' ? null : $hostTemplate->getNoteUrl(), \PDO::PARAM_STR ); $statement->bindValue( ':note', $hostTemplate->getNote() === '' ? null : $hostTemplate->getNote(), \PDO::PARAM_STR ); $statement->bindValue( ':actionUrl', $hostTemplate->getActionUrl() === '' ? null : $hostTemplate->getActionUrl(), \PDO::PARAM_STR ); $statement->bindValue(':iconId', $hostTemplate->getIconId(), \PDO::PARAM_INT); $statement->bindValue( ':iconAlternative', $hostTemplate->getIconAlternative() === '' ? null : $hostTemplate->getIconAlternative(), \PDO::PARAM_STR ); $statement->execute(); } private function addSeverity(int $hostTemplateId, NewHostTemplate $hostTemplate): void { $request = $this->translateDbName( <<<'SQL' INSERT INTO `:db`.hostcategories_relation ( host_host_id, hostcategories_hc_id ) VALUES ( :hostTemplateId, :severityId ) SQL ); $statement = $this->db->prepare($request); $statement->bindValue(':hostTemplateId', $hostTemplateId, \PDO::PARAM_INT); $statement->bindValue(':severityId', $hostTemplate->getSeverityId(), \PDO::PARAM_INT); $statement->execute(); } private function deleteSeverity(int $hostTemplateId): void { $request = $this->translateDbName( <<<'SQL' DELETE rel FROM `:db`.`hostcategories_relation` rel LEFT JOIN `:db`.`hostcategories` hc ON hc.hc_id = rel.hostcategories_hc_id WHERE rel.host_host_id = :hostTemplateId AND hc.level IS NOT NULL SQL ); $statement = $this->db->prepare($request); $statement->bindValue(':hostTemplateId', $hostTemplateId, \PDO::PARAM_INT); $statement->execute(); } private function updateTemplateBasicInformations(HostTemplate $hostTemplate): void { $request = $this->translateDbName( <<<'SQL' UPDATE `:db`.`host` SET `host_name` = :name, `host_alias` = :alias, `host_snmp_version` = :snmpVersion, `host_snmp_community` = :snmpCommunity, `host_location` = :timezoneId, `command_command_id` = :checkCommandId, `command_command_id_arg1` = :checkCommandArgs, `timeperiod_tp_id` = :checkTimeperiodId, `host_max_check_attempts` = :maxCheckAttempts, `host_check_interval` = :normalCheckInterval, `host_retry_check_interval` = :retryCheckInterval, `host_active_checks_enabled` = :activeCheckEnabled, `host_passive_checks_enabled` = :passiveCheckEnabled, `host_notifications_enabled` = :notificationEnabled, `host_notification_options` = :notificationOptions, `host_notification_interval` = :notificationInterval, `timeperiod_tp_id2` = :notificationTimeperiodId, `cg_additive_inheritance` = :addInheritedContactGroup, `contact_additive_inheritance` = :addInheritedContact, `host_first_notification_delay` = :firstNotificationDelay, `host_recovery_notification_delay` = :recoveryNotificationDelay, `host_acknowledgement_timeout` = :acknowledgementTimeout, `host_check_freshness` = :freshnessChecked, `host_freshness_threshold` = :freshnessThreshold, `host_flap_detection_enabled` = :flapDetectionEnabled, `host_low_flap_threshold` = :lowFlapThreshold, `host_high_flap_threshold` = :highFlapThreshold, `host_event_handler_enabled` = :eventHandlerEnabled, `command_command_id2` = :eventHandlerCommandId, `command_command_id_arg2` = :eventHandlerCommandArgs, `host_comment` = :comment, `host_activate` = :isActivated, `host_locked` = :isLocked, `host_register` = :hostType WHERE `host_id` = :hostId SQL ); $statement = $this->db->prepare($request); $statement->bindValue(':hostId', $hostTemplate->getId(), \PDO::PARAM_INT); $this->bindHostTemplateValues($statement, $hostTemplate); $statement->execute(); } private function updateExtendedInformations(HostTemplate $hostTemplate): void { $request = $this->translateDbName( <<<'SQL' UPDATE `:db`.`extended_host_information` SET ehi_notes_url = :noteUrl, ehi_notes = :note, ehi_action_url = :actionUrl, ehi_icon_image = :iconId, ehi_icon_image_alt = :iconAlternative WHERE host_host_id = :hostTemplateId SQL ); $statement = $this->db->prepare($request); $statement->bindValue(':hostTemplateId', $hostTemplate->getId(), \PDO::PARAM_INT); $statement->bindValue( ':noteUrl', $hostTemplate->getNoteUrl() === '' ? null : $hostTemplate->getNoteUrl(), \PDO::PARAM_STR ); $statement->bindValue( ':note', $hostTemplate->getNote() === '' ? null : $hostTemplate->getNote(), \PDO::PARAM_STR ); $statement->bindValue( ':actionUrl', $hostTemplate->getActionUrl() === '' ? null : $hostTemplate->getActionUrl(), \PDO::PARAM_STR ); $statement->bindValue(':iconId', $hostTemplate->getIconId(), \PDO::PARAM_INT); $statement->bindValue( ':iconAlternative', $hostTemplate->getIconAlternative() === '' ? null : $hostTemplate->getIconAlternative(), \PDO::PARAM_STR ); $statement->execute(); } private function bindHostTemplateValues(\PDOStatement $statement, NewHostTemplate $hostTemplate): void { $statement->bindValue( ':name', $hostTemplate->getName(), \PDO::PARAM_STR ); $statement->bindValue( ':alias', $hostTemplate->getAlias(), \PDO::PARAM_STR ); $statement->bindValue( ':snmpVersion', $hostTemplate->getSnmpVersion()?->value, \PDO::PARAM_STR ); $statement->bindValue( ':snmpCommunity', $hostTemplate->getSnmpCommunity() === '' ? null : $hostTemplate->getSnmpCommunity(), \PDO::PARAM_STR ); $statement->bindValue( ':timezoneId', $hostTemplate->getTimezoneId(), \PDO::PARAM_INT ); $statement->bindValue( ':checkCommandId', $hostTemplate->getCheckCommandId(), \PDO::PARAM_INT ); $checkCommandArguments = null; if ($hostTemplate->getCheckCommandArgs() !== []) { $checkCommandArguments = '!' . implode( '!', str_replace(["\n", "\t", "\r"], ['#BR#', '#T#', '#R#'], $hostTemplate->getCheckCommandArgs()) ); } $statement->bindValue( ':checkCommandArgs', $checkCommandArguments, \PDO::PARAM_STR ); $statement->bindValue( ':checkTimeperiodId', $hostTemplate->getCheckTimeperiodId(), \PDO::PARAM_INT ); $statement->bindValue( ':maxCheckAttempts', $hostTemplate->getMaxCheckAttempts(), \PDO::PARAM_INT ); $statement->bindValue( ':normalCheckInterval', $hostTemplate->getNormalCheckInterval(), \PDO::PARAM_INT ); $statement->bindValue( ':retryCheckInterval', $hostTemplate->getRetryCheckInterval(), \PDO::PARAM_INT ); $statement->bindValue( ':activeCheckEnabled', YesNoDefaultConverter::toString($hostTemplate->getActiveCheckEnabled()), \PDO::PARAM_STR ); $statement->bindValue( ':passiveCheckEnabled', YesNoDefaultConverter::toString($hostTemplate->getPassiveCheckEnabled()), \PDO::PARAM_STR ); $statement->bindValue( ':notificationEnabled', YesNoDefaultConverter::toString($hostTemplate->getNotificationEnabled()), \PDO::PARAM_STR ); $statement->bindValue( ':notificationOptions', $hostTemplate->getNotificationOptions() === [] ? null : HostEventConverter::toString($hostTemplate->getNotificationOptions()), \PDO::PARAM_STR ); $statement->bindValue( ':notificationInterval', $hostTemplate->getNotificationInterval(), \PDO::PARAM_INT ); $statement->bindValue( ':notificationTimeperiodId', $hostTemplate->getNotificationTimeperiodId(), \PDO::PARAM_INT ); $statement->bindValue( ':addInheritedContactGroup', $hostTemplate->addInheritedContactGroup() ? 1 : 0, \PDO::PARAM_INT ); $statement->bindValue( ':addInheritedContact', $hostTemplate->addInheritedContact() ? 1 : 0, \PDO::PARAM_INT ); $statement->bindValue( ':firstNotificationDelay', $hostTemplate->getFirstNotificationDelay(), \PDO::PARAM_INT ); $statement->bindValue( ':recoveryNotificationDelay', $hostTemplate->getRecoveryNotificationDelay(), \PDO::PARAM_INT ); $statement->bindValue( ':acknowledgementTimeout', $hostTemplate->getAcknowledgementTimeout(), \PDO::PARAM_INT ); $statement->bindValue( ':freshnessChecked', YesNoDefaultConverter::toString($hostTemplate->getFreshnessChecked()), \PDO::PARAM_STR ); $statement->bindValue( ':freshnessThreshold', $hostTemplate->getFreshnessThreshold(), \PDO::PARAM_INT ); $statement->bindValue( ':flapDetectionEnabled', YesNoDefaultConverter::toString($hostTemplate->getFlapDetectionEnabled()), \PDO::PARAM_STR ); $statement->bindValue( ':lowFlapThreshold', $hostTemplate->getLowFlapThreshold(), \PDO::PARAM_INT ); $statement->bindValue( ':highFlapThreshold', $hostTemplate->getHighFlapThreshold(), \PDO::PARAM_INT ); $statement->bindValue( ':eventHandlerEnabled', YesNoDefaultConverter::toString($hostTemplate->getEventHandlerEnabled()), \PDO::PARAM_STR ); $statement->bindValue( ':eventHandlerCommandId', $hostTemplate->getEventHandlerCommandId(), \PDO::PARAM_INT ); $eventHandlerCommandArguments = null; if ($hostTemplate->getEventHandlerCommandArgs() !== []) { $eventHandlerCommandArguments = '!' . implode( '!', str_replace(["\n", "\t", "\r"], ['#BR#', '#T#', '#R#'], $hostTemplate->getEventHandlerCommandArgs()) ); } $statement->bindValue( ':eventHandlerCommandArgs', $eventHandlerCommandArguments, \PDO::PARAM_STR ); $statement->bindValue( ':comment', $hostTemplate->getComment() === '' ? null : $hostTemplate->getComment(), \PDO::PARAM_STR ); $statement->bindValue( ':isActivated', (new BoolToEnumNormalizer())->normalize(true), \PDO::PARAM_STR ); $statement->bindValue( ':isLocked', $hostTemplate->isLocked() ? 1 : 0, \PDO::PARAM_INT ); $statement->bindValue( ':hostType', HostType::Template->value, \PDO::PARAM_STR ); } }
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/Infrastructure/Repository/DbWriteHostTemplateActionLogRepository.php
centreon/src/Core/HostTemplate/Infrastructure/Repository/DbWriteHostTemplateActionLogRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Infrastructure\Repository; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Log\LoggerTrait; use Centreon\Domain\Repository\RepositoryException; use Centreon\Infrastructure\DatabaseConnection; use Core\ActionLog\Application\Repository\WriteActionLogRepositoryInterface; use Core\ActionLog\Domain\Model\ActionLog; use Core\Common\Application\Converter\YesNoDefaultConverter; use Core\Common\Domain\YesNoDefault; use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB; use Core\Host\Application\Converter\HostEventConverter; use Core\Host\Domain\Model\HostEvent; use Core\Host\Domain\Model\SnmpVersion; use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface; use Core\HostTemplate\Application\Repository\WriteHostTemplateRepositoryInterface; use Core\HostTemplate\Domain\Model\HostTemplate; use Core\HostTemplate\Domain\Model\NewHostTemplate; class DbWriteHostTemplateActionLogRepository extends AbstractRepositoryRDB implements WriteHostTemplateRepositoryInterface { use LoggerTrait; /** * @param WriteHostTemplateRepositoryInterface $writeHostTemplateRepository * @param ContactInterface $contact * @param ReadHostTemplateRepositoryInterface $readHostTemplateRepository * @param WriteActionLogRepositoryInterface $writeActionLogRepository * @param DatabaseConnection $db */ public function __construct( private readonly WriteHostTemplateRepositoryInterface $writeHostTemplateRepository, private readonly ContactInterface $contact, private readonly ReadHostTemplateRepositoryInterface $readHostTemplateRepository, private readonly WriteActionLogRepositoryInterface $writeActionLogRepository, DatabaseConnection $db, ) { $this->db = $db; } /** * @inheritDoc */ public function delete(int $hostTemplateId): void { try { $hostTemplate = $this->readHostTemplateRepository->findById($hostTemplateId); if ($hostTemplate === null) { throw new RepositoryException('Cannot find host template to delete'); } $this->writeHostTemplateRepository->delete($hostTemplateId); $actionLog = new ActionLog( ActionLog::OBJECT_TYPE_HOST_TEMPLATE, $hostTemplateId, $hostTemplate->getName(), ActionLog::ACTION_TYPE_DELETE, $this->contact->getId() ); $this->writeActionLogRepository->addAction($actionLog); } catch (\Throwable $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); throw $ex; } } /** * @inheritDoc */ public function add(NewHostTemplate $hostTemplate): int { try { $hostTemplateId = $this->writeHostTemplateRepository->add($hostTemplate); if ($hostTemplateId === 0) { throw new RepositoryException('Host template ID cannot be 0'); } $actionLog = new ActionLog( ActionLog::OBJECT_TYPE_HOST_TEMPLATE, $hostTemplateId, $hostTemplate->getName(), ActionLog::ACTION_TYPE_ADD, $this->contact->getId() ); $actionLogId = $this->writeActionLogRepository->addAction($actionLog); $actionLog->setId($actionLogId); $details = $this->getHostTemplatePropertiesAsArray($hostTemplate); $this->writeActionLogRepository->addActionDetails($actionLog, $details); return $hostTemplateId; } catch (\Throwable $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); throw $ex; } } /** * @inheritDoc */ public function update(HostTemplate $hostTemplate): void { try { $currentHostTemplate = $this->readHostTemplateRepository->findById($hostTemplate->getId()); if ($currentHostTemplate === null) { throw new RepositoryException('Cannot find host template to update'); } $currentHostTemplateDetails = $this->getHostTemplatePropertiesAsArray($currentHostTemplate); $updatedHostTemplateDetails = $this->getHostTemplatePropertiesAsArray($hostTemplate); $diff = array_diff_assoc($updatedHostTemplateDetails, $currentHostTemplateDetails); // FIXME: $diff variable never used & do we want to always createActionLog even if nothing has changed ? $this->writeHostTemplateRepository->update($hostTemplate); $actionLog = new ActionLog( ActionLog::OBJECT_TYPE_HOST_TEMPLATE, $hostTemplate->getId(), $hostTemplate->getName(), ActionLog::ACTION_TYPE_CHANGE, $this->contact->getId() ); $actionLogId = $this->writeActionLogRepository->addAction($actionLog); if ($actionLogId === 0) { throw new RepositoryException('Action log ID cannot be 0'); } $actionLog->setId($actionLogId); $this->writeActionLogRepository->addActionDetails($actionLog, $updatedHostTemplateDetails); } catch (\Throwable $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); throw $ex; } } /** * @inheritDoc */ public function addParent(int $childId, int $parentId, int $order): void { $this->writeHostTemplateRepository->addParent($childId, $parentId, $order); } /** * @inheritDoc */ public function deleteParents(int $childId): void { $this->writeHostTemplateRepository->deleteParents($childId); } /** * @param NewHostTemplate $hostTemplate * * @return array<string,int|bool|string> */ private function getHostTemplatePropertiesAsArray(NewHostTemplate $hostTemplate): array { $hostTemplatePropertiesArray = []; $hostTemplateReflection = new \ReflectionClass($hostTemplate); foreach ($hostTemplateReflection->getProperties() as $property) { $value = $property->getValue($hostTemplate); if ($value === null) { $value = ''; } if ($value instanceof YesNoDefault) { $value = YesNoDefaultConverter::toString($value); } if ($value instanceof SnmpVersion) { $value = $value->value; } if (is_array($value)) { if ($value === []) { $value = ''; } elseif (is_string($value[0])) { $value = '!' . implode('!', str_replace(["\n", "\t", "\r"], ['#BR#', '#T#', '#R#'], $value)); } elseif ($value[0] instanceof HostEvent) { $value = HostEventConverter::toString($value); } } $hostTemplatePropertiesArray[$property->getName()] = $value; } /** @var array<string,int|bool|string> $hostTemplatePropertiesArray */ return $hostTemplatePropertiesArray; } }
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/Infrastructure/API/PartialUpdateHostTemplate/PartialUpdateHostTemplateController.php
centreon/src/Core/HostTemplate/Infrastructure/API/PartialUpdateHostTemplate/PartialUpdateHostTemplateController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Infrastructure\API\PartialUpdateHostTemplate; use Centreon\Application\Controller\AbstractController; use Centreon\Domain\Log\LoggerTrait; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\InvalidArgumentResponse; use Core\HostTemplate\Application\Exception\HostTemplateException; use Core\HostTemplate\Application\UseCase\PartialUpdateHostTemplate\PartialUpdateHostTemplate; use Core\HostTemplate\Application\UseCase\PartialUpdateHostTemplate\PartialUpdateHostTemplateRequest; use Core\Infrastructure\Common\Api\DefaultPresenter; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Exception\AccessDeniedException; final class PartialUpdateHostTemplateController extends AbstractController { use LoggerTrait; /** * @param Request $request * @param PartialUpdateHostTemplate $useCase * @param DefaultPresenter $presenter * @param bool $isCloudPlatform * @param int $hostTemplateId * * @throws AccessDeniedException * * @return Response */ public function __invoke( Request $request, PartialUpdateHostTemplate $useCase, DefaultPresenter $presenter, bool $isCloudPlatform, int $hostTemplateId, ): Response { $this->denyAccessUnlessGrantedForApiConfiguration(); try { $dto = $isCloudPlatform ? $this->setDtoForSaas($request) : $this->setDtoForOnPrem($request); $useCase($dto, $presenter, $hostTemplateId); } catch (\InvalidArgumentException $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); $presenter->setResponseStatus(new InvalidArgumentResponse($ex)); } catch (\Throwable $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); $presenter->setResponseStatus(new ErrorResponse(HostTemplateException::partialUpdateHostTemplate())); } return $presenter->show(); } private function setDtoForOnPrem(Request $request): PartialUpdateHostTemplateRequest { /** * @var array{ * macros?: array<array{id?:int|null,name:string,value:string|null,is_password:bool,description:string|null}>, * categories?: int[], * templates?: int[], * name?: string, * alias?: string, * snmp_version?: null|string, * snmp_community?: null|string, * timezone_id?: null|int, * severity_id?: null|int, * check_command_id?: null|int, * check_command_args?: string[], * check_timeperiod_id?: null|int, * max_check_attempts?: null|int, * normal_check_interval?: null|int, * retry_check_interval?: null|int, * active_check_enabled?: int, * passive_check_enabled?: int, * notification_enabled?: int, * notification_options?: null|int, * notification_interval?: null|int, * notification_timeperiod_id?: null|int, * add_inherited_contact_group?: bool, * add_inherited_contact?: bool, * first_notification_delay?: null|int, * recovery_notification_delay?: null|int, * acknowledgement_timeout?: null|int, * freshness_checked?: int, * freshness_threshold?: null|int, * flap_detection_enabled?: int, * low_flap_threshold?: null|int, * high_flap_threshold?: null|int, * event_handler_enabled?: int, * event_handler_command_id?: null|int, * event_handler_command_args?: string[], * note_url?: null|string, * note?: null|string, * action_url?: null|string, * icon_id?: null|int, * icon_alternative?: null|string, * comment?: string|null * } $data */ $data = $this->validateAndRetrieveDataSent($request, __DIR__ . '/PartialUpdateHostTemplateOnPremSchema.json'); $dto = new PartialUpdateHostTemplateRequest(); if (\array_key_exists('macros', $data)) { $dto->macros = $data['macros']; } if (\array_key_exists('categories', $data)) { $dto->categories = $data['categories']; } if (\array_key_exists('templates', $data)) { $dto->templates = $data['templates']; } if (\array_key_exists('name', $data)) { $dto->name = $data['name']; } if (\array_key_exists('alias', $data)) { $dto->alias = $data['alias']; } if (\array_key_exists('snmp_version', $data)) { $dto->snmpVersion = $data['snmp_version'] ?? ''; } if (\array_key_exists('snmp_community', $data)) { $dto->snmpCommunity = $data['snmp_community'] ?? ''; } if (\array_key_exists('timezone_id', $data)) { $dto->timezoneId = $data['timezone_id']; } if (\array_key_exists('severity_id', $data)) { $dto->severityId = $data['severity_id']; } if (\array_key_exists('check_command_id', $data)) { $dto->checkCommandId = $data['check_command_id']; } if (\array_key_exists('check_command_args', $data)) { $dto->checkCommandArgs = $data['check_command_args']; } if (\array_key_exists('check_timeperiod_id', $data)) { $dto->checkTimeperiodId = $data['check_timeperiod_id']; } if (\array_key_exists('max_check_attempts', $data)) { $dto->maxCheckAttempts = $data['max_check_attempts']; } if (\array_key_exists('normal_check_interval', $data)) { $dto->normalCheckInterval = $data['normal_check_interval']; } if (\array_key_exists('retry_check_interval', $data)) { $dto->retryCheckInterval = $data['retry_check_interval']; } if (\array_key_exists('active_check_enabled', $data)) { $dto->activeCheckEnabled = $data['active_check_enabled']; } if (\array_key_exists('passive_check_enabled', $data)) { $dto->passiveCheckEnabled = $data['passive_check_enabled']; } if (\array_key_exists('notification_enabled', $data)) { $dto->notificationEnabled = $data['notification_enabled']; } if (\array_key_exists('notification_options', $data)) { $dto->notificationOptions = $data['notification_options']; } if (\array_key_exists('notification_interval', $data)) { $dto->notificationInterval = $data['notification_interval']; } if (\array_key_exists('notification_timeperiod_id', $data)) { $dto->notificationTimeperiodId = $data['notification_timeperiod_id']; } if (\array_key_exists('add_inherited_contact_group', $data)) { $dto->addInheritedContactGroup = $data['add_inherited_contact_group']; } if (\array_key_exists('add_inherited_contact', $data)) { $dto->addInheritedContact = $data['add_inherited_contact']; } if (\array_key_exists('first_notification_delay', $data)) { $dto->firstNotificationDelay = $data['first_notification_delay']; } if (\array_key_exists('recovery_notification_delay', $data)) { $dto->recoveryNotificationDelay = $data['recovery_notification_delay']; } if (\array_key_exists('acknowledgement_timeout', $data)) { $dto->acknowledgementTimeout = $data['acknowledgement_timeout']; } if (\array_key_exists('freshness_checked', $data)) { $dto->freshnessChecked = $data['freshness_checked']; } if (\array_key_exists('freshness_threshold', $data)) { $dto->freshnessThreshold = $data['freshness_threshold']; } if (\array_key_exists('flap_detection_enabled', $data)) { $dto->flapDetectionEnabled = $data['flap_detection_enabled']; } if (\array_key_exists('low_flap_threshold', $data)) { $dto->lowFlapThreshold = $data['low_flap_threshold']; } if (\array_key_exists('high_flap_threshold', $data)) { $dto->highFlapThreshold = $data['high_flap_threshold']; } if (\array_key_exists('event_handler_enabled', $data)) { $dto->eventHandlerEnabled = $data['event_handler_enabled']; } if (\array_key_exists('event_handler_command_id', $data)) { $dto->eventHandlerCommandId = $data['event_handler_command_id']; } if (\array_key_exists('event_handler_command_args', $data)) { $dto->eventHandlerCommandArgs = $data['event_handler_command_args']; } if (\array_key_exists('note_url', $data)) { $dto->noteUrl = $data['note_url'] ?? ''; } if (\array_key_exists('note', $data)) { $dto->note = $data['note'] ?? ''; } if (\array_key_exists('action_url', $data)) { $dto->actionUrl = $data['action_url'] ?? ''; } if (\array_key_exists('icon_id', $data)) { $dto->iconId = $data['icon_id']; } if (\array_key_exists('icon_alternative', $data)) { $dto->iconAlternative = $data['icon_alternative'] ?? ''; } if (\array_key_exists('comment', $data)) { $dto->comment = $data['comment'] ?? ''; } return $dto; } /** * @param Request $request * * @throws \Throwable|\InvalidArgumentException * * @return PartialUpdateHostTemplateRequest */ private function setDtoForSaas(Request $request): PartialUpdateHostTemplateRequest { /** * @var array{ * macros?:array<array{id?:int|null,name:string,value:string|null,is_password:bool,description:string|null}>, * categories?: int[], * templates?: int[], * name: string, * alias: string, * snmp_version?: null|string, * snmp_community?: null|string, * max_check_attempts?: null|int, * normal_check_interval?: null|int, * retry_check_interval?: null|int, * timezone_id?: null|int, * severity_id?: null|int, * check_command_id?: null|int, * check_command_args?: string[], * check_timeperiod_id?: null|int, * note_url?: null|string, * note?: null|string, * action_url?: null|string, * icon_id?: null|int * } $data */ $data = $this->validateAndRetrieveDataSent($request, __DIR__ . '/PartialUpdateHostTemplateSaasSchema.json'); $dto = new PartialUpdateHostTemplateRequest(); if (\array_key_exists('macros', $data)) { $dto->macros = $data['macros']; } if (\array_key_exists('categories', $data)) { $dto->categories = $data['categories']; } if (\array_key_exists('templates', $data)) { $dto->templates = $data['templates']; } if (\array_key_exists('name', $data)) { $dto->name = $data['name']; } if (\array_key_exists('alias', $data)) { $dto->alias = $data['alias']; } if (\array_key_exists('snmp_version', $data)) { $dto->snmpVersion = $data['snmp_version'] ?? ''; } if (\array_key_exists('snmp_community', $data)) { $dto->snmpCommunity = $data['snmp_community'] ?? ''; } if (\array_key_exists('max_check_attempts', $data)) { $dto->maxCheckAttempts = $data['max_check_attempts']; } if (\array_key_exists('normal_check_interval', $data)) { $dto->normalCheckInterval = $data['normal_check_interval']; } if (\array_key_exists('retry_check_interval', $data)) { $dto->retryCheckInterval = $data['retry_check_interval']; } if (\array_key_exists('timezone_id', $data)) { $dto->timezoneId = $data['timezone_id']; } if (\array_key_exists('severity_id', $data)) { $dto->severityId = $data['severity_id']; } if (\array_key_exists('check_command_id', $data)) { $dto->checkCommandId = $data['check_command_id']; } if (\array_key_exists('check_command_args', $data)) { $dto->checkCommandArgs = $data['check_command_args']; } if (\array_key_exists('check_timeperiod_id', $data)) { $dto->checkTimeperiodId = $data['check_timeperiod_id']; } if (\array_key_exists('note_url', $data)) { $dto->noteUrl = $data['note_url'] ?? ''; } if (\array_key_exists('note', $data)) { $dto->note = $data['note'] ?? ''; } if (\array_key_exists('action_url', $data)) { $dto->actionUrl = $data['action_url'] ?? ''; } if (\array_key_exists('icon_id', $data)) { $dto->iconId = $data['icon_id']; } 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/Infrastructure/API/AddHostTemplate/AddHostTemplateSaasPresenter.php
centreon/src/Core/HostTemplate/Infrastructure/API/AddHostTemplate/AddHostTemplateSaasPresenter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Infrastructure\API\AddHostTemplate; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\Common\UseCase\CreatedResponse; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\HostTemplate\Application\UseCase\AddHostTemplate\AddHostTemplatePresenterInterface; use Core\HostTemplate\Application\UseCase\AddHostTemplate\AddHostTemplateResponse; use Core\Infrastructure\Common\Presenter\PresenterTrait; class AddHostTemplateSaasPresenter extends AbstractPresenter implements AddHostTemplatePresenterInterface { use PresenterTrait; /** * @inheritDoc */ public function presentResponse(AddHostTemplateResponse|ResponseStatusInterface $response): void { if ($response instanceof ResponseStatusInterface) { $this->setResponseStatus($response); } else { $this->present( new CreatedResponse( $response->id, [ 'id' => $response->id, 'name' => $response->name, 'alias' => $response->alias, 'snmp_version' => $response->snmpVersion, 'timezone_id' => $response->timezoneId, 'severity_id' => $response->severityId, 'check_command_id' => $response->checkCommandId, 'check_command_args' => $response->checkCommandArgs, 'check_timeperiod_id' => $response->checkTimeperiodId, 'max_check_attempts' => $response->maxCheckAttempts, 'normal_check_interval' => $response->normalCheckInterval, 'retry_check_interval' => $response->retryCheckInterval, 'note_url' => $this->emptyStringAsNull($response->noteUrl), 'note' => $this->emptyStringAsNull($response->note), 'action_url' => $this->emptyStringAsNull($response->actionUrl), 'icon_id' => $response->iconId, 'is_locked' => $response->isLocked, 'categories' => $response->categories, 'templates' => $response->templates, 'event_handler_enabled' => $response->eventHandlerEnabled, 'event_handler_command_id' => $response->eventHandlerCommandId, 'macros' => array_map( fn ($macro) => [ 'id' => $macro['id'], 'name' => $macro['name'], 'value' => $macro['isPassword'] ? null : $macro['value'], 'is_password' => $macro['isPassword'], 'description' => $this->emptyStringAsNull($macro['description']), ], $response->macros ), ] ) ); // NOT setting location as required route does not currently exist } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostTemplate/Infrastructure/API/AddHostTemplate/AddHostTemplateOnPremPresenter.php
centreon/src/Core/HostTemplate/Infrastructure/API/AddHostTemplate/AddHostTemplateOnPremPresenter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Infrastructure\API\AddHostTemplate; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\Common\UseCase\CreatedResponse; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\HostTemplate\Application\UseCase\AddHostTemplate\AddHostTemplatePresenterInterface; use Core\HostTemplate\Application\UseCase\AddHostTemplate\AddHostTemplateResponse; use Core\Infrastructure\Common\Presenter\PresenterTrait; class AddHostTemplateOnPremPresenter extends AbstractPresenter implements AddHostTemplatePresenterInterface { use PresenterTrait; /** * @inheritDoc */ public function presentResponse(AddHostTemplateResponse|ResponseStatusInterface $response): void { if ($response instanceof ResponseStatusInterface) { $this->setResponseStatus($response); } else { $this->present( new CreatedResponse( $response->id, [ 'id' => $response->id, 'name' => $response->name, 'alias' => $response->alias, 'snmp_version' => $response->snmpVersion, 'timezone_id' => $response->timezoneId, 'severity_id' => $response->severityId, 'check_command_id' => $response->checkCommandId, 'check_command_args' => $response->checkCommandArgs, 'check_timeperiod_id' => $response->checkTimeperiodId, 'max_check_attempts' => $response->maxCheckAttempts, 'normal_check_interval' => $response->normalCheckInterval, 'retry_check_interval' => $response->retryCheckInterval, 'active_check_enabled' => $response->activeCheckEnabled, 'passive_check_enabled' => $response->passiveCheckEnabled, 'notification_enabled' => $response->notificationEnabled, 'notification_options' => $response->notificationOptions, 'notification_interval' => $response->notificationInterval, 'notification_timeperiod_id' => $response->notificationTimeperiodId, 'add_inherited_contact_group' => $response->addInheritedContactGroup, 'add_inherited_contact' => $response->addInheritedContact, 'first_notification_delay' => $response->firstNotificationDelay, 'recovery_notification_delay' => $response->recoveryNotificationDelay, 'acknowledgement_timeout' => $response->acknowledgementTimeout, 'freshness_checked' => $response->freshnessChecked, 'freshness_threshold' => $response->freshnessThreshold, 'flap_detection_enabled' => $response->flapDetectionEnabled, 'low_flap_threshold' => $response->lowFlapThreshold, 'high_flap_threshold' => $response->highFlapThreshold, 'event_handler_enabled' => $response->eventHandlerEnabled, 'event_handler_command_id' => $response->eventHandlerCommandId, 'event_handler_command_args' => $response->eventHandlerCommandArgs, 'note_url' => $this->emptyStringAsNull($response->noteUrl), 'note' => $this->emptyStringAsNull($response->note), 'action_url' => $this->emptyStringAsNull($response->actionUrl), 'icon_id' => $response->iconId, 'icon_alternative' => $this->emptyStringAsNull($response->iconAlternative), 'comment' => $this->emptyStringAsNull($response->comment), 'is_locked' => $response->isLocked, 'categories' => $response->categories, 'templates' => $response->templates, 'macros' => array_map( fn ($macro) => [ 'id' => $macro['id'], 'name' => $macro['name'], 'value' => $macro['isPassword'] ? null : $macro['value'], 'is_password' => $macro['isPassword'], 'description' => $this->emptyStringAsNull($macro['description']), ], $response->macros ), ] ) ); // NOT setting location as required route does not currently exist } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostTemplate/Infrastructure/API/AddHostTemplate/AddHostTemplateController.php
centreon/src/Core/HostTemplate/Infrastructure/API/AddHostTemplate/AddHostTemplateController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Infrastructure\API\AddHostTemplate; use Centreon\Application\Controller\AbstractController; use Centreon\Domain\Log\LoggerTrait; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\InvalidArgumentResponse; use Core\Common\Application\Converter\YesNoDefaultConverter; use Core\HostTemplate\Application\Exception\HostTemplateException; use Core\HostTemplate\Application\UseCase\AddHostTemplate\AddHostTemplate; use Core\HostTemplate\Application\UseCase\AddHostTemplate\AddHostTemplateRequest; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Exception\AccessDeniedException; final class AddHostTemplateController extends AbstractController { use LoggerTrait; /** * @param Request $request * @param AddHostTemplate $useCase * @param AddHostTemplateSaasPresenter $saasPresenter * @param AddHostTemplateOnPremPresenter $onPremPresenter * @param bool $isCloudPlatform * * @throws AccessDeniedException * * @return Response */ public function __invoke( Request $request, AddHostTemplate $useCase, AddHostTemplateSaasPresenter $saasPresenter, AddHostTemplateOnPremPresenter $onPremPresenter, bool $isCloudPlatform, ): Response { $this->denyAccessUnlessGrantedForApiConfiguration(); if ($isCloudPlatform) { return $this->executeUseCaseSaas($useCase, $saasPresenter, $request); } return $this->executeUseCaseOnPrem($useCase, $onPremPresenter, $request); } /** * @param AddHostTemplate $useCase * @param AddHostTemplateOnPremPresenter $presenter * @param Request $request * * @return Response */ private function executeUseCaseOnPrem( AddHostTemplate $useCase, AddHostTemplateOnPremPresenter $presenter, Request $request, ): Response { try { /** * @var array{ * name: string, * alias: string, * snmp_version?: string, * snmp_community?: string, * timezone_id?: null|int, * severity_id?: null|int, * check_command_id?: null|int, * check_command_args?: string[], * check_timeperiod_id?: null|int, * max_check_attempts?: null|int, * normal_check_interval?: null|int, * retry_check_interval?: null|int, * active_check_enabled?: int, * passive_check_enabled?: int, * notification_enabled?: int, * notification_options?: null|int, * notification_interval?: null|int, * notification_timeperiod_id?: null|int, * add_inherited_contact_group?: bool, * add_inherited_contact?: bool, * first_notification_delay?: null|int, * recovery_notification_delay?: null|int, * acknowledgement_timeout?: null|int, * freshness_checked?: int, * freshness_threshold?: null|int, * flap_detection_enabled?: int, * low_flap_threshold?: null|int, * high_flap_threshold?: null|int, * event_handler_enabled?: int, * event_handler_command_id?: null|int, * event_handler_command_args?: string[], * note_url?: string, * note?: string, * action_url?: string, * icon_id?: null|int, * icon_alternative?: string, * comment?: string, * categories?: int[], * templates?: int[], * macros?: array<array{id?: int|null,name:string,value:null|string,is_password:bool,description:null|string}> * } $data */ $data = $this->validateAndRetrieveDataSent($request, __DIR__ . '/AddHostTemplateOnPremSchema.json'); $dto = new AddHostTemplateRequest(); $dto->name = $data['name']; $dto->alias = $data['alias']; $dto->snmpVersion = $data['snmp_version'] ?? ''; $dto->snmpCommunity = $data['snmp_community'] ?? ''; $dto->timezoneId = $data['timezone_id'] ?? null; $dto->severityId = $data['severity_id'] ?? null; $dto->checkCommandId = $data['check_command_id'] ?? null; $dto->checkCommandArgs = $data['check_command_args'] ?? []; $dto->checkTimeperiodId = $data['check_timeperiod_id'] ?? null; $dto->maxCheckAttempts = $data['max_check_attempts'] ?? null; $dto->normalCheckInterval = $data['normal_check_interval'] ?? null; $dto->retryCheckInterval = $data['retry_check_interval'] ?? null; $dto->activeCheckEnabled = $data['active_check_enabled'] ?? 2; $dto->passiveCheckEnabled = $data['passive_check_enabled'] ?? 2; $dto->notificationEnabled = $data['notification_enabled'] ?? 2; $dto->notificationOptions = $data['notification_options'] ?? null; $dto->notificationInterval = $data['notification_interval'] ?? null; $dto->notificationTimeperiodId = $data['notification_timeperiod_id'] ?? null; $dto->addInheritedContactGroup = $data['add_inherited_contact_group'] ?? false; $dto->addInheritedContact = $data['add_inherited_contact'] ?? false; $dto->firstNotificationDelay = $data['first_notification_delay'] ?? null; $dto->recoveryNotificationDelay = $data['recovery_notification_delay'] ?? null; $dto->acknowledgementTimeout = $data['acknowledgement_timeout'] ?? null; $dto->freshnessChecked = $data['freshness_checked'] ?? 2; $dto->freshnessThreshold = $data['freshness_threshold'] ?? null; $dto->flapDetectionEnabled = $data['flap_detection_enabled'] ?? 2; $dto->lowFlapThreshold = $data['low_flap_threshold'] ?? null; $dto->highFlapThreshold = $data['high_flap_threshold'] ?? null; $dto->eventHandlerEnabled = YesNoDefaultConverter::fromScalar($data['event_handler_enabled'] ?? 2); $dto->eventHandlerCommandId = $data['event_handler_command_id'] ?? null; $dto->eventHandlerCommandArgs = $data['event_handler_command_args'] ?? []; $dto->noteUrl = $data['note_url'] ?? ''; $dto->note = $data['note'] ?? ''; $dto->actionUrl = $data['action_url'] ?? ''; $dto->iconId = $data['icon_id'] ?? null; $dto->iconAlternative = $data['icon_alternative'] ?? ''; $dto->comment = $data['comment'] ?? ''; $dto->categories = $data['categories'] ?? []; $dto->templates = $data['templates'] ?? []; $dto->macros = $data['macros'] ?? []; $useCase($dto, $presenter); } catch (\InvalidArgumentException $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); $presenter->setResponseStatus(new InvalidArgumentResponse($ex)); } catch (\Throwable $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); $presenter->setResponseStatus(new ErrorResponse(HostTemplateException::addHostTemplate())); } return $presenter->show(); } /** * @param AddHostTemplate $useCase * @param AddHostTemplateSaasPresenter $presenter * @param Request $request * * @return Response */ private function executeUseCaseSaas( AddHostTemplate $useCase, AddHostTemplateSaasPresenter $presenter, Request $request, ): Response { try { /** * @var array{ * name: string, * alias: string, * snmp_version?: string, * snmp_community?: string, * timezone_id?: null|int, * severity_id?: null|int, * check_command_id?: null|int, * check_command_args?: string[], * check_timeperiod_id?: null|int, * max_check_attempts?: null|int, * normal_check_interval?: null|int, * retry_check_interval?: null|int, * note_url?: string, * note?: string, * action_url?: string, * icon_id?: null|int, * categories?: int[], * templates?: int[], * macros?: array<array{id?: int|null,name:string,value:null|string,is_password:bool,description:null|string}>, * event_handler_enabled?: int, * event_handler_command_id?: null|int * } $data */ $data = $this->validateAndRetrieveDataSent($request, __DIR__ . '/AddHostTemplateSaasSchema.json'); $dto = new AddHostTemplateRequest(); $dto->name = $data['name']; $dto->alias = $data['alias']; $dto->snmpVersion = $data['snmp_version'] ?? ''; $dto->snmpCommunity = $data['snmp_community'] ?? ''; $dto->maxCheckAttempts = $data['max_check_attempts'] ?? null; $dto->normalCheckInterval = $data['normal_check_interval'] ?? null; $dto->retryCheckInterval = $data['retry_check_interval'] ?? null; $dto->timezoneId = $data['timezone_id'] ?? null; $dto->severityId = $data['severity_id'] ?? null; $dto->checkCommandId = $data['check_command_id'] ?? null; $dto->checkCommandArgs = $data['check_command_args'] ?? []; $dto->checkTimeperiodId = $data['check_timeperiod_id'] ?? null; $dto->noteUrl = $data['note_url'] ?? ''; $dto->note = $data['note'] ?? ''; $dto->actionUrl = $data['action_url'] ?? ''; $dto->categories = $data['categories'] ?? []; $dto->templates = $data['templates'] ?? []; $dto->macros = $data['macros'] ?? []; $dto->iconId = $data['icon_id'] ?? null; $dto->eventHandlerEnabled = YesNoDefaultConverter::fromScalar($data['event_handler_enabled'] ?? 2); $dto->eventHandlerCommandId = $data['event_handler_command_id'] ?? null; $useCase($dto, $presenter); } catch (\InvalidArgumentException $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); $presenter->setResponseStatus(new InvalidArgumentResponse($ex)); } catch (\Throwable $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); $presenter->setResponseStatus(new ErrorResponse(HostTemplateException::addHostTemplate())); } return $presenter->show(); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostTemplate/Infrastructure/API/DeleteHostTemplate/DeleteHostTemplateController.php
centreon/src/Core/HostTemplate/Infrastructure/API/DeleteHostTemplate/DeleteHostTemplateController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Infrastructure\API\DeleteHostTemplate; use Centreon\Application\Controller\AbstractController; use Core\HostTemplate\Application\UseCase\DeleteHostTemplate\DeleteHostTemplate; use Core\Infrastructure\Common\Api\DefaultPresenter; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Exception\AccessDeniedException; final class DeleteHostTemplateController extends AbstractController { /** * @param int $hostTemplateId * @param DeleteHostTemplate $useCase * @param DefaultPresenter $presenter * * @throws AccessDeniedException * * @return Response */ public function __invoke( int $hostTemplateId, DeleteHostTemplate $useCase, DefaultPresenter $presenter, ): Response { $this->denyAccessUnlessGrantedForApiConfiguration(); $useCase($hostTemplateId, $presenter); return $presenter->show(); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostTemplate/Infrastructure/API/FindHostTemplates/FindHostTemplatesOnPremPresenter.php
centreon/src/Core/HostTemplate/Infrastructure/API/FindHostTemplates/FindHostTemplatesOnPremPresenter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Infrastructure\API\FindHostTemplates; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\HostTemplate\Application\UseCase\FindHostTemplates\FindHostTemplatesPresenterInterface; use Core\HostTemplate\Application\UseCase\FindHostTemplates\FindHostTemplatesResponse; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\Infrastructure\Common\Presenter\PresenterTrait; class FindHostTemplatesOnPremPresenter extends AbstractPresenter implements FindHostTemplatesPresenterInterface { use PresenterTrait; public function __construct( private readonly RequestParametersInterface $requestParameters, protected PresenterFormatterInterface $presenterFormatter, ) { parent::__construct($presenterFormatter); } /** * @inheritDoc */ public function presentResponse(FindHostTemplatesResponse|ResponseStatusInterface $response): void { if ($response instanceof ResponseStatusInterface) { $this->setResponseStatus($response); } else { $result = []; foreach ($response->hostTemplates as $hostTemplate) { $result[] = [ 'id' => $hostTemplate['id'], 'name' => $hostTemplate['name'], 'alias' => $hostTemplate['alias'], 'snmp_version' => $hostTemplate['snmpVersion'], 'timezone_id' => $hostTemplate['timezoneId'], 'severity_id' => $hostTemplate['severityId'], 'check_command_id' => $hostTemplate['checkCommandId'], 'check_command_args' => $hostTemplate['checkCommandArgs'], 'check_timeperiod_id' => $hostTemplate['checkTimeperiodId'], 'max_check_attempts' => $hostTemplate['maxCheckAttempts'], 'normal_check_interval' => $hostTemplate['normalCheckInterval'], 'retry_check_interval' => $hostTemplate['retryCheckInterval'], 'active_check_enabled' => $hostTemplate['activeCheckEnabled'], 'passive_check_enabled' => $hostTemplate['passiveCheckEnabled'], 'notification_enabled' => $hostTemplate['notificationEnabled'], 'notification_options' => $hostTemplate['notificationOptions'], 'notification_interval' => $hostTemplate['notificationInterval'], 'notification_timeperiod_id' => $hostTemplate['notificationTimeperiodId'], 'add_inherited_contact_group' => $hostTemplate['addInheritedContactGroup'], 'add_inherited_contact' => $hostTemplate['addInheritedContact'], 'first_notification_delay' => $hostTemplate['firstNotificationDelay'], 'recovery_notification_delay' => $hostTemplate['recoveryNotificationDelay'], 'acknowledgement_timeout' => $hostTemplate['acknowledgementTimeout'], 'freshness_checked' => $hostTemplate['freshnessChecked'], 'freshness_threshold' => $hostTemplate['freshnessThreshold'], 'flap_detection_enabled' => $hostTemplate['flapDetectionEnabled'], 'low_flap_threshold' => $hostTemplate['lowFlapThreshold'], 'high_flap_threshold' => $hostTemplate['highFlapThreshold'], 'event_handler_enabled' => $hostTemplate['eventHandlerEnabled'], 'event_handler_command_id' => $hostTemplate['eventHandlerCommandId'], 'event_handler_command_args' => $hostTemplate['eventHandlerCommandArgs'], 'note_url' => $this->emptyStringAsNull($hostTemplate['noteUrl']), 'note' => $this->emptyStringAsNull($hostTemplate['note']), 'action_url' => $this->emptyStringAsNull($hostTemplate['actionUrl']), 'icon_id' => $hostTemplate['iconId'], 'icon_alternative' => $this->emptyStringAsNull($hostTemplate['iconAlternative']), 'comment' => $this->emptyStringAsNull($hostTemplate['comment']), 'is_locked' => $hostTemplate['isLocked'], ]; } $this->present([ 'result' => $result, 'meta' => $this->requestParameters->toArray(), ]); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostTemplate/Infrastructure/API/FindHostTemplates/FindHostTemplatesSaasPresenter.php
centreon/src/Core/HostTemplate/Infrastructure/API/FindHostTemplates/FindHostTemplatesSaasPresenter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Infrastructure\API\FindHostTemplates; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\HostTemplate\Application\UseCase\FindHostTemplates\FindHostTemplatesPresenterInterface; use Core\HostTemplate\Application\UseCase\FindHostTemplates\FindHostTemplatesResponse; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\Infrastructure\Common\Presenter\PresenterTrait; class FindHostTemplatesSaasPresenter extends AbstractPresenter implements FindHostTemplatesPresenterInterface { use PresenterTrait; public function __construct( private readonly RequestParametersInterface $requestParameters, protected PresenterFormatterInterface $presenterFormatter, ) { parent::__construct($presenterFormatter); } /** * @inheritDoc */ public function presentResponse(FindHostTemplatesResponse|ResponseStatusInterface $response): void { if ($response instanceof ResponseStatusInterface) { $this->setResponseStatus($response); } else { $result = []; foreach ($response->hostTemplates as $hostTemplate) { $result[] = [ 'id' => $hostTemplate['id'], 'name' => $hostTemplate['name'], 'alias' => $hostTemplate['alias'], 'snmp_version' => $hostTemplate['snmpVersion'], 'max_check_attempts' => $hostTemplate['maxCheckAttempts'], 'normal_check_interval' => $hostTemplate['normalCheckInterval'], 'retry_check_interval' => $hostTemplate['retryCheckInterval'], 'timezone_id' => $hostTemplate['timezoneId'], 'severity_id' => $hostTemplate['severityId'], 'check_timeperiod_id' => $hostTemplate['checkTimeperiodId'], 'note_url' => $this->emptyStringAsNull($hostTemplate['noteUrl']), 'note' => $this->emptyStringAsNull($hostTemplate['note']), 'action_url' => $this->emptyStringAsNull($hostTemplate['actionUrl']), 'icon_id' => $hostTemplate['iconId'], 'is_locked' => $hostTemplate['isLocked'], ]; } $this->present([ 'result' => $result, 'meta' => $this->requestParameters->toArray(), ]); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostTemplate/Infrastructure/API/FindHostTemplates/FindHostTemplatesController.php
centreon/src/Core/HostTemplate/Infrastructure/API/FindHostTemplates/FindHostTemplatesController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Infrastructure\API\FindHostTemplates; use Centreon\Application\Controller\AbstractController; use Core\HostTemplate\Application\UseCase\FindHostTemplates\FindHostTemplates; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Exception\AccessDeniedException; final class FindHostTemplatesController extends AbstractController { /** * @param FindHostTemplates $useCase * @param FindHostTemplatesSaasPresenter $saasPresenter * @param FindHostTemplatesOnPremPresenter $onPremPresenter * @param bool $isCloudPlatform * * @throws AccessDeniedException * * @return Response */ public function __invoke( FindHostTemplates $useCase, FindHostTemplatesSaasPresenter $saasPresenter, FindHostTemplatesOnPremPresenter $onPremPresenter, bool $isCloudPlatform, ): Response { $this->denyAccessUnlessGrantedForApiConfiguration(); $presenter = $isCloudPlatform ? $saasPresenter : $onPremPresenter; $useCase($presenter); return $presenter->show(); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/RealTime/UseCase/FindMetaService/FindMetaService.php
centreon/src/Core/Application/RealTime/UseCase/FindMetaService/FindMetaService.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\RealTime\UseCase\FindMetaService; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Log\LoggerTrait; use Core\Application\Common\UseCase\NotFoundResponse; use Core\Application\Configuration\MetaService\Repository\ReadMetaServiceRepositoryInterface as ReadMetaServiceConfigurationRepositoryInterface; use Core\Application\RealTime\Repository\ReadAcknowledgementRepositoryInterface; use Core\Application\RealTime\Repository\ReadDowntimeRepositoryInterface; use Core\Application\RealTime\Repository\ReadMetaServiceRepositoryInterface; use Core\Domain\Configuration\Model\MetaService as MetaServiceConfiguration; use Core\Domain\RealTime\Model\Acknowledgement; use Core\Domain\RealTime\Model\Downtime; use Core\Domain\RealTime\Model\MetaService; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\Security\AccessGroup\Domain\Model\AccessGroup; final class FindMetaService { use LoggerTrait; /** * @param ReadMetaServiceRepositoryInterface $repository * @param ReadMetaServiceConfigurationRepositoryInterface $configurationRepository * @param ContactInterface $contact * @param ReadAccessGroupRepositoryInterface $accessGroupRepository * @param ReadDowntimeRepositoryInterface $downtimeRepository * @param ReadAcknowledgementRepositoryInterface $acknowledgementRepository */ public function __construct( private ReadMetaServiceRepositoryInterface $repository, private ReadMetaServiceConfigurationRepositoryInterface $configurationRepository, private ContactInterface $contact, private ReadAccessGroupRepositoryInterface $accessGroupRepository, private ReadDowntimeRepositoryInterface $downtimeRepository, private ReadAcknowledgementRepositoryInterface $acknowledgementRepository, ) { } /** * @param int $metaId * @param FindMetaServicePresenterInterface $presenter */ public function __invoke( int $metaId, FindMetaServicePresenterInterface $presenter, ): void { $this->info( 'Searching details for Meta Service', [ 'id' => $metaId, ] ); if ($this->contact->isAdmin()) { $this->debug('Find MetaService as an admin user'); $metaServiceConfiguration = $this->configurationRepository->findMetaServiceById($metaId); if ($metaServiceConfiguration === null) { $this->handleMetaServiceConfigurationNotFound($metaId, $presenter); return; } $metaService = $this->repository->findMetaServiceById($metaId); if ($metaService === null) { $this->handleMetaServiceNotFound($metaId, $presenter); return; } } else { $this->debug('Find MetaService as an non-admin user'); $accessGroups = $this->accessGroupRepository->findByContact($this->contact); $accessGroupIds = array_map( fn (AccessGroup $accessGroup) => $accessGroup->getId(), $accessGroups ); $metaServiceConfiguration = $this->configurationRepository->findMetaServiceByIdAndAccessGroupIds( $metaId, $accessGroupIds ); if ($metaServiceConfiguration === null) { $this->handleMetaServiceConfigurationNotFound($metaId, $presenter); return; } $metaService = $this->repository->findMetaServiceByIdAndAccessGroupIds( $metaId, $accessGroupIds ); if ($metaService === null) { $this->handleMetaServiceNotFound($metaId, $presenter); return; } } $hostId = $metaService->getHostId(); $serviceId = $metaService->getServiceId(); $acknowledgement = $metaService->isAcknowledged() === true ? $this->acknowledgementRepository->findOnGoingAcknowledgementByHostIdAndServiceId($hostId, $serviceId) : null; $downtimes = $metaService->isInDowntime() === true ? $this->downtimeRepository->findOnGoingDowntimesByHostIdAndServiceId($hostId, $serviceId) : []; $presenter->present( $this->createResponse( $metaService, $metaServiceConfiguration, $downtimes, $acknowledgement, ) ); } /** * @param MetaService $metaService * @param MetaServiceConfiguration $metaServiceConfiguration * @param Downtime[] $downtimes * @param Acknowledgement|null $acknowledgement * * @return FindMetaServiceResponse */ public function createResponse( MetaService $metaService, MetaServiceConfiguration $metaServiceConfiguration, array $downtimes, ?Acknowledgement $acknowledgement, ): FindMetaServiceResponse { $findMetaServiceResponse = new FindMetaServiceResponse( $metaService->getId(), $metaService->getHostId(), $metaService->getServiceId(), $metaService->getName(), $metaService->getMonitoringServerName(), $metaService->getStatus(), $metaServiceConfiguration->getCalculationType(), $downtimes, $acknowledgement ); $findMetaServiceResponse->isFlapping = $metaService->isFlapping(); $findMetaServiceResponse->isAcknowledged = $metaService->isAcknowledged(); $findMetaServiceResponse->isInDowntime = $metaService->isInDowntime(); $findMetaServiceResponse->output = $metaService->getOutput(); $findMetaServiceResponse->performanceData = $metaService->getPerformanceData(); $findMetaServiceResponse->commandLine = $metaService->getCommandLine(); $findMetaServiceResponse->notificationNumber = $metaService->getNotificationNumber(); $findMetaServiceResponse->lastStatusChange = $metaService->getLastStatusChange(); $findMetaServiceResponse->lastNotification = $metaService->getLastNotification(); $findMetaServiceResponse->latency = $metaService->getLatency(); $findMetaServiceResponse->executionTime = $metaService->getExecutionTime(); $findMetaServiceResponse->statusChangePercentage = $metaService->getStatusChangePercentage(); $findMetaServiceResponse->nextCheck = $metaService->getNextCheck(); $findMetaServiceResponse->lastCheck = $metaService->getLastCheck(); $findMetaServiceResponse->hasPassiveChecks = $metaService->hasPassiveChecks(); $findMetaServiceResponse->hasActiveChecks = $metaService->hasActiveChecks(); $findMetaServiceResponse->lastTimeOk = $metaService->getLastTimeOk(); $findMetaServiceResponse->checkAttempts = $metaService->getCheckAttempts(); $findMetaServiceResponse->maxCheckAttempts = $metaService->getMaxCheckAttempts(); $findMetaServiceResponse->hasGraphData = $metaService->hasGraphData(); return $findMetaServiceResponse; } /** * Handle Meta Service Configuration not found. This method will log the error and set the ResponseStatus. * * @param int $metaId * @param FindMetaServicePresenterInterface $presenter */ private function handleMetaServiceConfigurationNotFound( int $metaId, FindMetaServicePresenterInterface $presenter, ): void { $this->error( 'Meta Service configuration not found', [ 'id' => $metaId, 'userId' => $this->contact->getId(), ] ); $presenter->setResponseStatus(new NotFoundResponse('MetaService configuration')); } /** * Handle Meta Service not found. This method will log the error and set the ResponseStatus. * * @param int $metaId * @param FindMetaServicePresenterInterface $presenter */ private function handleMetaServiceNotFound( int $metaId, FindMetaServicePresenterInterface $presenter, ): void { $this->error( 'Meta Service not found', [ 'id' => $metaId, 'userId' => $this->contact->getId(), ] ); $presenter->setResponseStatus(new NotFoundResponse('MetaService')); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/RealTime/UseCase/FindMetaService/FindMetaServiceResponse.php
centreon/src/Core/Application/RealTime/UseCase/FindMetaService/FindMetaServiceResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\RealTime\UseCase\FindMetaService; use Core\Application\RealTime\Common\RealTimeResponseTrait; use Core\Domain\RealTime\Model\Acknowledgement; use Core\Domain\RealTime\Model\Downtime; use Core\Domain\RealTime\Model\ResourceTypes\MetaServiceResourceType; use Core\Domain\RealTime\Model\ServiceStatus; final class FindMetaServiceResponse { use RealTimeResponseTrait; /** @var bool */ public $isFlapping; /** @var bool */ public $isAcknowledged; /** @var bool */ public $isInDowntime; /** @var string|null */ public $output; /** @var string|null */ public $performanceData; /** @var string|null */ public $commandLine; /** @var int|null */ public $notificationNumber; /** @var \DateTime|null */ public $lastStatusChange; /** @var \DateTime|null */ public $lastNotification; /** @var float|null */ public $latency; /** @var float|null */ public $executionTime; /** @var float|null */ public $statusChangePercentage; /** @var \DateTime|null */ public $nextCheck; /** @var \DateTime|null */ public $lastCheck; /** @var bool */ public $hasActiveChecks; /** @var bool */ public $hasPassiveChecks; /** @var \DateTime|null */ public $lastTimeOk; /** @var int|null */ public $checkAttempts; /** @var int|null */ public $maxCheckAttempts; /** @var array<string, mixed> */ public $status; /** @var array<array<string, mixed>> */ public $downtimes; /** @var array<string, mixed> */ public $acknowledgement; /** @var bool */ public $hasGraphData; /** @var string */ public string $type = MetaServiceResourceType::TYPE_NAME; /** * @param int $metaId * @param int $hostId * @param int $serviceId * @param string $name * @param string $monitoringServerName * @param ServiceStatus $status * @param Downtime[] $downtimes * @param Acknowledgement|null $acknowledgement * @param string $calculationType */ public function __construct( public int $metaId, public int $hostId, public int $serviceId, public string $name, public string $monitoringServerName, ServiceStatus $status, public string $calculationType, array $downtimes, ?Acknowledgement $acknowledgement, ) { $this->status = $this->statusToArray($status); $this->downtimes = $this->downtimesToArray($downtimes); $this->acknowledgement = $this->acknowledgementToArray($acknowledgement); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/RealTime/UseCase/FindMetaService/FindMetaServicePresenterInterface.php
centreon/src/Core/Application/RealTime/UseCase/FindMetaService/FindMetaServicePresenterInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\RealTime\UseCase\FindMetaService; use Core\Application\Common\UseCase\PresenterInterface; interface FindMetaServicePresenterInterface extends PresenterInterface { /** * {@inheritDoc} * * @param FindMetaServiceResponse $response */ public function present(mixed $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/Application/RealTime/UseCase/FindService/FindServicePresenterInterface.php
centreon/src/Core/Application/RealTime/UseCase/FindService/FindServicePresenterInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\RealTime\UseCase\FindService; use Core\Application\Common\UseCase\PresenterInterface; interface FindServicePresenterInterface extends PresenterInterface { /** * {@inheritDoc} * * @param FindServiceResponse $data */ public function present(mixed $data): void; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/RealTime/UseCase/FindService/FindService.php
centreon/src/Core/Application/RealTime/UseCase/FindService/FindService.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\RealTime\UseCase\FindService; use Centreon\Domain\Contact\Contact; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Log\LoggerTrait; use Centreon\Domain\Monitoring\Host as LegacyHost; use Centreon\Domain\Monitoring\Interfaces\MonitoringServiceInterface; use Centreon\Domain\Monitoring\Service as LegacyService; use Core\Application\Common\UseCase\NotFoundResponse; use Core\Application\RealTime\Repository\ReadAcknowledgementRepositoryInterface; use Core\Application\RealTime\Repository\ReadDowntimeRepositoryInterface; use Core\Application\RealTime\Repository\ReadHostRepositoryInterface; use Core\Application\RealTime\Repository\ReadServicegroupRepositoryInterface; use Core\Application\RealTime\Repository\ReadServiceRepositoryInterface; use Core\Domain\RealTime\Model\Acknowledgement; use Core\Domain\RealTime\Model\Downtime; use Core\Domain\RealTime\Model\Host; use Core\Domain\RealTime\Model\Service; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\Security\AccessGroup\Domain\Model\AccessGroup; use Core\Severity\RealTime\Application\Repository\ReadSeverityRepositoryInterface; use Core\Severity\RealTime\Domain\Model\Severity; use Core\Tag\RealTime\Application\Repository\ReadTagRepositoryInterface; use Core\Tag\RealTime\Domain\Model\Tag; final class FindService { use LoggerTrait; /** * @param ReadServiceRepositoryInterface $repository * @param ReadHostRepositoryInterface $hostRepository * @param ReadServicegroupRepositoryInterface $servicegroupRepository * @param ContactInterface $contact * @param ReadAccessGroupRepositoryInterface $accessGroupRepository * @param ReadDowntimeRepositoryInterface $downtimeRepository * @param ReadAcknowledgementRepositoryInterface $acknowledgementRepository * @param MonitoringServiceInterface $monitoringService * @param ReadTagRepositoryInterface $tagRepository * @param ReadSeverityRepositoryInterface $severityRepository */ public function __construct( private ReadServiceRepositoryInterface $repository, private ReadHostRepositoryInterface $hostRepository, private ReadServicegroupRepositoryInterface $servicegroupRepository, private ContactInterface $contact, private ReadAccessGroupRepositoryInterface $accessGroupRepository, private ReadDowntimeRepositoryInterface $downtimeRepository, private ReadAcknowledgementRepositoryInterface $acknowledgementRepository, private MonitoringServiceInterface $monitoringService, private ReadTagRepositoryInterface $tagRepository, private ReadSeverityRepositoryInterface $severityRepository, ) { } /** * @param int $hostId * @param int $serviceId * @param FindServicePresenterInterface $presenter */ public function __invoke( int $hostId, int $serviceId, FindServicePresenterInterface $presenter, ): void { $this->info('Searching details for service', ['id' => $serviceId]); if ($this->contact->isAdmin()) { $host = $this->hostRepository->findHostById($hostId); if ($host === null) { $this->handleHostNotFound($hostId, $presenter); return; } $service = $this->repository->findServiceById($hostId, $serviceId); if ($service === null) { $this->handleServiceNotFound($hostId, $serviceId, $presenter); return; } $servicegroups = $this->servicegroupRepository->findAllByHostIdAndServiceId( $hostId, $serviceId ); } else { $accessGroups = $this->accessGroupRepository->findByContact($this->contact); $accessGroupIds = array_map( fn (AccessGroup $accessGroup) => $accessGroup->getId(), $accessGroups ); $host = $this->hostRepository->findHostByIdAndAccessGroupIds($hostId, $accessGroupIds); if ($host === null) { $this->handleHostNotFound($hostId, $presenter); return; } $service = $this->repository->findServiceByIdAndAccessGroupIds($hostId, $serviceId, $accessGroupIds); if ($service === null) { $this->handleServiceNotFound($hostId, $serviceId, $presenter); return; } $servicegroups = $this->servicegroupRepository->findAllByHostIdAndServiceIdAndAccessGroupIds( $hostId, $serviceId, $accessGroupIds ); } $service->setGroups($servicegroups); $serviceCategories = $this->tagRepository->findAllByResourceAndTypeId( $serviceId, $hostId, Tag::SERVICE_CATEGORY_TYPE_ID ); $service->setCategories($serviceCategories); $this->info( 'Fetching severity from the database for service', [ 'hostId' => $hostId, 'serviceId' => $serviceId, 'typeId' => Severity::SERVICE_SEVERITY_TYPE_ID, ] ); $severity = $this->severityRepository->findByResourceAndTypeId( $serviceId, $hostId, Severity::SERVICE_SEVERITY_TYPE_ID ); $service->setSeverity($severity); $acknowledgement = $service->isAcknowledged() === true ? $this->acknowledgementRepository->findOnGoingAcknowledgementByHostIdAndServiceId($hostId, $serviceId) : null; $downtimes = $service->isInDowntime() === true ? $this->downtimeRepository->findOnGoingDowntimesByHostIdAndServiceId($hostId, $serviceId) : []; /** * Obfuscate the passwords in Service commandLine. */ $service->setCommandLine($this->obfuscatePasswordInServiceCommandLine($service)); $presenter->present( $this->createResponse( $service, $downtimes, $acknowledgement, $host ) ); } /** * @param Service $service * @param Downtime[] $downtimes * @param Acknowledgement|null $acknowledgement * @param Host $host * * @return FindServiceResponse */ public function createResponse( Service $service, array $downtimes, ?Acknowledgement $acknowledgement, Host $host, ): FindServiceResponse { $findServiceResponse = new FindServiceResponse( $service->getId(), $service->getHostId(), $service->getName(), $service->getStatus(), $service->getIcon(), $service->getGroups(), $downtimes, $acknowledgement, $host, $service->getCategories(), $service->getSeverity() ); $findServiceResponse->isFlapping = $service->isFlapping(); $findServiceResponse->isAcknowledged = $service->isAcknowledged(); $findServiceResponse->isInDowntime = $service->isInDowntime(); $findServiceResponse->output = $service->getOutput(); $findServiceResponse->performanceData = $service->getPerformanceData(); $findServiceResponse->commandLine = $service->getCommandLine(); $findServiceResponse->notificationNumber = $service->getNotificationNumber(); $findServiceResponse->lastStatusChange = $service->getLastStatusChange(); $findServiceResponse->lastNotification = $service->getLastNotification(); $findServiceResponse->latency = $service->getLatency(); $findServiceResponse->executionTime = $service->getExecutionTime(); $findServiceResponse->statusChangePercentage = $service->getStatusChangePercentage(); $findServiceResponse->nextCheck = $service->getNextCheck(); $findServiceResponse->lastCheck = $service->getLastCheck(); $findServiceResponse->hasPassiveChecks = $service->hasPassiveChecks(); $findServiceResponse->hasActiveChecks = $service->hasActiveChecks(); $findServiceResponse->lastTimeOk = $service->getLastTimeOk(); $findServiceResponse->checkAttempts = $service->getCheckAttempts(); $findServiceResponse->maxCheckAttempts = $service->getMaxCheckAttempts(); $findServiceResponse->hasGraphData = $service->hasGraphData(); return $findServiceResponse; } /** * Handle Host not found. This method will log the error and set the ResponseStatus. * * @param int $hostId * @param FindServicePresenterInterface $presenter */ private function handleHostNotFound(int $hostId, FindServicePresenterInterface $presenter): void { $this->error( 'Host not found', [ 'id' => $hostId, 'userId' => $this->contact->getId(), ] ); $presenter->setResponseStatus(new NotFoundResponse('Host')); } /** * Handle Service not found. This method will log the error and set the ResponseStatus. * * @param int $hostId * @param int $serviceId * @param FindServicePresenterInterface $presenter */ private function handleServiceNotFound(int $hostId, int $serviceId, FindServicePresenterInterface $presenter): void { $this->error( 'Service not found', [ 'id' => $serviceId, 'hostId' => $hostId, 'userId' => $this->contact->getId(), ] ); $presenter->setResponseStatus(new NotFoundResponse('Service')); } /** * Obfuscate passwords in the commandline. * * @param Service $service * * @return string|null */ private function obfuscatePasswordInServiceCommandLine(Service $service): ?string { $obfuscatedCommandLine = null; /** * Check if user can see the commandLine. * If so, then hide potential passwords. */ if ( ($this->contact->isAdmin() || $this->contact->hasRole(Contact::ROLE_DISPLAY_COMMAND)) && $service->getCommandLine() !== null ) { try { $legacyService = (new LegacyService()) ->setHost((new LegacyHost())->setId($service->getHostId())) ->setId($service->getId()) ->setCommandLine($service->getCommandLine()); $this->monitoringService->hidePasswordInServiceCommandLine($legacyService); $obfuscatedCommandLine = $legacyService->getCommandLine(); } catch (\Throwable $ex) { $this->debug( 'Failed to hide password in service command line', [ 'id' => $service->getId(), 'reason' => $ex->getMessage(), ] ); $obfuscatedCommandLine = sprintf( _('Unable to hide passwords in command (Reason: %s)'), $ex->getMessage() ); } } return $obfuscatedCommandLine; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/RealTime/UseCase/FindService/FindServiceResponse.php
centreon/src/Core/Application/RealTime/UseCase/FindService/FindServiceResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\RealTime\UseCase\FindService; use Core\Application\RealTime\Common\RealTimeResponseTrait; use Core\Domain\RealTime\Model\Acknowledgement; use Core\Domain\RealTime\Model\Downtime; use Core\Domain\RealTime\Model\Host; use Core\Domain\RealTime\Model\Icon; use Core\Domain\RealTime\Model\ResourceTypes\ServiceResourceType; use Core\Domain\RealTime\Model\Servicegroup; use Core\Domain\RealTime\Model\ServiceStatus; use Core\Severity\RealTime\Domain\Model\Severity; use Core\Tag\RealTime\Domain\Model\Tag; /** * @phpstan-import-type _severityArray from RealTimeResponseTrait */ final class FindServiceResponse { use RealTimeResponseTrait; /** @var bool */ public $isFlapping; /** @var bool */ public $isAcknowledged; /** @var bool */ public $isInDowntime; /** @var string|null */ public $output; /** @var string|null */ public $performanceData; /** @var string|null */ public $commandLine; /** @var int|null */ public $notificationNumber; /** @var \DateTime|null */ public $lastStatusChange; /** @var \DateTime|null */ public $lastNotification; /** @var float|null */ public $latency; /** @var float|null */ public $executionTime; /** @var float|null */ public $statusChangePercentage; /** @var \DateTime|null */ public $nextCheck; /** @var \DateTime|null */ public $lastCheck; /** @var bool */ public $hasActiveChecks; /** @var bool */ public $hasPassiveChecks; /** @var \DateTime|null */ public $lastTimeOk; /** @var int|null */ public $checkAttempts; /** @var int|null */ public $maxCheckAttempts; /** @var array<string, int|string|null> */ public $icon; /** @var array<array<string, mixed>> */ public $groups; /** @var array<array<string, mixed>> */ public $categories; /** @var array<string, mixed> */ public $status; /** @var array<array<string, mixed>> */ public $downtimes; /** @var array<string, mixed> */ public $acknowledgement; /** @var array<string, mixed> */ public $host; /** @var bool */ public $hasGraphData; /** @var _severityArray|null */ public ?array $severity = null; // @var string public string $type = ServiceResourceType::TYPE_NAME; /** * @param int $serviceId * @param int $hostId * @param string $name * @param ServiceStatus $status * @param Icon|null $icon * @param Servicegroup[] $servicegroups * @param Downtime[] $downtimes * @param Acknowledgement|null $acknowledgement * @param Host $host * @param Tag[] $serviceCategories * @param Severity|null $severity */ public function __construct( public int $serviceId, public int $hostId, public string $name, ServiceStatus $status, ?Icon $icon, array $servicegroups, array $downtimes, ?Acknowledgement $acknowledgement, Host $host, array $serviceCategories, ?Severity $severity, ) { $this->groups = $this->servicegroupsToArray($servicegroups); $this->status = $this->statusToArray($status); $this->icon = $this->iconToArray($icon); $this->downtimes = $this->downtimesToArray($downtimes); $this->acknowledgement = $this->acknowledgementToArray($acknowledgement); $this->host = $this->hostToArray($host); $this->categories = $this->tagsToArray($serviceCategories); $this->severity = $severity === null ? $severity : $this->severityToArray($severity); } /** * Converts an array of Servicegroups model into an array. * * @param Servicegroup[] $servicegroups * * @return array<int, array<string, mixed>> */ private function servicegroupsToArray(array $servicegroups): array { return array_map( fn (Servicegroup $servicegroup) => [ 'id' => $servicegroup->getId(), 'name' => $servicegroup->getName(), ], $servicegroups ); } /** * Converts a Host entity into an array. * * @param Host $host * * @return array<string, mixed> */ private function hostToArray(Host $host): array { return [ 'type' => 'host', 'id' => $host->getId(), 'name' => $host->getName(), 'status' => $this->statusToArray($host->getStatus()), 'monitoring_server_name' => $host->getMonitoringServerName(), ]; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/RealTime/UseCase/FindHost/FindHostResponse.php
centreon/src/Core/Application/RealTime/UseCase/FindHost/FindHostResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\RealTime\UseCase\FindHost; use Core\Application\RealTime\Common\RealTimeResponseTrait; use Core\Domain\RealTime\Model\Acknowledgement; use Core\Domain\RealTime\Model\Downtime; use Core\Domain\RealTime\Model\Hostgroup; use Core\Domain\RealTime\Model\HostStatus; use Core\Domain\RealTime\Model\Icon; use Core\Domain\RealTime\Model\ResourceTypes\HostResourceType; use Core\Severity\RealTime\Domain\Model\Severity; use Core\Tag\RealTime\Domain\Model\Tag; /** * @phpstan-import-type _severityArray from RealTimeResponseTrait */ final class FindHostResponse { use RealTimeResponseTrait; /** @var string|null */ public $timezone; /** @var string|null */ public $alias; /** @var bool */ public $isFlapping; /** @var bool */ public $isAcknowledged; /** @var bool */ public $isInDowntime; /** @var string|null */ public $output; /** @var string|null */ public $performanceData; /** @var string|null */ public $commandLine; /** @var int|null */ public $notificationNumber; /** @var \DateTime|null */ public $lastStatusChange; /** @var \DateTime|null */ public $lastNotification; /** @var float|null */ public $latency; /** @var float|null */ public $executionTime; /** @var float|null */ public $statusChangePercentage; /** @var \DateTime|null */ public $nextCheck; /** @var \DateTime|null */ public $lastCheck; /** @var bool */ public $hasActiveChecks; /** @var bool */ public $hasPassiveChecks; /** @var \DateTime|null */ public $lastTimeUp; /** @var int|null */ public $checkAttempts; /** @var int|null */ public $maxCheckAttempts; /** @var array<string, int|string|null> */ public $icon; /** @var array<array<string, mixed>> */ public $groups; /** @var array<string, mixed> */ public $status; /** @var array<int, array<string, mixed>> */ public $downtimes; /** @var array<string, mixed> */ public $acknowledgement; /** @var array<array<string, mixed>> */ public array $categories = []; /** @var _severityArray|null */ public ?array $severity = null; /** @var string */ public string $type = HostResourceType::TYPE_NAME; /** * @param int $hostId * @param string $name * @param string $address * @param string $monitoringServerName * @param HostStatus $status * @param Icon|null $icon * @param Hostgroup[] $hostgroups * @param Downtime[] $downtimes * @param Acknowledgement|null $acknowledgement, * @param Tag[] $categories * @param Severity|null $severity */ public function __construct( public int $hostId, public string $name, public string $address, public string $monitoringServerName, HostStatus $status, ?Icon $icon, array $hostgroups, array $downtimes, ?Acknowledgement $acknowledgement, array $categories, ?Severity $severity, ) { $this->icon = $this->iconToArray($icon); $this->status = $this->statusToArray($status); $this->groups = $this->hostgroupsToArray($hostgroups); $this->downtimes = $this->downtimesToArray($downtimes); $this->acknowledgement = $this->acknowledgementToArray($acknowledgement); $this->categories = $this->tagsToArray($categories); $this->severity = $severity === null ? $severity : $this->severityToArray($severity); } /** * Converts an array of Hostgroups model into an array. * * @param Hostgroup[] $hostgroups * * @return array<int, array<string, mixed>> */ private function hostgroupsToArray(array $hostgroups): array { return array_map( fn (Hostgroup $hostgroup) => [ 'id' => $hostgroup->getId(), 'name' => $hostgroup->getName(), ], $hostgroups ); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/RealTime/UseCase/FindHost/FindHostPresenterInterface.php
centreon/src/Core/Application/RealTime/UseCase/FindHost/FindHostPresenterInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\RealTime\UseCase\FindHost; use Core\Application\Common\UseCase\PresenterInterface; interface FindHostPresenterInterface extends PresenterInterface { /** * {@inheritDoc} * * @param FindHostResponse $response */ public function present(mixed $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/Application/RealTime/UseCase/FindHost/FindHost.php
centreon/src/Core/Application/RealTime/UseCase/FindHost/FindHost.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\RealTime\UseCase\FindHost; use Centreon\Domain\Contact\Contact; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Log\LoggerTrait; use Centreon\Domain\Monitoring\Host as LegacyHost; use Centreon\Domain\Monitoring\Interfaces\MonitoringServiceInterface; use Core\Application\Common\UseCase\NotFoundResponse; use Core\Application\RealTime\Repository\ReadAcknowledgementRepositoryInterface; use Core\Application\RealTime\Repository\ReadDowntimeRepositoryInterface; use Core\Application\RealTime\Repository\ReadHostgroupRepositoryInterface; use Core\Application\RealTime\Repository\ReadHostRepositoryInterface; use Core\Domain\RealTime\Model\Acknowledgement; use Core\Domain\RealTime\Model\Downtime; use Core\Domain\RealTime\Model\Host; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\Severity\RealTime\Application\Repository\ReadSeverityRepositoryInterface; use Core\Severity\RealTime\Domain\Model\Severity; use Core\Tag\RealTime\Application\Repository\ReadTagRepositoryInterface; use Core\Tag\RealTime\Domain\Model\Tag; final class FindHost { use LoggerTrait; /** * @param ReadHostRepositoryInterface $repository * @param ReadHostgroupRepositoryInterface $hostgroupRepository * @param ContactInterface $contact * @param ReadAccessGroupRepositoryInterface $accessGroupRepository * @param ReadDowntimeRepositoryInterface $downtimeRepository * @param ReadAcknowledgementRepositoryInterface $acknowledgementRepository * @param MonitoringServiceInterface $monitoringService * @param ReadTagRepositoryInterface $tagRepository * @param ReadSeverityRepositoryInterface $severityRepository */ public function __construct( private ReadHostRepositoryInterface $repository, private ReadHostgroupRepositoryInterface $hostgroupRepository, private ContactInterface $contact, private ReadAccessGroupRepositoryInterface $accessGroupRepository, private ReadDowntimeRepositoryInterface $downtimeRepository, private ReadAcknowledgementRepositoryInterface $acknowledgementRepository, private MonitoringServiceInterface $monitoringService, private ReadTagRepositoryInterface $tagRepository, private ReadSeverityRepositoryInterface $severityRepository, ) { } /** * @param int $hostId * @param FindHostPresenterInterface $presenter */ public function __invoke(int $hostId, FindHostPresenterInterface $presenter): void { $this->info('Searching details for host', ['id' => $hostId]); if ($this->contact->isAdmin()) { $host = $this->repository->findHostById($hostId); if ($host === null) { $this->handleHostNotFound($hostId, $presenter); return; } $hostGroups = $this->hostgroupRepository->findAllByHostId($hostId); } else { $accessGroups = $this->accessGroupRepository->findByContact($this->contact); $accessGroupIds = array_map( fn ($accessGroup) => $accessGroup->getId(), $accessGroups ); $host = $this->repository->findHostByIdAndAccessGroupIds($hostId, $accessGroupIds); if ($host === null) { $this->handleHostNotFound($hostId, $presenter); return; } $hostGroups = $this->hostgroupRepository->findAllByHostIdAndAccessGroupIds($hostId, $accessGroupIds); } $host->setGroups($hostGroups); $categories = $this->tagRepository->findAllByResourceAndTypeId($host->getId(), 0, Tag::HOST_CATEGORY_TYPE_ID); $host->setCategories($categories); $this->info( 'Fetching severity from the database for host', [ 'hostId' => $hostId, 'typeId' => Severity::HOST_SEVERITY_TYPE_ID, ] ); $severity = $this->severityRepository->findByResourceAndTypeId( $hostId, 0, Severity::HOST_SEVERITY_TYPE_ID ); $host->setSeverity($severity); $acknowledgement = $host->isAcknowledged() === true ? $this->acknowledgementRepository->findOnGoingAcknowledgementByHostId($hostId) : null; $downtimes = $host->isInDowntime() === true ? $this->downtimeRepository->findOnGoingDowntimesByHostId($hostId) : []; /** * Obfuscate the passwords in Host commandLine. * * @todo Re-write this code when monitoring repository will be migrated to new architecture */ $host->setCommandLine($this->obfuscatePasswordInHostCommandLine($host)); $presenter->present( $this->createResponse( $host, $downtimes, $acknowledgement ) ); } /** * Handle Host not found. This method will log the error and set the ResponseStatus. * * @param int $hostId * @param FindHostPresenterInterface $presenter */ private function handleHostNotFound(int $hostId, FindHostPresenterInterface $presenter): void { $this->error('Host not found', ['id' => $hostId, 'userId' => $this->contact->getId()]); $presenter->setResponseStatus(new NotFoundResponse('Host')); } /** * @param Host $host * @param Downtime[] $downtimes * @param Acknowledgement|null $acknowledgement * * @return FindHostResponse */ private function createResponse(Host $host, array $downtimes, ?Acknowledgement $acknowledgement): FindHostResponse { $findHostResponse = new FindHostResponse( $host->getId(), $host->getName(), $host->getAddress(), $host->getMonitoringServerName(), $host->getStatus(), $host->getIcon(), $host->getGroups(), $downtimes, $acknowledgement, $host->getCategories(), $host->getSeverity() ); $findHostResponse->timezone = $host->getTimezone(); $findHostResponse->alias = $host->getAlias(); $findHostResponse->isFlapping = $host->isFlapping(); $findHostResponse->isAcknowledged = $host->isAcknowledged(); $findHostResponse->isInDowntime = $host->isInDowntime(); $findHostResponse->output = $host->getOutput(); $findHostResponse->performanceData = $host->getPerformanceData(); $findHostResponse->commandLine = $host->getCommandLine(); $findHostResponse->notificationNumber = $host->getNotificationNumber(); $findHostResponse->lastStatusChange = $host->getLastStatusChange(); $findHostResponse->lastNotification = $host->getLastNotification(); $findHostResponse->latency = $host->getLatency(); $findHostResponse->executionTime = $host->getExecutionTime(); $findHostResponse->statusChangePercentage = $host->getStatusChangePercentage(); $findHostResponse->nextCheck = $host->getNextCheck(); $findHostResponse->lastCheck = $host->getLastCheck(); $findHostResponse->hasPassiveChecks = $host->hasPassiveChecks(); $findHostResponse->hasActiveChecks = $host->hasActiveChecks(); $findHostResponse->lastTimeUp = $host->getLastTimeUp(); $findHostResponse->checkAttempts = $host->getCheckAttempts(); $findHostResponse->maxCheckAttempts = $host->getMaxCheckAttempts(); return $findHostResponse; } /** * Offuscate passwords in the commandline. * * @param Host $host * * @return string|null */ private function obfuscatePasswordInHostCommandLine(Host $host): ?string { $obfuscatedCommandLine = null; /** * Check if user can see the commandLine. * If so, then hide potential passwords. */ if ( $this->contact->isAdmin() || $this->contact->hasRole(Contact::ROLE_DISPLAY_COMMAND) || $host->getCommandLine() !== null ) { try { $legacyHost = (new LegacyHost()) ->setId($host->getId()) ->setCheckCommand($host->getCommandLine()); $this->monitoringService->hidePasswordInHostCommandLine($legacyHost); $obfuscatedCommandLine = $legacyHost->getCheckCommand(); } catch (\Throwable $ex) { $errorMsg = 'Failed to hide password in host command line'; $this->debug($errorMsg, ['id' => $host->getId(), 'reason' => $ex->getMessage()]); $obfuscatedCommandLine = sprintf( _('Unable to hide passwords in command (Reason: %s)'), $ex->getMessage() ); } } return $obfuscatedCommandLine; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/RealTime/Common/RealTimeResponseTrait.php
centreon/src/Core/Application/RealTime/Common/RealTimeResponseTrait.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\RealTime\Common; use Core\Domain\RealTime\Model\Acknowledgement; use Core\Domain\RealTime\Model\Downtime; use Core\Domain\RealTime\Model\Icon; use Core\Domain\RealTime\Model\Status; use Core\Severity\RealTime\Domain\Model\Severity; use Core\Tag\RealTime\Domain\Model\Tag; /** * @phpstan-type _iconArray array{ * id: null|int, * name: null|string, * url: null|string, * } * @phpstan-type _severityArray array{ * id: int, * name: string, * level: int, * type: string, * icon: array{}|_iconArray, * } */ trait RealTimeResponseTrait { /** * Converts an Icon model into an array. * * @param Icon|null $icon * * @return ($icon is null ? array{} : _iconArray) */ public function iconToArray(?Icon $icon): array { return $icon === null ? [] : [ 'id' => $icon->getId(), 'name' => $icon->getName(), 'url' => $icon->getUrl(), ]; } /** * Converts an array of Downtimes entities into an array. * * @param Downtime[] $downtimes * * @return array<int, array<string, mixed>> */ public function downtimesToArray(array $downtimes): array { return array_map( fn (Downtime $downtime) => [ 'start_time' => $downtime->getStartTime(), 'end_time' => $downtime->getEndTime(), 'actual_start_time' => $downtime->getActualStartTime(), 'actual_end_time' => $downtime->getActualEndTime(), 'id' => $downtime->getId(), 'entry_time' => $downtime->getEntryTime(), 'author_id' => $downtime->getAuthorId(), 'author_name' => $downtime->getAuthorName(), 'host_id' => $downtime->getHostId(), 'service_id' => $downtime->getServiceId(), 'is_cancelled' => $downtime->isCancelled(), 'comment' => $downtime->getComment(), 'deletion_time' => $downtime->getDeletionTime(), 'duration' => $downtime->getDuration(), 'internal_id' => $downtime->getEngineDowntimeId(), 'is_fixed' => $downtime->isFixed(), 'poller_id' => $downtime->getInstanceId(), 'is_started' => $downtime->isStarted(), ], $downtimes ); } /** * Converts an Acknowledgement entity into an array. * * @param Acknowledgement|null $acknowledgement * * @return array<string, mixed> */ public function acknowledgementToArray(?Acknowledgement $acknowledgement): array { return is_null($acknowledgement) ? [] : [ 'id' => $acknowledgement->getId(), 'poller_id' => $acknowledgement->getInstanceId(), 'host_id' => $acknowledgement->getHostId(), 'service_id' => $acknowledgement->getServiceId(), 'author_id' => $acknowledgement->getAuthorId(), 'author_name' => $acknowledgement->getAuthorName(), 'comment' => $acknowledgement->getComment(), 'deletion_time' => $acknowledgement->getDeletionTime(), 'entry_time' => $acknowledgement->getEntryTime(), 'is_notify_contacts' => $acknowledgement->isNotifyContacts(), 'is_persistent_comment' => $acknowledgement->isPersistentComment(), 'is_sticky' => $acknowledgement->isSticky(), 'state' => $acknowledgement->getState(), 'type' => $acknowledgement->getType(), 'with_services' => $acknowledgement->isWithServices(), ]; } /** * Convert array of HostCategory models into an array made of scalars. * * @param Tag[] $tags * * @return array<int, array<string, int|string>> */ private function tagsToArray(array $tags): array { return array_map( fn (Tag $tag) => [ 'id' => $tag->getId(), 'name' => $tag->getName(), ], $tags ); } /** * Converts Status model into an array for DTO. * * @param Status $status * * @return array<string, mixed> */ private function statusToArray(Status $status): array { return [ 'name' => $status->getName(), 'code' => $status->getCode(), 'severity_code' => $status->getOrder(), 'type' => $status->getType(), ]; } /** * Converts Severity model into an array for DTO. * * @param Severity $severity * * @return _severityArray */ private function severityToArray(Severity $severity): array { return [ 'id' => $severity->getId(), 'name' => $severity->getName(), 'level' => $severity->getLevel(), 'type' => $severity->getTypeAsString(), 'icon' => $this->iconToArray($severity->getIcon()), ]; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/RealTime/Repository/ReadMetaServiceRepositoryInterface.php
centreon/src/Core/Application/RealTime/Repository/ReadMetaServiceRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\RealTime\Repository; use Core\Domain\RealTime\Model\MetaService; interface ReadMetaServiceRepositoryInterface { /** * Find MetaService without ACL. * * @param int $metaId * * @return MetaService|null */ public function findMetaServiceById(int $metaId): ?MetaService; /** * Find MetaService with ACL. * * @param int $metaId * @param int[] $accessGroupIds * * @return MetaService|null */ public function findMetaServiceByIdAndAccessGroupIds(int $metaId, array $accessGroupIds): ?MetaService; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/RealTime/Repository/ReadPerformanceDataRepositoryInterface.php
centreon/src/Core/Application/RealTime/Repository/ReadPerformanceDataRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\RealTime\Repository; use Core\Metric\Domain\Model\Metric; use Core\Metric\Domain\Model\PerformanceMetric; use DateTimeInterface; interface ReadPerformanceDataRepositoryInterface { /** * @param array<Metric> $metrics * @param DateTimeInterface $startDate * @param DateTimeInterface $endDate * * @return iterable<PerformanceMetric> */ public function findDataByMetricsAndDates( array $metrics, DateTimeInterface $startDate, DateTimeInterface $endDate, ): iterable; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/RealTime/Repository/ReadHostgroupRepositoryInterface.php
centreon/src/Core/Application/RealTime/Repository/ReadHostgroupRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\RealTime\Repository; use Core\Domain\RealTime\Model\Hostgroup; interface ReadHostgroupRepositoryInterface { /** * Find related hostgroups regarding a host without ACL. * * @param int $hostId * * @return Hostgroup[] */ public function findAllByHostId(int $hostId): array; /** * Find related hostgroups regarding a host with ACL. * * @param int $hostId * @param int[] $accessGroupIds * * @return Hostgroup[] */ public function findAllByHostIdAndAccessGroupIds(int $hostId, array $accessGroupIds): array; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/RealTime/Repository/ReadHostRepositoryInterface.php
centreon/src/Core/Application/RealTime/Repository/ReadHostRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\RealTime\Repository; use Core\Domain\RealTime\Model\Host; interface ReadHostRepositoryInterface { /** * Find Host without ACL. * * @param int $hostId * * @return Host|null */ public function findHostById(int $hostId): ?Host; /** * Find Host regarding user ACL. * * @param int $hostId * @param int[] $accessGroupIds * * @return Host|null */ public function findHostByIdAndAccessGroupIds(int $hostId, array $accessGroupIds): ?Host; /** * Check if user is allowed to get host information. * * @param int $hostId * @param int[] $accessGroupIds * * @return bool */ public function isAllowedToFindHostByAccessGroupIds(int $hostId, array $accessGroupIds): bool; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/RealTime/Repository/ReadAcknowledgementRepositoryInterface.php
centreon/src/Core/Application/RealTime/Repository/ReadAcknowledgementRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\RealTime\Repository; use Core\Domain\RealTime\Model\Acknowledgement; interface ReadAcknowledgementRepositoryInterface { /** * @param int $hostId * * @return Acknowledgement|null */ public function findOnGoingAcknowledgementByHostId(int $hostId): ?Acknowledgement; /** * @param int $hostId * @param int $serviceId * * @return Acknowledgement|null */ public function findOnGoingAcknowledgementByHostIdAndServiceId(int $hostId, int $serviceId): ?Acknowledgement; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/RealTime/Repository/ReadDowntimeRepositoryInterface.php
centreon/src/Core/Application/RealTime/Repository/ReadDowntimeRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\RealTime\Repository; use Core\Domain\RealTime\Model\Downtime; interface ReadDowntimeRepositoryInterface { /** * @param int $hostId * * @return Downtime[] */ public function findOnGoingDowntimesByHostId(int $hostId): array; /** * @param int $hostId * @param int $serviceId * * @return Downtime[] */ public function findOnGoingDowntimesByHostIdAndServiceId(int $hostId, int $serviceId): 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/Application/RealTime/Repository/ReadServiceRepositoryInterface.php
centreon/src/Core/Application/RealTime/Repository/ReadServiceRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\RealTime\Repository; use Core\Domain\RealTime\Model\Service; interface ReadServiceRepositoryInterface { /** * Find Service without ACL. * * @param int $hostId * @param int $serviceId * * @return Service|null */ public function findServiceById(int $hostId, int $serviceId): ?Service; /** * Find Service with ACL. * * @param int $hostId * @param int $serviceId * @param int[] $accessGroupIds * * @return Service|null */ public function findServiceByIdAndAccessGroupIds(int $hostId, int $serviceId, array $accessGroupIds): ?Service; /** * Check if user is allowed to get service information. * * @param int $hostId * @param int $serviceId * @param int[] $accessGroupIds * * @return bool */ public function isAllowedToFindServiceByAccessGroupIds(int $hostId, int $serviceId, array $accessGroupIds): bool; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/RealTime/Repository/ReadIndexDataRepositoryInterface.php
centreon/src/Core/Application/RealTime/Repository/ReadIndexDataRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\RealTime\Repository; use Core\Domain\RealTime\Model\IndexData; interface ReadIndexDataRepositoryInterface { /** * @param int $hostId * @param int $serviceId * * @throw \Throwable * * @return int */ public function findIndexByHostIdAndServiceId(int $hostId, int $serviceId): int; /** * @param int $index * * @return IndexData|null */ public function findHostNameAndServiceDescriptionByIndex(int $index): ?IndexData; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/RealTime/Repository/ReadServicegroupRepositoryInterface.php
centreon/src/Core/Application/RealTime/Repository/ReadServicegroupRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\RealTime\Repository; use Core\Domain\RealTime\Model\Servicegroup; interface ReadServicegroupRepositoryInterface { /** * Find Servicegroups that contains the requested Service by Id without ACL. * * @param int $hostId * @param int $serviceId * * @return Servicegroup[] */ public function findAllByHostIdAndServiceId(int $hostId, int $serviceId): array; /** * Find Servicegroups that contains the requested Service by Id with ACL. * * @param int $hostId * @param int $serviceId * @param int[] $accessGroupIds * * @return Servicegroup[] */ public function findAllByHostIdAndServiceIdAndAccessGroupIds( int $hostId, int $serviceId, array $accessGroupIds, ): array; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Configuration/NotificationPolicy/UseCase/FindHostNotificationPolicy.php
centreon/src/Core/Application/Configuration/NotificationPolicy/UseCase/FindHostNotificationPolicy.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Configuration\NotificationPolicy\UseCase; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Engine\EngineConfiguration; use Centreon\Domain\Engine\Interfaces\EngineConfigurationServiceInterface; use Centreon\Domain\HostConfiguration\Host; use Centreon\Domain\HostConfiguration\Interfaces\HostConfigurationRepositoryInterface; use Centreon\Domain\Log\LoggerTrait; use Centreon\Domain\Option\OptionService; use Core\Application\Common\UseCase\NotFoundResponse; use Core\Application\Configuration\Notification\Repository\ReadHostNotificationRepositoryInterface; use Core\Application\RealTime\Repository\ReadHostRepositoryInterface as ReadRealTimeHostRepositoryInterface; use Core\Common\Application\Converter\YesNoDefaultConverter; use Core\Domain\Configuration\Notification\Model\NotifiedContact; use Core\Domain\Configuration\Notification\Model\NotifiedContactGroup; use Core\Domain\RealTime\Model\Host as RealtimeHost; use Core\Host\Application\Repository\ReadHostRepositoryInterface; use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; class FindHostNotificationPolicy { use LoggerTrait; private const INHERITANCE_MODE_VERTICAL = 1; private const INHERITANCE_MODE_CLOSE = 2; private const INHERITANCE_MODE_CUMULATIVE = 3; private const TYPE_CONTACT = 'contact'; private const TYPE_CONTACT_GROUP = 'cg'; /** * @param ReadHostNotificationRepositoryInterface $readHostNotificationRepository * @param HostConfigurationRepositoryInterface $hostRepository * @param EngineConfigurationServiceInterface $engineService * @param ReadAccessGroupRepositoryInterface $accessGroupRepository * @param ContactInterface $contact * @param ReadRealTimeHostRepositoryInterface $readRealTimeHostRepository * @param OptionService $optionService * @param ReadHostTemplateRepositoryInterface $readHostTemplateRepository * @param ReadHostRepositoryInterface $readHostRepository */ public function __construct( private ReadHostNotificationRepositoryInterface $readHostNotificationRepository, private HostConfigurationRepositoryInterface $hostRepository, private EngineConfigurationServiceInterface $engineService, private ReadAccessGroupRepositoryInterface $accessGroupRepository, private ContactInterface $contact, private ReadRealTimeHostRepositoryInterface $readRealTimeHostRepository, private readonly OptionService $optionService, private readonly ReadHostTemplateRepositoryInterface $readHostTemplateRepository, private readonly ReadHostRepositoryInterface $readHostRepository, ) { } /** * @param int $hostId * @param FindNotificationPolicyPresenterInterface $presenter */ public function __invoke( int $hostId, FindNotificationPolicyPresenterInterface $presenter, ): void { $this->info('Searching for host notification policy', ['id' => $hostId]); $host = $this->findHost($hostId); if ($host === null) { $this->handleHostNotFound($hostId, $presenter); return; } $inheritanceMode = $this->optionService->findSelectedOptions(['inheritance_mode']); $inheritanceMode = isset($inheritanceMode[0]) ? (int) $inheritanceMode[0]->getValue() : 0; [$notifiedContactsIds, $notifiedContactGroupsIds] = $this->getNotifiedContactsAndContactGroupsIds($hostId, $inheritanceMode, $presenter); if (! $this->contact->isAdmin()) { $accessGroups = $this->accessGroupRepository->findByContact($this->contact); $notifiedContacts = $this->readHostNotificationRepository->findNotifiedContactsByIdsAndAccessGroups( $hostId, $notifiedContactsIds, $notifiedContactGroupsIds, $accessGroups ); $notifiedContactGroups = $this->readHostNotificationRepository->findNotifiedContactGroupsByIdsAndAccessGroups( $hostId, $notifiedContactsIds, $notifiedContactGroupsIds, $accessGroups ); } else { $notifiedContacts = $this->readHostNotificationRepository->findNotifiedContactsByIds( $hostId, $notifiedContactsIds, $notifiedContactGroupsIds ); $notifiedContactGroups = $this->readHostNotificationRepository->findNotifiedContactGroupsByIds( $hostId, $notifiedContactsIds, $notifiedContactGroupsIds ); } $realtimeHost = $this->readRealTimeHostRepository->findHostById($hostId); if ($realtimeHost === null) { $this->handleHostNotFound($hostId, $presenter); return; } $engineConfiguration = $this->engineService->findEngineConfigurationByHost($host); if ($engineConfiguration === null) { $this->handleEngineHostConfigurationNotFound($hostId, $presenter); return; } $this->overrideHostNotificationByEngineConfiguration($engineConfiguration, $realtimeHost); $presenter->present( $this->createResponse( $notifiedContacts, $notifiedContactGroups, $realtimeHost->isNotificationEnabled(), ) ); } /** * @param NotifiedContact[] $notifiedContacts * @param NotifiedContactGroup[] $notifiedContactGroups * @param bool $isNotificationEnabled * * @return FindNotificationPolicyResponse */ public function createResponse( array $notifiedContacts, array $notifiedContactGroups, bool $isNotificationEnabled, ): FindNotificationPolicyResponse { return new FindNotificationPolicyResponse( $notifiedContacts, $notifiedContactGroups, $isNotificationEnabled, ); } /** * Find host by id. * * @param int $hostId * * @return Host|null */ private function findHost(int $hostId): ?Host { $this->info('Searching for host configuration', ['id' => $hostId]); $host = null; if ($this->contact->isAdmin()) { $host = $this->hostRepository->findHost($hostId); } else { $accessGroups = $this->accessGroupRepository->findByContact($this->contact); $accessGroupIds = array_map( fn ($accessGroup) => $accessGroup->getId(), $accessGroups ); if ($this->readRealTimeHostRepository->isAllowedToFindHostByAccessGroupIds($hostId, $accessGroupIds)) { $host = $this->hostRepository->findHost($hostId); } } return $host; } /** * @param int $hostId * @param FindNotificationPolicyPresenterInterface $presenter */ private function handleHostNotFound( int $hostId, FindNotificationPolicyPresenterInterface $presenter, ): void { $this->error( 'Host not found', [ 'id' => $hostId, 'userId' => $this->contact->getId(), ] ); $presenter->setResponseStatus(new NotFoundResponse('Host')); } /** * @param int $hostTemplateId * @param FindNotificationPolicyPresenterInterface $presenter */ private function handleHostTemplateNotFound( int $hostTemplateId, FindNotificationPolicyPresenterInterface $presenter, ): void { $this->error( 'HostTemplate not found', [ 'id' => $hostTemplateId, 'userId' => $this->contact->getId(), ] ); $presenter->setResponseStatus(new NotFoundResponse('HostTemplate')); } /** * @param int $hostId * @param FindNotificationPolicyPresenterInterface $presenter */ private function handleEngineHostConfigurationNotFound( int $hostId, FindNotificationPolicyPresenterInterface $presenter, ): void { $this->error( 'Engine configuration not found for Host', [ 'id' => $hostId, 'userId' => $this->contact->getId(), ] ); $presenter->setResponseStatus(new NotFoundResponse('Engine configuration')); } /** * If engine configuration related to the host has notification disabled, * it overrides host notification status. * * @param EngineConfiguration $engineConfiguration * @param RealtimeHost $realtimeHost */ private function overrideHostNotificationByEngineConfiguration( EngineConfiguration $engineConfiguration, RealtimeHost $realtimeHost, ): void { if ( $engineConfiguration->getNotificationsEnabledOption() === EngineConfiguration::NOTIFICATIONS_OPTION_DISABLED ) { $realtimeHost->setNotificationEnabled(false); } } /** * Returns contacts and ContactGroups Ids related to a host by inheritance mode. * * @param int $hostId * @param int $inheritanceMode * @param FindNotificationPolicyPresenterInterface $presenter * * @return array<int, array<int, int>> */ private function getNotifiedContactsAndContactGroupsIds(int $hostId, int $inheritanceMode, FindNotificationPolicyPresenterInterface $presenter): array { $host = $this->readHostRepository->findById($hostId); if ($host === null) { return [[], []]; } // check if notifications are enabled for host if (YesNoDefaultConverter::toInt($host->getNotificationEnabled()) !== null && YesNoDefaultConverter::toInt($host->getNotificationEnabled()) === 0) { return [[], []]; } $hostContacts = $this->readHostNotificationRepository->findContactsByHostOrHostTemplate($hostId); $hostContactGroups = $this->readHostNotificationRepository->findContactGroupsByHostOrHostTemplate($hostId); $hostTemplates = $this->readHostTemplateRepository->findByHostId($hostId); $parents = $this->findAllParents($hostId); switch ($inheritanceMode) { case self::INHERITANCE_MODE_CUMULATIVE: [$notifiedContacts, $notifiedContactGroups] = $this->cumulativeInheritance($hostTemplates, $parents, $presenter); $hostContacts = array_unique( array_merge($hostContacts, $notifiedContacts), SORT_NUMERIC ); $hostContactGroups = array_unique( array_merge($hostContactGroups, $notifiedContactGroups), SORT_NUMERIC ); break; case self::INHERITANCE_MODE_CLOSE: if ($hostContacts === []) { $hostContacts = array_unique( array_merge($hostContacts, $this->closeInheritance($hostTemplates, $parents, self::TYPE_CONTACT, $presenter)), SORT_NUMERIC ); } if ($hostContactGroups === []) { $hostContactGroups = array_unique( array_merge($hostContactGroups, $this->closeInheritance($hostTemplates, $parents, self::TYPE_CONTACT_GROUP, $presenter)), SORT_NUMERIC ); } break; case self::INHERITANCE_MODE_VERTICAL: default: if ($host->addInheritedContact()) { $hostContacts = array_unique( array_merge($hostContacts, $this->verticalInheritance($hostTemplates, $parents, self::TYPE_CONTACT, $presenter)), SORT_NUMERIC ); } if ($host->addInheritedContactGroup()) { $hostContactGroups = array_unique( array_merge($hostContactGroups, $this->verticalInheritance($hostTemplates, $parents, self::TYPE_CONTACT_GROUP, $presenter)), SORT_NUMERIC ); } break; } return [$hostContacts, $hostContactGroups]; } /** * Returns contacts and contact groups ids by cumulative inheritance. * * @param array<int, int> $hostTemplates * @param array<int, array<int, int>> $parents * @param FindNotificationPolicyPresenterInterface $presenter * * @return array<int, array<int, int>> */ private function cumulativeInheritance(array $hostTemplates, array $parents, FindNotificationPolicyPresenterInterface $presenter): array { $notifiedContacts = []; $notifiedContactGroups = []; foreach ($hostTemplates as $hostTemplateId) { $stack = [$hostTemplateId]; $processed = []; $contactGroups = []; $contacts = []; while ($currentTemplateId = array_shift($stack)) { // skip if already processed if (isset($processed[$currentTemplateId])) { continue; } $processed[$currentTemplateId] = true; // check if notifications are enabled for hostTemplate $hostTemplateData = $this->readHostTemplateRepository->findById($currentTemplateId); if ($hostTemplateData === null) { $this->handleHostTemplateNotFound($currentTemplateId, $presenter); continue; } if (YesNoDefaultConverter::toInt($hostTemplateData->getNotificationEnabled()) === 0) { continue; } $hostTemplateContactGroups = $this->readHostNotificationRepository->findContactGroupsByHostOrHostTemplate($currentTemplateId); $contactGroups = array_merge($contactGroups, $hostTemplateContactGroups); $hostTemplateContacts = $this->readHostNotificationRepository->findContactsByHostOrHostTemplate($currentTemplateId); $contacts = array_merge($contacts, $hostTemplateContacts); $stack = array_merge($parents[$currentTemplateId], $stack); } $notifiedContacts = array_unique(array_merge($notifiedContacts, $contacts), SORT_NUMERIC); $notifiedContactGroups = array_unique(array_merge($notifiedContactGroups, array_unique($contactGroups)), SORT_NUMERIC); } return [$notifiedContacts, $notifiedContactGroups]; } /** * Returns contacts or contact groups ids by close inheritance. * * @param array<int, int> $hostTemplates * @param array<int, array<int, int>> $parents * @param string $type contact|cg * @param FindNotificationPolicyPresenterInterface $presenter * * @return array<int, int> */ private function closeInheritance(array $hostTemplates, array $parents, string $type, FindNotificationPolicyPresenterInterface $presenter): array { foreach ($hostTemplates as $hostTemplateId) { $stack = [$hostTemplateId]; $processed = []; while ($currentTemplateId = array_shift($stack)) { // skip if already processed if (isset($processed[$currentTemplateId])) { continue; } $processed[$currentTemplateId] = true; // check if notifications are enabled for hostTemplate $hostTemplateData = $this->readHostTemplateRepository->findById($currentTemplateId); if ($hostTemplateData === null) { $this->handleHostTemplateNotFound($currentTemplateId, $presenter); continue; } if (YesNoDefaultConverter::toInt($hostTemplateData->getNotificationEnabled()) === 0) { continue; } $values = $type === self::TYPE_CONTACT ? $this->readHostNotificationRepository->findContactsByHostOrHostTemplate($currentTemplateId) : $this->readHostNotificationRepository->findContactGroupsByHostOrHostTemplate($currentTemplateId); if ($values !== []) { return $values; } $stack = array_merge($parents[$currentTemplateId], $stack); } } return []; } /** * Returns contacts or contact groups ids by vertical inheritance. * * @param array<int, int> $hostTemplates * @param array<int, array<int, int>> $parents * @param string $type contact|cg * @param FindNotificationPolicyPresenterInterface $presenter * * @return array<int, int> */ private function verticalInheritance(array $hostTemplates, array $parents, string $type, FindNotificationPolicyPresenterInterface $presenter): array { foreach ($hostTemplates as $hostTemplateId) { $computed = []; $stack = [[$hostTemplateId, 1]]; $processed = []; $currentLevelCatch = null; while (($shifted = array_shift($stack)) !== null && [$currentTemplateId, $level] = $shifted) { if ($currentLevelCatch >= $level) { break; } // skip if template already processed if (isset($processed[$currentTemplateId])) { continue; } $processed[$currentTemplateId] = true; // check if notifications are enabled for hostTemplate $hostTemplateData = $this->readHostTemplateRepository->findById($currentTemplateId); if ($hostTemplateData === null) { $this->handleHostNotFound($currentTemplateId, $presenter); continue; } if (YesNoDefaultConverter::toInt($hostTemplateData->getNotificationEnabled()) === 0) { continue; } [$values, $additive] = $type === self::TYPE_CONTACT ? [$this->readHostNotificationRepository->findContactsByHostOrHostTemplate($currentTemplateId), $hostTemplateData->addInheritedContact()] : [$this->readHostNotificationRepository->findContactGroupsByHostOrHostTemplate($currentTemplateId), $hostTemplateData->addInheritedContactGroup()]; if ($values !== []) { $computed = array_merge($computed, $values); $currentLevelCatch = $level; if (! $additive) { break; } } foreach (array_reverse($parents[$currentTemplateId]) as $parent) { array_unshift($stack, [$parent, $level + 1]); } } if ($computed !== []) { return array_unique($computed, SORT_NUMERIC); } } return []; } /** * Find host templates recursive parents. * * @param int $hostId * * @return array<int, array<int, int>> */ private function findAllParents(int $hostId): array { $parentData = $this->readHostTemplateRepository->findParents($hostId); $parents = []; foreach ($parentData as $data) { if (! isset($parents[$data['parent_id']])) { $parents[$data['parent_id']] = []; } } foreach ($parentData as $data) { if (in_array($data['child_id'], array_keys($parents), false)) { $parents[$data['child_id']][] = $data['parent_id']; } } return $parents; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Configuration/NotificationPolicy/UseCase/FindNotificationPolicyResponse.php
centreon/src/Core/Application/Configuration/NotificationPolicy/UseCase/FindNotificationPolicyResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Configuration\NotificationPolicy\UseCase; use Core\Domain\Configuration\Notification\Model\NotifiedContact; use Core\Domain\Configuration\Notification\Model\NotifiedContactGroup; use Core\Domain\Configuration\TimePeriod\Model\TimePeriod; final class FindNotificationPolicyResponse { /** @var array<array<string, mixed>> */ public $notifiedContacts; /** @var array<array<string, mixed>> */ public $notifiedContactGroups; /** @var array<array<string, mixed>> */ public $usersNotificationSettings; /** * @param NotifiedContact[] $notifiedContacts * @param NotifiedContactGroup[] $notifiedContactGroups * @param bool $isNotificationEnabled */ public function __construct( array $notifiedContacts, array $notifiedContactGroups, public bool $isNotificationEnabled, ) { $this->notifiedContacts = $this->contactsToArray($notifiedContacts); $this->notifiedContactGroups = $this->contactGroupsToArray($notifiedContactGroups); } /** * @param NotifiedContact[] $notifiedContacts * * @return array<array<string, mixed>> */ private function contactsToArray(array $notifiedContacts): array { return array_map( fn (NotifiedContact $notifiedContact) => [ 'id' => $notifiedContact->getId(), 'name' => $notifiedContact->getName(), 'alias' => $notifiedContact->getAlias(), 'email' => $notifiedContact->getEmail(), 'notifications' => [ 'host' => $notifiedContact->getHostNotification() ? [ 'events' => $notifiedContact->getHostNotification()->getEvents(), 'time_period' => self::timePeriodToArray( $notifiedContact->getHostNotification()->getTimePeriod(), ), ] : null, 'service' => $notifiedContact->getServiceNotification() ? [ 'events' => $notifiedContact->getServiceNotification()->getEvents(), 'time_period' => self::timePeriodToArray( $notifiedContact->getServiceNotification()->getTimePeriod(), ), ] : null, ], ], $notifiedContacts ); } /** * @param NotifiedContactGroup[] $notifiedContactGroups * * @return array<array<string, mixed>> */ private function contactGroupsToArray(array $notifiedContactGroups): array { return array_map( fn (NotifiedContactGroup $notifiedContactGroup) => [ 'id' => $notifiedContactGroup->getId(), 'name' => $notifiedContactGroup->getName(), 'alias' => $notifiedContactGroup->getAlias(), ], $notifiedContactGroups ); } /** * @param TimePeriod|null $timePeriod * * @return array<string, mixed> */ private function timePeriodToArray(?TimePeriod $timePeriod): array { if ($timePeriod === null) { return []; } return [ 'id' => $timePeriod->getId(), 'name' => $timePeriod->getName(), 'alias' => $timePeriod->getAlias(), ]; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Configuration/NotificationPolicy/UseCase/FindServiceNotificationPolicy.php
centreon/src/Core/Application/Configuration/NotificationPolicy/UseCase/FindServiceNotificationPolicy.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Configuration\NotificationPolicy\UseCase; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Engine\EngineConfiguration; use Centreon\Domain\Engine\Interfaces\EngineConfigurationServiceInterface; use Centreon\Domain\HostConfiguration\Host; use Centreon\Domain\HostConfiguration\Interfaces\HostConfigurationRepositoryInterface; use Centreon\Domain\Log\LoggerTrait; use Centreon\Domain\ServiceConfiguration\Interfaces\ServiceConfigurationRepositoryInterface; use Centreon\Domain\ServiceConfiguration\Service; use Core\Application\Common\UseCase\NotFoundResponse; use Core\Application\Configuration\Notification\Repository\ReadServiceNotificationRepositoryInterface; use Core\Application\RealTime\Repository\ReadHostRepositoryInterface as ReadRealTimeHostRepositoryInterface; use Core\Application\RealTime\Repository\ReadServiceRepositoryInterface as ReadRealTimeServiceRepositoryInterface; use Core\Domain\Configuration\Notification\Model\NotifiedContact; use Core\Domain\Configuration\Notification\Model\NotifiedContactGroup; use Core\Domain\RealTime\Model\Service as RealtimeService; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; class FindServiceNotificationPolicy { use LoggerTrait; /** * @param ReadServiceNotificationRepositoryInterface $readServiceNotificationRepository * @param HostConfigurationRepositoryInterface $hostRepository * @param ServiceConfigurationRepositoryInterface $serviceRepository * @param EngineConfigurationServiceInterface $engineService * @param ReadAccessGroupRepositoryInterface $accessGroupRepository * @param ContactInterface $contact * @param ReadRealTimeHostRepositoryInterface $readRealTimeHostRepository * @param ReadRealTimeServiceRepositoryInterface $readRealTimeServiceRepository */ public function __construct( private ReadServiceNotificationRepositoryInterface $readServiceNotificationRepository, private HostConfigurationRepositoryInterface $hostRepository, private ServiceConfigurationRepositoryInterface $serviceRepository, private EngineConfigurationServiceInterface $engineService, private ReadAccessGroupRepositoryInterface $accessGroupRepository, private ContactInterface $contact, private ReadRealTimeHostRepositoryInterface $readRealTimeHostRepository, private ReadRealTimeServiceRepositoryInterface $readRealTimeServiceRepository, ) { } /** * @param int $hostId * @param int $serviceId * @param FindNotificationPolicyPresenterInterface $presenter */ public function __invoke( int $hostId, int $serviceId, FindNotificationPolicyPresenterInterface $presenter, ): void { $this->info('Searching for service notification policy', ['host_id' => $hostId, 'service_id' => $serviceId]); $host = $this->findHost($hostId); if ($host === null) { $this->handleHostNotFound($hostId, $presenter); return; } $service = $this->findService($hostId, $serviceId); if ($service === null) { $this->handleServiceNotFound($hostId, $serviceId, $presenter); return; } if (! $this->contact->isAdmin()) { $accessGroups = $this->accessGroupRepository->findByContact($this->contact); $notifiedContacts = $this->readServiceNotificationRepository->findNotifiedContactsByIdAndAccessGroups( $hostId, $serviceId, $accessGroups ); $notifiedContactGroups = $this->readServiceNotificationRepository->findNotifiedContactGroupsByIdAndAccessGroups( $hostId, $serviceId, $accessGroups ); } else { $notifiedContacts = $this->readServiceNotificationRepository->findNotifiedContactsById($hostId, $serviceId); $notifiedContactGroups = $this->readServiceNotificationRepository->findNotifiedContactGroupsById( $hostId, $serviceId ); } $realtimeService = $this->readRealTimeServiceRepository->findServiceById($hostId, $serviceId); if ($realtimeService === null) { $this->handleServiceNotFound($hostId, $serviceId, $presenter); return; } $engineConfiguration = $this->engineService->findEngineConfigurationByHost($host); if ($engineConfiguration === null) { $this->handleEngineHostConfigurationNotFound($hostId, $presenter); return; } $this->overrideServiceNotificationByEngineConfiguration($engineConfiguration, $realtimeService); $presenter->present( $this->createResponse( $notifiedContacts, $notifiedContactGroups, $realtimeService->isNotificationEnabled(), ) ); } /** * @param NotifiedContact[] $notifiedContacts * @param NotifiedContactGroup[] $notifiedContactGroups * @param bool $isNotificationEnabled * * @return FindNotificationPolicyResponse */ public function createResponse( array $notifiedContacts, array $notifiedContactGroups, bool $isNotificationEnabled, ): FindNotificationPolicyResponse { return new FindNotificationPolicyResponse( $notifiedContacts, $notifiedContactGroups, $isNotificationEnabled, ); } /** * Find host by id. * * @param int $hostId * * @return Host|null */ private function findHost(int $hostId): ?Host { $this->info('Searching for host configuration', ['id' => $hostId]); $host = null; if ($this->contact->isAdmin()) { $host = $this->hostRepository->findHost($hostId); } else { $accessGroups = $this->accessGroupRepository->findByContact($this->contact); $accessGroupIds = array_map( fn ($accessGroup) => $accessGroup->getId(), $accessGroups ); if ($this->readRealTimeHostRepository->isAllowedToFindHostByAccessGroupIds($hostId, $accessGroupIds)) { $host = $this->hostRepository->findHost($hostId); } } return $host; } /** * Find service by id. * * @param int $hostId * @param int $serviceId * * @return Service|null */ private function findService(int $hostId, int $serviceId): ?Service { $this->info('Searching for service configuration', ['host_id' => $hostId, 'service_id' => $serviceId]); $service = null; if ($this->contact->isAdmin()) { $service = $this->serviceRepository->findService($serviceId); } else { $accessGroups = $this->accessGroupRepository->findByContact($this->contact); $accessGroupIds = array_map( fn ($accessGroup) => $accessGroup->getId(), $accessGroups ); if ( $this->readRealTimeServiceRepository->isAllowedToFindServiceByAccessGroupIds( $hostId, $serviceId, $accessGroupIds, ) ) { $service = $this->serviceRepository->findService($serviceId); } } return $service; } /** * @param int $hostId * @param FindNotificationPolicyPresenterInterface $presenter */ private function handleHostNotFound( int $hostId, FindNotificationPolicyPresenterInterface $presenter, ): void { $this->error( 'Host not found', [ 'id' => $hostId, 'userId' => $this->contact->getId(), ] ); $presenter->setResponseStatus(new NotFoundResponse('Host')); } /** * @param int $hostId * @param int $serviceId * @param FindNotificationPolicyPresenterInterface $presenter */ private function handleServiceNotFound( int $hostId, int $serviceId, FindNotificationPolicyPresenterInterface $presenter, ): void { $this->error( 'Service not found', [ 'host_id' => $hostId, 'service_id' => $serviceId, 'userId' => $this->contact->getId(), ] ); $presenter->setResponseStatus(new NotFoundResponse('Service')); } /** * @param int $hostId * @param FindNotificationPolicyPresenterInterface $presenter */ private function handleEngineHostConfigurationNotFound( int $hostId, FindNotificationPolicyPresenterInterface $presenter, ): void { $this->error( 'Engine configuration not found for Host', [ 'host_id' => $hostId, 'userId' => $this->contact->getId(), ] ); $presenter->setResponseStatus(new NotFoundResponse('Engine configuration')); } /** * If engine configuration related to the host has notification disabled, * it overrides host notification status. * * @param EngineConfiguration $engineConfiguration * @param RealtimeService $realtimeService */ private function overrideServiceNotificationByEngineConfiguration( EngineConfiguration $engineConfiguration, RealtimeService $realtimeService, ): void { if ( $engineConfiguration->getNotificationsEnabledOption() === EngineConfiguration::NOTIFICATIONS_OPTION_DISABLED ) { $realtimeService->setNotificationEnabled(false); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Configuration/NotificationPolicy/UseCase/FindNotificationPolicyPresenterInterface.php
centreon/src/Core/Application/Configuration/NotificationPolicy/UseCase/FindNotificationPolicyPresenterInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Configuration\NotificationPolicy\UseCase; use Core\Application\Common\UseCase\PresenterInterface; interface FindNotificationPolicyPresenterInterface extends PresenterInterface { }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Configuration/NotificationPolicy/UseCase/FindMetaServiceNotificationPolicy.php
centreon/src/Core/Application/Configuration/NotificationPolicy/UseCase/FindMetaServiceNotificationPolicy.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Configuration\NotificationPolicy\UseCase; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Engine\EngineConfiguration; use Centreon\Domain\Engine\Interfaces\EngineConfigurationServiceInterface; use Centreon\Domain\Log\LoggerTrait; use Centreon\Domain\MetaServiceConfiguration\Interfaces\MetaServiceConfigurationReadRepositoryInterface; use Centreon\Domain\MetaServiceConfiguration\Model\MetaServiceConfiguration; use Core\Application\Common\UseCase\NotFoundResponse; use Core\Application\Configuration\Notification\Repository\ReadMetaServiceNotificationRepositoryInterface; use Core\Application\RealTime\Repository\ReadMetaServiceRepositoryInterface as ReadRealTimeMetaServiceRepositoryInterface; use Core\Domain\Configuration\Notification\Model\NotifiedContact; use Core\Domain\Configuration\Notification\Model\NotifiedContactGroup; use Core\Domain\RealTime\Model\MetaService as RealtimeMetaService; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; class FindMetaServiceNotificationPolicy { use LoggerTrait; /** * @param ReadAccessGroupRepositoryInterface $readAccessGroupRepository * @param ReadMetaServiceNotificationRepositoryInterface $readMetaServiceNotificationRepository * @param MetaServiceConfigurationReadRepositoryInterface $readMetaServiceRepository * @param EngineConfigurationServiceInterface $engineService * @param ContactInterface $contact * @param ReadRealTimeMetaServiceRepositoryInterface $readRealTimeMetaServiceRepository */ public function __construct( private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository, private readonly ReadMetaServiceNotificationRepositoryInterface $readMetaServiceNotificationRepository, private readonly MetaServiceConfigurationReadRepositoryInterface $readMetaServiceRepository, private readonly EngineConfigurationServiceInterface $engineService, private readonly ContactInterface $contact, private readonly ReadRealTimeMetaServiceRepositoryInterface $readRealTimeMetaServiceRepository, ) { } /** * @param int $metaServiceId * @param FindNotificationPolicyPresenterInterface $presenter */ public function __invoke( int $metaServiceId, FindNotificationPolicyPresenterInterface $presenter, ): void { $metaService = $this->findMetaService($metaServiceId); if ($metaService === null) { $this->handleMetaServiceNotFound($metaServiceId, $presenter); return; } if ($this->contact->isAdmin()) { $notifiedContacts = $this->readMetaServiceNotificationRepository->findNotifiedContactsById($metaServiceId); $notifiedContactGroups = $this->readMetaServiceNotificationRepository->findNotifiedContactGroupsById( $metaServiceId ); } else { $accessGroups = $this->readAccessGroupRepository->findByContact($this->contact); $notifiedContacts = $this->readMetaServiceNotificationRepository->findNotifiedContactsByIdAndAccessGroups( $metaServiceId, $accessGroups ); $notifiedContactGroups = $this->readMetaServiceNotificationRepository->findNotifiedContactGroupsByIdAndAccessGroups( $metaServiceId, $accessGroups ); } $realtimeMetaService = $this->readRealTimeMetaServiceRepository->findMetaServiceById($metaServiceId); if ($realtimeMetaService === null) { $this->handleMetaServiceNotFound($metaServiceId, $presenter); return; } $engineConfiguration = $this->engineService->findCentralEngineConfiguration(); if ($engineConfiguration === null) { $this->handleEngineHostConfigurationNotFound($presenter); return; } $this->overrideMetaServiceNotificationByEngineConfiguration($engineConfiguration, $realtimeMetaService); $presenter->present( $this->createResponse( $notifiedContacts, $notifiedContactGroups, $realtimeMetaService->isNotificationEnabled(), ) ); } /** * @param NotifiedContact[] $notifiedContacts * @param NotifiedContactGroup[] $notifiedContactGroups * @param bool $isNotificationEnabled * * @return FindNotificationPolicyResponse */ public function createResponse( array $notifiedContacts, array $notifiedContactGroups, bool $isNotificationEnabled, ): FindNotificationPolicyResponse { return new FindNotificationPolicyResponse( $notifiedContacts, $notifiedContactGroups, $isNotificationEnabled, ); } /** * Find host by id. * * @param int $metaServiceId * * @return MetaServiceConfiguration|null */ private function findMetaService(int $metaServiceId): ?MetaServiceConfiguration { $this->info('Searching for meta service configuration', ['id' => $metaServiceId]); if ($this->contact->isAdmin()) { $metaService = $this->readMetaServiceRepository->findById($metaServiceId); } else { $metaService = $this->readMetaServiceRepository->findByIdAndContact($metaServiceId, $this->contact); } return $metaService; } /** * @param int $metaServiceId * @param FindNotificationPolicyPresenterInterface $presenter */ private function handleMetaServiceNotFound( int $metaServiceId, FindNotificationPolicyPresenterInterface $presenter, ): void { $this->error( 'Meta service not found', [ 'id' => $metaServiceId, 'userId' => $this->contact->getId(), ] ); $presenter->setResponseStatus(new NotFoundResponse('Meta service')); } /** * @param FindNotificationPolicyPresenterInterface $presenter */ private function handleEngineHostConfigurationNotFound( FindNotificationPolicyPresenterInterface $presenter, ): void { $this->error( 'Central engine configuration not found', [ 'userId' => $this->contact->getId(), ] ); $presenter->setResponseStatus(new NotFoundResponse('Engine configuration')); } /** * If engine configuration related to the meta service has notification disabled, * it overrides meta service notification status. * * @param EngineConfiguration $engineConfiguration * @param RealtimeMetaService $realtimeMetaService */ private function overrideMetaServiceNotificationByEngineConfiguration( EngineConfiguration $engineConfiguration, RealtimeMetaService $realtimeMetaService, ): void { if ( $engineConfiguration->getNotificationsEnabledOption() === EngineConfiguration::NOTIFICATIONS_OPTION_DISABLED ) { $realtimeMetaService->setNotificationEnabled(false); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Configuration/MetaService/Repository/ReadMetaServiceRepositoryInterface.php
centreon/src/Core/Application/Configuration/MetaService/Repository/ReadMetaServiceRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Configuration\MetaService\Repository; use Core\Domain\Configuration\Model\MetaService; use Core\Domain\Configuration\Model\MetaServiceNamesById; interface ReadMetaServiceRepositoryInterface { /** * Find MetaService configuration without ACL. * * @param int $metaId * * @return MetaService|null */ public function findMetaServiceById(int $metaId): ?MetaService; /** * Find MetaService configuration with ACL. * * @param int $metaId * @param int[] $accessGroupIds * * @return MetaService|null */ public function findMetaServiceByIdAndAccessGroupIds(int $metaId, array $accessGroupIds): ?MetaService; /** * @param int[] $metaIds * * @return int[] */ public function exist(array $metaIds): array; /** * Find Meta Services names by their IDs. * * @param int ...$ids * * @return MetaServiceNamesById */ public function findNames(int ...$ids): MetaServiceNamesById; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Configuration/Notification/Repository/ReadHostNotificationRepositoryInterface.php
centreon/src/Core/Application/Configuration/Notification/Repository/ReadHostNotificationRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Configuration\Notification\Repository; use Centreon\Domain\Repository\RepositoryException; use Core\Domain\Configuration\Notification\Model\NotifiedContact; use Core\Domain\Configuration\Notification\Model\NotifiedContactGroup; use Core\Security\AccessGroup\Domain\Model\AccessGroup; interface ReadHostNotificationRepositoryInterface { /** * @param int $hostId * @param array<int, int> $notifiedContactsIds * @param array<int, int> $notifiedContactGroupIds * * @return NotifiedContact[] */ public function findNotifiedContactsByIds(int $hostId, array $notifiedContactsIds, array $notifiedContactGroupIds): array; /** * @param int $hostId * @param array<int, int> $notifiedContactsIds * @param array<int, int> $notifiedContactGroupIds * @param AccessGroup[] $accessGroups * * @return NotifiedContact[] */ public function findNotifiedContactsByIdsAndAccessGroups(int $hostId, array $notifiedContactsIds, array $notifiedContactGroupIds, array $accessGroups): array; /** * @param int $hostId * @param array<int, int> $notifiedContactsIds * @param array<int, int> $notifiedContactGroupIds * * @return NotifiedContactGroup[] */ public function findNotifiedContactGroupsByIds(int $hostId, array $notifiedContactsIds, array $notifiedContactGroupIds): array; /** * @param int $hostId * @param array<int, int> $notifiedContactsIds * @param array<int, int> $notifiedContactGroupIds * @param AccessGroup[] $accessGroups * * @return NotifiedContactGroup[] */ public function findNotifiedContactGroupsByIdsAndAccessGroups(int $hostId, array $notifiedContactsIds, array $notifiedContactGroupIds, array $accessGroups): array; /** * @param int $hostId * * @throws RepositoryException * * @return array<int, int> */ public function findContactsByHostOrHostTemplate(int $hostId): array; /** * @param int $hostId * * @throws RepositoryException * * @return array<int, int> */ public function findContactGroupsByHostOrHostTemplate(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/Application/Configuration/Notification/Repository/ReadMetaServiceNotificationRepositoryInterface.php
centreon/src/Core/Application/Configuration/Notification/Repository/ReadMetaServiceNotificationRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Configuration\Notification\Repository; use Core\Domain\Configuration\Notification\Model\NotifiedContact; use Core\Domain\Configuration\Notification\Model\NotifiedContactGroup; use Core\Security\AccessGroup\Domain\Model\AccessGroup; interface ReadMetaServiceNotificationRepositoryInterface { /** * @param int $metaServiceId * * @throws \Throwable * * @return NotifiedContact[] */ public function findNotifiedContactsById(int $metaServiceId): array; /** * @param int $metaServiceId * @param AccessGroup[] $accessGroups * * @throws \Throwable * * @return NotifiedContact[] */ public function findNotifiedContactsByIdAndAccessGroups(int $metaServiceId, array $accessGroups): array; /** * @param int $metaServiceId * * @throws \Throwable * * @return NotifiedContactGroup[] */ public function findNotifiedContactGroupsById(int $metaServiceId): array; /** * @param int $metaServiceId * @param AccessGroup[] $accessGroups * * @throws \Throwable * * @return NotifiedContactGroup[] */ public function findNotifiedContactGroupsByIdAndAccessGroups(int $metaServiceId, array $accessGroups): 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/Application/Configuration/Notification/Repository/ReadServiceNotificationRepositoryInterface.php
centreon/src/Core/Application/Configuration/Notification/Repository/ReadServiceNotificationRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Configuration\Notification\Repository; use Core\Domain\Configuration\Notification\Model\NotifiedContact; use Core\Domain\Configuration\Notification\Model\NotifiedContactGroup; use Core\Security\AccessGroup\Domain\Model\AccessGroup; interface ReadServiceNotificationRepositoryInterface { /** * @param int $hostId * @param int $serviceId * * @return NotifiedContact[] */ public function findNotifiedContactsById(int $hostId, int $serviceId): array; /** * @param int $hostId * @param int $serviceId * @param AccessGroup[] $accessGroups * * @return NotifiedContact[] */ public function findNotifiedContactsByIdAndAccessGroups(int $hostId, int $serviceId, array $accessGroups): array; /** * @param int $hostId * @param int $serviceId * * @return NotifiedContactGroup[] */ public function findNotifiedContactGroupsById(int $hostId, int $serviceId): array; /** * @param int $hostId * @param int $serviceId * @param AccessGroup[] $accessGroups * * @return NotifiedContactGroup[] */ public function findNotifiedContactGroupsByIdAndAccessGroups(int $hostId, int $serviceId, array $accessGroups): 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/Application/Configuration/User/UseCase/FindUsers/FindUsersPresenterInterface.php
centreon/src/Core/Application/Configuration/User/UseCase/FindUsers/FindUsersPresenterInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Configuration\User\UseCase\FindUsers; use Core\Application\Common\UseCase\PresenterInterface; interface FindUsersPresenterInterface extends PresenterInterface { }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Configuration/User/UseCase/FindUsers/FindUsersErrorResponse.php
centreon/src/Core/Application/Configuration/User/UseCase/FindUsers/FindUsersErrorResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Configuration\User\UseCase\FindUsers; use Core\Application\Common\UseCase\ErrorResponse; final class FindUsersErrorResponse extends ErrorResponse { }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Configuration/User/UseCase/FindUsers/FindUsersResponse.php
centreon/src/Core/Application/Configuration/User/UseCase/FindUsers/FindUsersResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Configuration\User\UseCase\FindUsers; use Core\Domain\Configuration\User\Model\User; final class FindUsersResponse { /** @var array<string,mixed> */ public $users; /** * @param User[] $users */ public function __construct(array $users) { $this->users = $this->usersToArray($users); } /** * Converts an array of User models into an array. * * @param User[] $users * * @return array<string,mixed> */ public function usersToArray(array $users): array { return array_map( fn (User $user) => [ 'id' => $user->getId(), 'alias' => $user->getAlias(), 'name' => $user->getName(), 'email' => $user->getEmail(), 'is_admin' => $user->isAdmin(), ], $users ); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Configuration/User/UseCase/FindUsers/FindUsers.php
centreon/src/Core/Application/Configuration/User/UseCase/FindUsers/FindUsers.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Configuration\User\UseCase\FindUsers; use Centreon\Domain\Log\LoggerTrait; use Core\Application\Configuration\User\Repository\ReadUserRepositoryInterface; use Core\Domain\Configuration\User\Model\User; class FindUsers { use LoggerTrait; /** * @param ReadUserRepositoryInterface $usersRepository */ public function __construct(private ReadUserRepositoryInterface $usersRepository) { } /** * @param FindUsersPresenterInterface $presenter */ public function __invoke(FindUsersPresenterInterface $presenter): void { $this->debug('Searching for configured users'); try { $users = $this->usersRepository->findAllUsers(); } catch (\Throwable $ex) { $this->critical($ex->getMessage()); $presenter->setResponseStatus( new FindUsersErrorResponse($ex->getMessage()) ); return; } $presenter->present($this->createResponse($users)); } /** * @param User[] $users * * @return FindUsersResponse */ public function createResponse(array $users): FindUsersResponse { return new FindUsersResponse($users); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Configuration/User/UseCase/PatchUser/PatchUserRequest.php
centreon/src/Core/Application/Configuration/User/UseCase/PatchUser/PatchUserRequest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Configuration\User\UseCase\PatchUser; final class PatchUserRequest { public int $userId; public ?string $theme = null; public ?string $userInterfaceDensity = null; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Configuration/User/UseCase/PatchUser/PatchUserResponse.php
centreon/src/Core/Application/Configuration/User/UseCase/PatchUser/PatchUserResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Configuration\User\UseCase\PatchUser; final class PatchUserResponse { }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Configuration/User/UseCase/PatchUser/PatchUser.php
centreon/src/Core/Application/Configuration/User/UseCase/PatchUser/PatchUser.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Configuration\User\UseCase\PatchUser; use Centreon\Domain\Log\LoggerTrait; use Core\Application\Common\Session\Repository\ReadSessionRepositoryInterface; use Core\Application\Common\Session\Repository\WriteSessionRepositoryInterface; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\NoContentResponse; use Core\Application\Common\UseCase\NotFoundResponse; use Core\Application\Common\UseCase\PresenterInterface; use Core\Application\Configuration\User\Exception\UserException; use Core\Application\Configuration\User\Repository\ReadUserRepositoryInterface; use Core\Application\Configuration\User\Repository\WriteUserRepositoryInterface; final class PatchUser { use LoggerTrait; /** * @param ReadUserRepositoryInterface $readUserRepository * @param WriteUserRepositoryInterface $writeUserRepository * @param ReadSessionRepositoryInterface $readSessionRepository * @param WriteSessionRepositoryInterface $writeSessionRepository */ public function __construct( private ReadUserRepositoryInterface $readUserRepository, private WriteUserRepositoryInterface $writeUserRepository, private ReadSessionRepositoryInterface $readSessionRepository, private WriteSessionRepositoryInterface $writeSessionRepository, ) { } /** * @param PatchUserRequest $request * @param PatchUserPresenterInterface $presenter */ public function __invoke(PatchUserRequest $request, PatchUserPresenterInterface $presenter): void { $this->info('Updating user', ['request' => $request]); try { try { $this->debug('Find user', ['user_id' => $request->userId]); if (($user = $this->readUserRepository->findById($request->userId)) === null) { $this->userNotFound($request->userId, $presenter); return; } } catch (\Throwable $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); throw UserException::errorWhileSearchingForUser($ex); } if ($request->theme !== null) { try { if (($themes = $this->readUserRepository->findAvailableThemes()) === []) { $this->unexpectedError('Abnormally empty list of themes', $presenter); return; } $this->debug('User themes available', ['themes' => $themes]); if (! in_array($request->theme, $themes, true)) { $this->themeNotFound($request->theme, $presenter); return; } } catch (\Throwable $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); throw UserException::errorInReadingUserThemes($ex); } $user->setTheme($request->theme); $this->debug('New theme', ['theme' => $request->theme]); } if ($request->userInterfaceDensity !== null) { try { $user->setUserInterfaceDensity($request->userInterfaceDensity); $this->debug('New user interface view mode', ['mode' => $request->userInterfaceDensity]); } catch (\InvalidArgumentException $ex) { $this->userInterfaceViewModeUnhandled($request->userInterfaceDensity, $presenter); return; } } try { $this->writeUserRepository->update($user); $this->updateUserSessions($request); } catch (\Throwable $ex) { throw UserException::errorOnUpdatingUser($ex); } $presenter->setResponseStatus(new NoContentResponse()); } catch (\Throwable $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); $this->unexpectedError($ex->getMessage(), $presenter); } } /** * Update all user sessions. * * @param PatchUserRequest $request * * @throws \Throwable */ private function updateUserSessions(PatchUserRequest $request): void { $userSessionIds = $this->readSessionRepository->findSessionIdsByUserId($request->userId); foreach ($userSessionIds as $sessionId) { /** * @var \Centreon|null $centreon */ $centreon = $this->readSessionRepository->getValueFromSession( $sessionId, 'centreon' ); if ($centreon === null) { continue; } $centreon->user->theme = $request->theme; $this->writeSessionRepository->updateSession( $sessionId, 'centreon', $centreon ); } } /** * Handle user not found. * * @param int $userId * @param PresenterInterface $presenter */ private function userNotFound(int $userId, PresenterInterface $presenter): void { $this->error( 'User not found', ['user_id' => $userId] ); $presenter->setResponseStatus(new NotFoundResponse('User')); } /** * @param string $errorMessage * @param PresenterInterface $presenter */ private function unexpectedError(string $errorMessage, PresenterInterface $presenter): void { $this->error($errorMessage); $presenter->setResponseStatus(new ErrorResponse($errorMessage)); } /** * @param string $theme * @param PresenterInterface $presenter */ private function themeNotFound(string $theme, PresenterInterface $presenter): void { $this->error('Requested theme not found', ['theme' => $theme]); $presenter->setResponseStatus(new ErrorResponse(_('Requested theme not found'))); } /** * @param string $userInterfaceViewMode * @param PresenterInterface $presenter */ private function userInterfaceViewModeUnhandled(string $userInterfaceViewMode, PresenterInterface $presenter): void { $this->error('Requested user interface view mode not handled', ['mode' => $userInterfaceViewMode]); $presenter->setResponseStatus(new ErrorResponse(_('Requested user interface view mode not handled'))); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Configuration/User/UseCase/PatchUser/PatchUserPresenterInterface.php
centreon/src/Core/Application/Configuration/User/UseCase/PatchUser/PatchUserPresenterInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Configuration\User\UseCase\PatchUser; use Core\Application\Common\UseCase\PresenterInterface; interface PatchUserPresenterInterface extends PresenterInterface { }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Configuration/User/Exception/UserException.php
centreon/src/Core/Application/Configuration/User/Exception/UserException.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Configuration\User\Exception; class UserException extends \Exception { /** * @param \Throwable $ex * * @return self */ public static function errorOnUpdatingUser(\Throwable $ex): self { return new self(sprintf(_('Error on updating an user'), $ex->getMessage()), 0, $ex); } /** * @param \Throwable $ex * * @return self */ public static function errorInReadingUserThemes(\Throwable $ex): self { return new self( _('Error in reading the themes available to the user'), 0, $ex ); } /** * @param \Throwable $ex * * @return self */ public static function errorWhileSearchingForUser(\Throwable $ex): self { return new self( _('Error while searching for the user'), 0, $ex ); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Configuration/User/Repository/WriteUserRepositoryInterface.php
centreon/src/Core/Application/Configuration/User/Repository/WriteUserRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Configuration\User\Repository; use Core\Domain\Configuration\User\Model\NewUser; use Core\Domain\Configuration\User\Model\User; interface WriteUserRepositoryInterface { /** * Update a user. * * @param User $user */ public function update(User $user): void; /** * Create a user. * * @param NewUser $user * * @throws \Throwable */ public function create(NewUser $user): 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/Application/Configuration/User/Repository/ReadUserRepositoryInterface.php
centreon/src/Core/Application/Configuration/User/Repository/ReadUserRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Configuration\User\Repository; use Assert\AssertionFailedException; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Core\Domain\Configuration\User\Model\User; interface ReadUserRepositoryInterface { /** * Find configured users. * * @return User[] */ public function findAllUsers(): array; /** * Find configured users by their contactgroup ids. * * @param ContactInterface $contact * * @return User[] */ public function findByContactGroups(ContactInterface $contact): array; /** * Find user ids from a list of alias. * * @param string[] $userAliases * * @return int[] */ public function findUserIdsByAliases(array $userAliases): array; /** * Find user by its id. * * @param int $userId * * @throws AssertionFailedException * * @return User|null */ public function findById(int $userId): ?User; /** * Find all available themes. * * @return string[] */ public function findAvailableThemes(): 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/Application/Configuration/UserGroup/Repository/ReadUserGroupRepositoryInterface.php
centreon/src/Core/Application/Configuration/UserGroup/Repository/ReadUserGroupRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Configuration\UserGroup\Repository; use Core\Domain\Configuration\UserGroup\Model\UserGroup; interface ReadUserGroupRepositoryInterface { /** * @param int[] $userGroupIds * * @return UserGroup[] */ public function findByIds(array $userGroupIds): 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/Application/Common/UseCase/StandardResponseInterface.php
centreon/src/Core/Application/Common/UseCase/StandardResponseInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Common\UseCase; interface StandardResponseInterface { public function getData(): mixed; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Common/UseCase/NotModifiedResponse.php
centreon/src/Core/Application/Common/UseCase/NotModifiedResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Common\UseCase; final class NotModifiedResponse implements ResponseStatusInterface { /** * @inheritDoc */ public function getMessage(): string { return 'Not modified'; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Common/UseCase/AbstractPresenter.php
centreon/src/Core/Application/Common/UseCase/AbstractPresenter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Common\UseCase; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Symfony\Component\HttpFoundation\Response; abstract class AbstractPresenter implements PresenterInterface { /** @var ResponseStatusInterface|null */ private ?ResponseStatusInterface $responseStatus = null; /** @var array<string, mixed> */ private array $responseHeaders = []; /** @var mixed */ private mixed $presentedData = null; /** * @param PresenterFormatterInterface $presenterFormatter */ public function __construct(protected PresenterFormatterInterface $presenterFormatter) { } /** * @inheritDoc */ public function present(mixed $data): void { $this->presentedData = $data; } /** * @inheritDoc */ public function getPresentedData(): mixed { return $this->presentedData; } /** * @inheritDoc */ public function show(): Response { return ($this->responseStatus !== null) ? $this->presenterFormatter->format($this->responseStatus, $this->responseHeaders) : $this->presenterFormatter->format($this->presentedData, $this->responseHeaders); } /** * @inheritDoc */ public function setResponseStatus(?ResponseStatusInterface $responseStatus): void { $this->responseStatus = $responseStatus; } /** * @inheritDoc */ public function getResponseStatus(): ?ResponseStatusInterface { return $this->responseStatus; } /** * @inheritDoc */ public function setResponseHeaders(array $responseHeaders): void { $this->responseHeaders = $responseHeaders; } /** * @inheritDoc */ public function getResponseHeaders(): array { return $this->responseHeaders; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Common/UseCase/CreatedResponse.php
centreon/src/Core/Application/Common/UseCase/CreatedResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Common\UseCase; /** * @template TResourceId of int|string|null * @template TPayload */ final class CreatedResponse implements ResponseStatusInterface { /** * @param TResourceId $resourceId * @param TPayload $payload */ public function __construct( readonly private mixed $resourceId, private mixed $payload, ) { } /** * @return TResourceId */ public function getResourceId(): mixed { return match (true) { $this->resourceId === null, is_int($this->resourceId) => $this->resourceId, default => (string) $this->resourceId, }; } /** * @return TPayload */ public function getPayload(): mixed { return $this->payload; } /** * If you need to change the payload type, use {@see self::withPayload()}. * * @param TPayload $payload */ public function setPayload(mixed $payload): void { $this->payload = $payload; } /** * Basically the proper way to avoid the mutation of the internal type. * * @template TChangedPayload * * @param TChangedPayload $payload * * @return self<TResourceId, TChangedPayload> */ public function withPayload(mixed $payload): self { return new self($this->resourceId, $payload); } /** * @return string */ public function getMessage(): string { return 'Created'; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Common/UseCase/ErrorResponse.php
centreon/src/Core/Application/Common/UseCase/ErrorResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Common\UseCase; /** * Class * * @class ErrorResponse * @package Core\Application\Common\UseCase * * @description This is a standard error response that has three properties to manage errors in the use cases: * - message : accepts either a string to be translated, or a Throwable object from which to obtain the message * - context : is an array to contain information of the use case * - exception : is a \Throwable object to throw the use case exceptions in the presenter */ class ErrorResponse extends AbstractResponse { /** * ErrorResponse constructor * * @param string|\Throwable $message Only to have a message * @param array<string,mixed> $context * @param \Throwable|null $exception */ public function __construct( string|\Throwable $message, array $context = [], private readonly ?\Throwable $exception = null, ) { parent::__construct($message, $context); } /** * @return \Throwable|null */ public function getException(): ?\Throwable { return $this->exception; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Common/UseCase/UnauthorizedResponse.php
centreon/src/Core/Application/Common/UseCase/UnauthorizedResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Common\UseCase; class UnauthorizedResponse extends AbstractResponse { }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Common/UseCase/AbstractResponse.php
centreon/src/Core/Application/Common/UseCase/AbstractResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Common\UseCase; /** * This is standard Error Response which accepts either * - a string which will be translated * - a Throwable from which we will get the message. */ abstract class AbstractResponse implements ResponseStatusInterface { /** * @param string|\Throwable $message * @param array<string,mixed> $context */ public function __construct( private readonly string|\Throwable $message, private readonly array $context = [], ) { } /** * @return array<string,mixed> */ public function getContext(): array { return $this->context; } /** * @inheritDoc */ public function getMessage(): string { return \is_string($this->message) ? _($this->message) : $this->message->getMessage(); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Common/UseCase/ForbiddenResponse.php
centreon/src/Core/Application/Common/UseCase/ForbiddenResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Common\UseCase; class ForbiddenResponse extends AbstractResponse { }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Common/UseCase/ResponseStatusInterface.php
centreon/src/Core/Application/Common/UseCase/ResponseStatusInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Common\UseCase; interface ResponseStatusInterface { /** * @return string */ public function getMessage(): string; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Common/UseCase/IncompatibilityResponse.php
centreon/src/Core/Application/Common/UseCase/IncompatibilityResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Common\UseCase; final class IncompatibilityResponse extends ErrorResponse { }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Common/UseCase/MultiStatusResponse.php
centreon/src/Core/Application/Common/UseCase/MultiStatusResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Common\UseCase; final class MultiStatusResponse implements ResponseStatusInterface { /** * @param array<mixed> $results */ public function __construct(private readonly array $results) { } /** * @inheritDoc */ public function getMessage(): string { return 'Multi-status'; } /** * @return array<mixed> */ public function getPayload(): array { return $this->results; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Common/UseCase/ListingResponseInterface.php
centreon/src/Core/Application/Common/UseCase/ListingResponseInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Common\UseCase; interface ListingResponseInterface extends StandardResponseInterface { public function getData(): mixed; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Common/UseCase/PaymentRequiredResponse.php
centreon/src/Core/Application/Common/UseCase/PaymentRequiredResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Common\UseCase; final class PaymentRequiredResponse extends AbstractResponse { }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Common/UseCase/BulkResponseInterface.php
centreon/src/Core/Application/Common/UseCase/BulkResponseInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Common\UseCase; interface BulkResponseInterface extends StandardResponseInterface { public function getData(): mixed; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Common/UseCase/BodyResponseInterface.php
centreon/src/Core/Application/Common/UseCase/BodyResponseInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Common\UseCase; interface BodyResponseInterface { /** * @param mixed $body */ public function setBody(mixed $body): void; /** * @return mixed */ public function getBody(): mixed; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Common/UseCase/PresenterInterface.php
centreon/src/Core/Application/Common/UseCase/PresenterInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Common\UseCase; use Symfony\Component\HttpFoundation\Response; interface PresenterInterface { /** * @param ResponseStatusInterface|null $responseStatus */ public function setResponseStatus(?ResponseStatusInterface $responseStatus): void; /** * @return ResponseStatusInterface|null */ public function getResponseStatus(): ?ResponseStatusInterface; /** * @param array<string, mixed> $responseHeaders */ public function setResponseHeaders(array $responseHeaders): void; /** * @return array<string, mixed> */ public function getResponseHeaders(): array; /** * @param mixed $data */ public function present(mixed $data): void; /** * Return the response stored in the presenter. * * Useful for handle case where show is not called (e.g for a redirection) * * @return mixed */ public function getPresentedData(): mixed; /** * @return Response */ public function show(): 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/Application/Common/UseCase/NoContentResponse.php
centreon/src/Core/Application/Common/UseCase/NoContentResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Common\UseCase; final class NoContentResponse implements ResponseStatusInterface { /** * @inheritDoc */ public function getMessage(): string { return 'No content'; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Common/UseCase/ErrorAuthenticationConditionsResponse.php
centreon/src/Core/Application/Common/UseCase/ErrorAuthenticationConditionsResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Common\UseCase; final class ErrorAuthenticationConditionsResponse extends ForbiddenResponse { }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Common/UseCase/NotFoundResponse.php
centreon/src/Core/Application/Common/UseCase/NotFoundResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Common\UseCase; final class NotFoundResponse extends AbstractResponse { /** * @param string|\Throwable $objectNotFound * @param array<string,mixed> $context * @param \Throwable|null $exception */ public function __construct( string|\Throwable $objectNotFound, array $context = [], private readonly ?\Throwable $exception = null, ) { parent::__construct( \is_string($objectNotFound) ? $objectNotFound . ' not found' : $objectNotFound, $context ); } /** * @return null|\Throwable */ public function getException(): ?\Throwable { return $this->exception; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Common/UseCase/StandardPresenterInterface.php
centreon/src/Core/Application/Common/UseCase/StandardPresenterInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Common\UseCase; use Symfony\Component\Serializer\Encoder\JsonEncoder; interface StandardPresenterInterface { /** * @param StandardResponseInterface $data * @param array<string, mixed> $context * @param string $format * * @return string */ public function present( StandardResponseInterface $data, array $context = [], string $format = JsonEncoder::FORMAT, ): string; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Common/UseCase/ConflictResponse.php
centreon/src/Core/Application/Common/UseCase/ConflictResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Common\UseCase; /** * This is standard Error Response which accepts * - a string which will be translated * - a Throwable from which we will get the message. */ final class ConflictResponse extends AbstractResponse { }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Common/UseCase/InvalidArgumentResponse.php
centreon/src/Core/Application/Common/UseCase/InvalidArgumentResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Common\UseCase; final class InvalidArgumentResponse extends AbstractResponse { /** * InvalidArgumentResponse constructor * * @param string|\Throwable $message Only to have a message * @param array<string,mixed> $context * @param \Throwable|null $exception */ public function __construct( string|\Throwable $message, array $context = [], private readonly ?\Throwable $exception = null, ) { parent::__construct($message, $context); } /** * @return null|\Throwable */ public function getException(): ?\Throwable { return $this->exception; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Common/UseCase/CliAbstractPresenter.php
centreon/src/Core/Application/Common/UseCase/CliAbstractPresenter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Common\UseCase; use Symfony\Component\Console\Formatter\OutputFormatterStyle; use Symfony\Component\Console\Output\OutputInterface; abstract class CliAbstractPresenter { public function __construct(readonly private OutputInterface $output) { $this->output->getFormatter()->setStyle( 'error', new OutputFormatterStyle('red', '', ['bold']) ); $this->output->getFormatter()->setStyle( 'ok', new OutputFormatterStyle('green', '', ['bold']) ); $this->output->getFormatter()->setStyle( 'warning', new OutputFormatterStyle('', '#FFA500', ['bold']) ); } public function error(string $message): void { $this->output->writeln("<error>{$message}</>"); } public function ok(string $message): void { $this->output->writeln("<ok>{$message}</>"); } public function warning(string $message): void { $this->output->writeln("<warning>{$message}</>"); } public function write(string $message): void { $this->output->writeln($message); } /** * @param string[] $messages */ public function writeMultiLine(array $messages): void { $this->output->writeln($messages); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Common/Session/Repository/WriteSessionRepositoryInterface.php
centreon/src/Core/Application/Common/Session/Repository/WriteSessionRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Common\Session\Repository; interface WriteSessionRepositoryInterface { /** * Update a value in session. * * @param string $sessionId * @param string $key * @param mixed $value */ public function updateSession(string $sessionId, string $key, mixed $value): 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/Application/Common/Session/Repository/ReadSessionRepositoryInterface.php
centreon/src/Core/Application/Common/Session/Repository/ReadSessionRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Common\Session\Repository; interface ReadSessionRepositoryInterface { /** * Find the session id using the user id. * * @param int $userId * * @throws \Throwable * * @return string[] */ public function findSessionIdsByUserId(int $userId): array; /** * Get a value from session using a key. * * @param string $sessionId * @param string $key * * @throws \Throwable * * @return mixed */ public function getValueFromSession(string $sessionId, string $key): mixed; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Platform/UseCase/FindInstallationStatus/FindInstallationStatusResponse.php
centreon/src/Core/Application/Platform/UseCase/FindInstallationStatus/FindInstallationStatusResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Platform\UseCase\FindInstallationStatus; final class FindInstallationStatusResponse { /** @var bool */ public bool $isCentreonWebInstalled; /** @var bool */ public bool $isCentreonWebUpgradeAvailable; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Platform/UseCase/FindInstallationStatus/FindInstallationStatusPresenterInterface.php
centreon/src/Core/Application/Platform/UseCase/FindInstallationStatus/FindInstallationStatusPresenterInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Platform\UseCase\FindInstallationStatus; use Core\Application\Common\UseCase\PresenterInterface; interface FindInstallationStatusPresenterInterface extends PresenterInterface { }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Application/Platform/UseCase/FindInstallationStatus/FindInstallationStatus.php
centreon/src/Core/Application/Platform/UseCase/FindInstallationStatus/FindInstallationStatus.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\Application\Platform\UseCase\FindInstallationStatus; use Centreon\Domain\Log\LoggerTrait; use Core\Application\Common\UseCase\ErrorResponse; use Core\Platform\Domain\InstallationVerifierInterface; final class FindInstallationStatus { use LoggerTrait; /** * @param InstallationVerifierInterface $centreonInstallationVerifier */ public function __construct(private InstallationVerifierInterface $centreonInstallationVerifier) { } /** * @param FindInstallationStatusPresenterInterface $presenter */ public function __invoke(FindInstallationStatusPresenterInterface $presenter): void { $this->info('check installation status of centreon web'); $isCentreonWebInstalled = $this->centreonInstallationVerifier->isCentreonWebInstalled(); $isCentreonWebUpgradeAvailable = $this->centreonInstallationVerifier->isCentreonWebInstallableOrUpgradable(); if ($isCentreonWebInstalled === false && $isCentreonWebUpgradeAvailable === false) { $this->critical( 'something went wrong during your rpm installation, no centreon.conf.php or install dir was found' ); $presenter->setResponseStatus(new ErrorResponse( _('centreon is not properly installed') )); return; } $presenter->present($this->createResponse( $isCentreonWebInstalled, $isCentreonWebUpgradeAvailable )); } /** * @param bool $isCentreonWebInstalled * @param bool $isCentreonWebUpgradeAvailable * * @return FindInstallationStatusResponse */ private function createResponse( bool $isCentreonWebInstalled, bool $isCentreonWebUpgradeAvailable, ): FindInstallationStatusResponse { $response = new FindInstallationStatusResponse(); $response->isCentreonWebInstalled = $isCentreonWebInstalled; $response->isCentreonWebUpgradeAvailable = $isCentreonWebUpgradeAvailable; 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/AdditionalConnectorConfiguration/Application/UseCase/DeleteAcc/DeleteAcc.php
centreon/src/Core/AdditionalConnectorConfiguration/Application/UseCase/DeleteAcc/DeleteAcc.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\AdditionalConnectorConfiguration\Application\UseCase\DeleteAcc; use Centreon\Domain\Contact\Contact; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Log\LoggerTrait; use Core\AdditionalConnectorConfiguration\Application\Exception\AccException; use Core\AdditionalConnectorConfiguration\Application\Repository\ReadAccRepositoryInterface; use Core\AdditionalConnectorConfiguration\Application\Repository\WriteAccRepositoryInterface; use Core\AdditionalConnectorConfiguration\Application\Repository\WriteVaultAccRepositoryInterface; use Core\AdditionalConnectorConfiguration\Domain\Model\Poller; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\ForbiddenResponse; use Core\Application\Common\UseCase\NoContentResponse; use Core\Application\Common\UseCase\NotFoundResponse; use Core\Application\Common\UseCase\PresenterInterface; use Core\Common\Infrastructure\FeatureFlags; use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; final class DeleteAcc { use LoggerTrait; /** @var WriteVaultAccRepositoryInterface[] */ private array $writeVaultAccRepositories = []; /** * @param ReadAccRepositoryInterface $readAccRepository * @param WriteAccRepositoryInterface $writeAccRepository * @param ReadAccessGroupRepositoryInterface $readAccessGroupRepository * @param ReadMonitoringServerRepositoryInterface $readMonitoringServerRepository * @param ContactInterface $user * @param FeatureFlags $flags * @param \Traversable<WriteVaultAccRepositoryInterface> $writeVaultAccRepositories */ public function __construct( private readonly ReadAccRepositoryInterface $readAccRepository, private readonly WriteAccRepositoryInterface $writeAccRepository, private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository, private readonly ReadMonitoringServerRepositoryInterface $readMonitoringServerRepository, private readonly ContactInterface $user, private readonly FeatureFlags $flags, \Traversable $writeVaultAccRepositories, ) { $this->writeVaultAccRepositories = iterator_to_array($writeVaultAccRepositories); } public function __invoke( int $id, PresenterInterface $presenter, ): void { try { if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_ACC_RW)) { $this->error( "User doesn't have sufficient rights to access additional connector configurations", ['user_id' => $this->user->getId()] ); $presenter->setResponseStatus( new ForbiddenResponse(AccException::accessNotAllowed()) ); return; } if (null === $acc = $this->readAccRepository->find($id)) { $presenter->setResponseStatus(new NotFoundResponse('Additional Connector Configuration')); return; } if ($this->user->isAdmin() === false) { $linkedPollerIds = array_map( static fn (Poller $poller): int => $poller->id, $this->readAccRepository->findPollersByAccId($id) ); $accessGroups = $this->readAccessGroupRepository->findByContact($this->user); $accessiblePollerIds = $this->readMonitoringServerRepository->existByAccessGroups( $linkedPollerIds, $accessGroups ); if (array_diff($linkedPollerIds, $accessiblePollerIds)) { $presenter->setResponseStatus( new ForbiddenResponse(AccException::unsufficientRights()) ); return; } } if ($this->flags->isEnabled('vault_gorgone')) { foreach ($this->writeVaultAccRepositories as $repository) { if ($repository->isValidFor($acc->getType())) { $repository->deleteFromVault($acc); } } } $this->writeAccRepository->delete($id); $presenter->setResponseStatus(new NoContentResponse()); } catch (\Throwable $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); $presenter->setResponseStatus(new ErrorResponse( $ex instanceof AccException ? $ex : AccException::deleteAcc() )); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AdditionalConnectorConfiguration/Application/UseCase/AddAcc/AddAccResponse.php
centreon/src/Core/AdditionalConnectorConfiguration/Application/UseCase/AddAcc/AddAccResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\AdditionalConnectorConfiguration\Application\UseCase\AddAcc; use Core\AdditionalConnectorConfiguration\Domain\Model\Poller; use Core\AdditionalConnectorConfiguration\Domain\Model\Type; final class AddAccResponse { /** * @param int $id * @param Type $type * @param string $name * @param string|null $description * @param null|array{id:int,name:string} $createdBy * @param null|array{id:int,name:string} $updatedBy * @param \DateTimeImmutable $createdAt * @param \DateTimeImmutable $updatedAt * @param array<string,mixed> $parameters * @param Poller[] $pollers */ public function __construct( public int $id = 0, public Type $type = Type::VMWARE_V6, public string $name = '', public ?string $description = null, public ?array $createdBy = null, public ?array $updatedBy = null, public \DateTimeImmutable $createdAt = new \DateTimeImmutable(), public \DateTimeImmutable $updatedAt = new \DateTimeImmutable(), public array $parameters = [], public array $pollers = [], ) { } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AdditionalConnectorConfiguration/Application/UseCase/AddAcc/AddAcc.php
centreon/src/Core/AdditionalConnectorConfiguration/Application/UseCase/AddAcc/AddAcc.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\AdditionalConnectorConfiguration\Application\UseCase\AddAcc; use Assert\AssertionFailedException; use Centreon\Domain\Contact\Contact; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Log\LoggerTrait; use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface; use Core\AdditionalConnectorConfiguration\Application\Exception\AccException; use Core\AdditionalConnectorConfiguration\Application\Factory\AccFactory; use Core\AdditionalConnectorConfiguration\Application\Repository\ReadAccRepositoryInterface; use Core\AdditionalConnectorConfiguration\Application\Repository\WriteAccRepositoryInterface; use Core\AdditionalConnectorConfiguration\Application\Repository\WriteVaultAccRepositoryInterface; use Core\AdditionalConnectorConfiguration\Domain\Model\Acc; use Core\AdditionalConnectorConfiguration\Domain\Model\NewAcc; use Core\AdditionalConnectorConfiguration\Domain\Model\Poller; use Core\AdditionalConnectorConfiguration\Domain\Model\Type; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\ForbiddenResponse; use Core\Application\Common\UseCase\InvalidArgumentResponse; use Core\Common\Infrastructure\FeatureFlags; final class AddAcc { use LoggerTrait; /** @var WriteVaultAccRepositoryInterface[] */ private array $writeVaultAccRepositories = []; /** * @param ReadAccRepositoryInterface $readAccRepository * @param WriteAccRepositoryInterface $writeAccRepository * @param Validator $validator * @param AccFactory $factory * @param DataStorageEngineInterface $dataStorageEngine * @param ContactInterface $user * @param FeatureFlags $flags * @param \Traversable<WriteVaultAccRepositoryInterface> $writeVaultAccRepositories */ public function __construct( private readonly ReadAccRepositoryInterface $readAccRepository, private readonly WriteAccRepositoryInterface $writeAccRepository, private readonly Validator $validator, private readonly AccFactory $factory, private readonly DataStorageEngineInterface $dataStorageEngine, private readonly ContactInterface $user, private readonly FeatureFlags $flags, \Traversable $writeVaultAccRepositories, ) { $this->writeVaultAccRepositories = iterator_to_array($writeVaultAccRepositories); } public function __invoke( AddAccRequest $request, AddAccPresenterInterface $presenter, ): void { try { if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_ACC_RW)) { $this->error( "User doesn't have sufficient rights to access additional connector configurations", ['user_id' => $this->user->getId()] ); $presenter->presentResponse( new ForbiddenResponse(AccException::accessNotAllowed()) ); return; } $request->pollers = array_unique($request->pollers); $this->validator->validateRequestOrFail($request); $newAcc = $this->factory->createNewAcc( name: $request->name, type: Type::from($request->type), createdBy: $this->user->getId(), parameters: $request->parameters, description: $request->description, ); if ($this->flags->isEnabled('vault_gorgone')) { $parameters = $newAcc->getParameters(); foreach ($this->writeVaultAccRepositories as $repository) { if ($repository->isValidFor($newAcc->getType())) { $parameters = $repository->saveCredentialInVault($newAcc->getParameters()); } } $newAcc = $this->factory->createNewAcc( name: $newAcc->getName(), type: $newAcc->getType(), createdBy: $newAcc->getCreatedBy(), parameters: $parameters->getData(), description: $newAcc->getDescription(), ); } $accId = $this->addAcc($newAcc, $request->pollers); if (null === $additionalConnector = $this->readAccRepository->find($accId)) { throw AccException::errorWhileRetrievingObject(); } $pollers = $this->readAccRepository->findPollersByAccId($accId); $presenter->presentResponse($this->createResponse($additionalConnector, $pollers)); } catch (AssertionFailedException|\InvalidArgumentException $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); $presenter->presentResponse(new InvalidArgumentResponse($ex)); } catch (\Throwable $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); $presenter->presentResponse(new ErrorResponse( $ex instanceof AccException ? $ex : AccException::addAcc() )); } } /** * @param NewAcc $acc * @param int[] $pollers * * @throws \Throwable * * @return int */ private function addAcc(NewAcc $acc, array $pollers): int { try { $this->dataStorageEngine->startTransaction(); $newAccId = $this->writeAccRepository->add($acc); $this->writeAccRepository->linkToPollers($newAccId, $pollers); $this->dataStorageEngine->commitTransaction(); } catch (\Throwable $ex) { $this->error("Rollback of 'AddAcc' transaction."); $this->dataStorageEngine->rollbackTransaction(); throw $ex; } return $newAccId; } /** * @param Acc $acc * @param Poller[] $pollers * * @return AddAccResponse */ private function createResponse(Acc $acc, array $pollers): AddAccResponse { return new AddAccResponse( id: $acc->getId(), type: $acc->getType(), name: $acc->getName(), description: $acc->getDescription(), createdBy: ['id' => $this->user->getId(), 'name' => $this->user->getName()], updatedBy: ['id' => $this->user->getId(), 'name' => $this->user->getName()], createdAt: $acc->getCreatedAt(), updatedAt: $acc->getCreatedAt(), parameters: $acc->getParameters()->getDataWithoutCredentials(), pollers: $pollers ); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AdditionalConnectorConfiguration/Application/UseCase/AddAcc/Validator.php
centreon/src/Core/AdditionalConnectorConfiguration/Application/UseCase/AddAcc/Validator.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\AdditionalConnectorConfiguration\Application\UseCase\AddAcc; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Log\LoggerTrait; use Core\AdditionalConnectorConfiguration\Application\Exception\AccException; use Core\AdditionalConnectorConfiguration\Application\Repository\ReadAccRepositoryInterface; use Core\AdditionalConnectorConfiguration\Application\Validation\TypeDataValidatorInterface; use Core\AdditionalConnectorConfiguration\Domain\Model\Poller; use Core\AdditionalConnectorConfiguration\Domain\Model\Type; use Core\Common\Domain\TrimmedString; use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use ValueError; class Validator { use LoggerTrait; /** @var TypeDataValidatorInterface[] */ private array $parametersValidators = []; /** * @param ReadAccRepositoryInterface $readAccRepository * @param ContactInterface $user * @param ReadAccessGroupRepositoryInterface $readAccessGroupRepository * @param ReadMonitoringServerRepositoryInterface $readMonitoringServerRepository * @param \Traversable<TypeDataValidatorInterface> $parametersValidators */ public function __construct( private readonly ReadAccRepositoryInterface $readAccRepository, private readonly ContactInterface $user, private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository, private readonly ReadMonitoringServerRepositoryInterface $readMonitoringServerRepository, \Traversable $parametersValidators, ) { $this->parametersValidators = iterator_to_array($parametersValidators); } /** * @param AddAccRequest $request * * @throws AccException|ValueError */ public function validateRequestOrFail(AddAccRequest $request): void { $this->validateNameOrFail($request); $this->validatePollersOrFail($request); $this->validateTypeOrFail($request); $this->validateParametersOrFail($request); } /** * Validate that ACC name is not already used. * * @param AddAccRequest $request * * @throws AccException */ public function validateNameOrFail(AddAccRequest $request): void { $trimmedName = new TrimmedString($request->name); if ($this->readAccRepository->existsByName($trimmedName)) { throw AccException::nameAlreadyExists($trimmedName->value); } } /** * Validate that requesting user has access to pollers. * * @param AddAccRequest $request * * @throws AccException */ public function validatePollersOrFail(AddAccRequest $request): void { if ($request->pollers === []) { throw AccException::arrayCanNotBeEmpty('pollers'); } $invalidPollers = []; foreach ($request->pollers as $pollerId) { $isPollerIdValid = false; if ($this->user->isAdmin()) { $isPollerIdValid = $this->readMonitoringServerRepository->exists($pollerId); } else { $accessGroups = $this->readAccessGroupRepository->findByContact($this->user); $isPollerIdValid = $this->readMonitoringServerRepository->existsByAccessGroups($pollerId, $accessGroups); } if ($isPollerIdValid === false) { $invalidPollers[] = $pollerId; } } if ($invalidPollers !== []) { throw AccException::idsDoNotExist('pollers', $invalidPollers); } } /** * Check that pollers are not already linked to same ACC type. * * @param AddAccRequest $request * * @throws AccException|ValueError */ public function validateTypeOrFail(AddAccRequest $request): void { $type = Type::from($request->type); $pollers = $this->readAccRepository->findPollersByType($type); $pollerIds = array_map(fn (Poller $poller) => $poller->id, $pollers); if ([] !== $invalidPollers = array_intersect($pollerIds, $request->pollers)) { throw AccException::alreadyAssociatedPollers($type, $invalidPollers); } } public function validateParametersOrFail(AddAccRequest $request): void { foreach ($this->parametersValidators as $validator) { if ($validator->isValidFor(Type::from($request->type))) { $validator->validateParametersOrFail($request); } } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AdditionalConnectorConfiguration/Application/UseCase/AddAcc/AddAccRequest.php
centreon/src/Core/AdditionalConnectorConfiguration/Application/UseCase/AddAcc/AddAccRequest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\AdditionalConnectorConfiguration\Application\UseCase\AddAcc; final class AddAccRequest { public string $name = ''; public string $type = ''; public ?string $description = null; /** @var int[] */ public array $pollers = []; /** @var array<string,mixed> */ public array $parameters = []; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AdditionalConnectorConfiguration/Application/UseCase/AddAcc/AddAccPresenterInterface.php
centreon/src/Core/AdditionalConnectorConfiguration/Application/UseCase/AddAcc/AddAccPresenterInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\AdditionalConnectorConfiguration\Application\UseCase\AddAcc; use Core\Application\Common\UseCase\ResponseStatusInterface; interface AddAccPresenterInterface { public function presentResponse(AddAccResponse|ResponseStatusInterface $data): void; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AdditionalConnectorConfiguration/Application/UseCase/FindAcc/FindAccPresenterInterface.php
centreon/src/Core/AdditionalConnectorConfiguration/Application/UseCase/FindAcc/FindAccPresenterInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\AdditionalConnectorConfiguration\Application\UseCase\FindAcc; use Core\Application\Common\UseCase\ResponseStatusInterface; interface FindAccPresenterInterface { public function presentResponse(FindAccResponse|ResponseStatusInterface $data): void; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AdditionalConnectorConfiguration/Application/UseCase/FindAcc/FindAccResponse.php
centreon/src/Core/AdditionalConnectorConfiguration/Application/UseCase/FindAcc/FindAccResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\AdditionalConnectorConfiguration\Application\UseCase\FindAcc; use Core\AdditionalConnectorConfiguration\Domain\Model\Poller; use Core\AdditionalConnectorConfiguration\Domain\Model\Type; final class FindAccResponse { /** * @param int $id * @param Type $type * @param string $name * @param string|null $description * @param null|array{id:int,name:string} $createdBy * @param null|array{id:int,name:string} $updatedBy * @param \DateTimeImmutable $createdAt * @param \DateTimeImmutable $updatedAt * @param array<string,mixed> $parameters * @param Poller[] $pollers */ public function __construct( public int $id = 0, public Type $type = Type::VMWARE_V6, public string $name = '', public ?string $description = null, public ?array $createdBy = null, public ?array $updatedBy = null, public \DateTimeImmutable $createdAt = new \DateTimeImmutable(), public \DateTimeImmutable $updatedAt = new \DateTimeImmutable(), public array $parameters = [], public array $pollers = [], ) { } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AdditionalConnectorConfiguration/Application/UseCase/FindAcc/FindAcc.php
centreon/src/Core/AdditionalConnectorConfiguration/Application/UseCase/FindAcc/FindAcc.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\AdditionalConnectorConfiguration\Application\UseCase\FindAcc; use Centreon\Domain\Contact\Contact; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Log\LoggerTrait; use Core\AdditionalConnectorConfiguration\Application\Exception\AccException; use Core\AdditionalConnectorConfiguration\Application\Repository\ReadAccRepositoryInterface; use Core\AdditionalConnectorConfiguration\Domain\Model\Acc; use Core\AdditionalConnectorConfiguration\Domain\Model\Poller; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\ForbiddenResponse; use Core\Application\Common\UseCase\NotFoundResponse; use Core\Contact\Application\Repository\ReadContactRepositoryInterface; use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; final class FindAcc { use LoggerTrait; public function __construct( private readonly ReadAccRepositoryInterface $readAccRepository, private readonly ReadMonitoringServerRepositoryInterface $readMonitoringServerRepository, private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository, private readonly ReadContactRepositoryInterface $readContactRepository, private readonly ContactInterface $user, ) { } public function __invoke( int $id, FindAccPresenterInterface $presenter, ): void { try { if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_ACC_RW)) { $this->error( "User doesn't have sufficient rights to read additional connector configurations", ['user_id' => $this->user->getId()] ); $presenter->presentResponse( new ForbiddenResponse(AccException::accessNotAllowed()) ); return; } if (null === $acc = $this->readAccRepository->find($id)) { $presenter->presentResponse( new NotFoundResponse('Additional Connector Configuration') ); return; } $pollers = $this->readAccRepository->findPollersByAccId($id); if (! $this->user->isAdmin()) { $pollerIds = array_map( static fn (Poller $poller): int => $poller->id, $pollers ); $accessGroups = $this->readAccessGroupRepository->findByContact($this->user); $validPollerIds = $this->readMonitoringServerRepository->existByAccessGroups($pollerIds, $accessGroups); if (array_diff($pollerIds, $validPollerIds) !== []) { $presenter->presentResponse( new NotFoundResponse('Additional Connector') ); return; } } $presenter->presentResponse($this->createResponse($acc, $pollers)); } catch (\Throwable $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); $presenter->presentResponse(new ErrorResponse( $ex instanceof AccException ? $ex : AccException::errorWhileRetrievingObject() )); } } /** * @param Acc $acc * @param Poller[] $pollers * * @return FindAccResponse */ private function createResponse(Acc $acc, array $pollers): FindAccResponse { $userIds = []; if ($acc->getCreatedBy() !== null) { $userIds[] = $acc->getCreatedBy(); } if ($acc->getUpdatedBy() !== null) { $userIds[] = $acc->getUpdatedBy(); } $users = $this->readContactRepository->findNamesByIds(...$userIds); return new FindAccResponse( id: $acc->getId(), type: $acc->getType(), name: $acc->getName(), description: $acc->getDescription(), createdBy: $acc->getCreatedBy() ? $users[$acc->getCreatedBy()] : null, updatedBy: $acc->getUpdatedBy() ? $users[$acc->getUpdatedBy()] : null, createdAt: $acc->getCreatedAt(), updatedAt: $acc->getUpdatedAt(), parameters: $acc->getParameters()->getDataWithoutCredentials(), pollers: $pollers ); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AdditionalConnectorConfiguration/Application/UseCase/FindAccs/FindAccs.php
centreon/src/Core/AdditionalConnectorConfiguration/Application/UseCase/FindAccs/FindAccs.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\AdditionalConnectorConfiguration\Application\UseCase\FindAccs; use Centreon\Domain\Contact\Contact; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Log\LoggerTrait; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Centreon\Infrastructure\RequestParameters\RequestParametersTranslatorException; use Core\AdditionalConnectorConfiguration\Application\Exception\AccException; use Core\AdditionalConnectorConfiguration\Application\Repository\ReadAccRepositoryInterface; use Core\AdditionalConnectorConfiguration\Domain\Model\Acc; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\ForbiddenResponse; use Core\Contact\Application\Repository\ReadContactRepositoryInterface; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; final class FindAccs { use LoggerTrait; public function __construct( private readonly RequestParametersInterface $requestParameters, private readonly ReadAccRepositoryInterface $readAccRepository, private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository, private readonly ReadContactRepositoryInterface $readContactRepository, private readonly ContactInterface $user, ) { } public function __invoke( FindAccsPresenterInterface $presenter, ): void { try { if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_ACC_RW)) { $this->error( "User doesn't have sufficient rights to access additional connector configurations", ['user_id' => $this->user->getId()] ); $presenter->presentResponse( new ForbiddenResponse(AccException::accessNotAllowed()) ); return; } if ($this->user->isAdmin()) { $accs = $this->readAccRepository->findByRequestParameters($this->requestParameters); } else { $accessGroups = $this->readAccessGroupRepository->findByContact($this->user); $accs = $this->readAccRepository->findByRequestParametersAndAccessGroups($this->requestParameters, $accessGroups); } $presenter->presentResponse($this->createResponse($accs)); } catch (RequestParametersTranslatorException $ex) { $presenter->presentResponse(new ErrorResponse($ex->getMessage())); $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); } catch (\Throwable $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); $presenter->presentResponse(new ErrorResponse( $ex instanceof AccException ? $ex : AccException::findAccs() )); } } /** * @param Acc[] $accs * * @return FindAccsResponse */ private function createResponse(array $accs): FindAccsResponse { $accDtos = []; foreach ($accs as $acc) { $userIds = []; if ($acc->getCreatedBy() !== null) { $userIds[] = $acc->getCreatedBy(); } if ($acc->getUpdatedBy() !== null) { $userIds[] = $acc->getUpdatedBy(); } $users = $this->readContactRepository->findNamesByIds(...$userIds); $accDtos[] = new AccDto( id: $acc->getId(), type: $acc->getType(), name: $acc->getName(), description: $acc->getDescription(), createdBy: $acc->getCreatedBy() ? $users[$acc->getCreatedBy()] : null, updatedBy: $acc->getUpdatedBy() ? $users[$acc->getUpdatedBy()] : null, createdAt: $acc->getCreatedAt(), updatedAt: $acc->getUpdatedAt() ); } return new FindAccsResponse($accDtos); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AdditionalConnectorConfiguration/Application/UseCase/FindAccs/FindAccsResponse.php
centreon/src/Core/AdditionalConnectorConfiguration/Application/UseCase/FindAccs/FindAccsResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\AdditionalConnectorConfiguration\Application\UseCase\FindAccs; final class FindAccsResponse { /** * @param AccDto[] $accs */ public function __construct( public array $accs, ) { } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AdditionalConnectorConfiguration/Application/UseCase/FindAccs/FindAccsPresenterInterface.php
centreon/src/Core/AdditionalConnectorConfiguration/Application/UseCase/FindAccs/FindAccsPresenterInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\AdditionalConnectorConfiguration\Application\UseCase\FindAccs; use Core\Application\Common\UseCase\ResponseStatusInterface; interface FindAccsPresenterInterface { public function presentResponse(FindAccsResponse|ResponseStatusInterface $data): void; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AdditionalConnectorConfiguration/Application/UseCase/FindAccs/AccDto.php
centreon/src/Core/AdditionalConnectorConfiguration/Application/UseCase/FindAccs/AccDto.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\AdditionalConnectorConfiguration\Application\UseCase\FindAccs; use Core\AdditionalConnectorConfiguration\Domain\Model\Type; final class AccDto { /** * @param int $id * @param Type $type * @param string $name * @param string|null $description * @param null|array{id:int,name:string} $createdBy * @param null|array{id:int,name:string} $updatedBy * @param \DateTimeImmutable $createdAt * @param \DateTimeImmutable $updatedAt */ public function __construct( public int $id = 0, public Type $type = Type::VMWARE_V6, public string $name = '', public ?string $description = null, public ?array $createdBy = null, public ?array $updatedBy = null, public \DateTimeImmutable $createdAt = new \DateTimeImmutable(), public \DateTimeImmutable $updatedAt = new \DateTimeImmutable(), ) { } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AdditionalConnectorConfiguration/Application/UseCase/UpdateAcc/UpdateAcc.php
centreon/src/Core/AdditionalConnectorConfiguration/Application/UseCase/UpdateAcc/UpdateAcc.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\AdditionalConnectorConfiguration\Application\UseCase\UpdateAcc; use Assert\AssertionFailedException; use Centreon\Domain\Contact\Contact; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Log\LoggerTrait; use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface; use Core\AdditionalConnectorConfiguration\Application\Exception\AccException; use Core\AdditionalConnectorConfiguration\Application\Factory\AccFactory; use Core\AdditionalConnectorConfiguration\Application\Repository\ReadAccRepositoryInterface; use Core\AdditionalConnectorConfiguration\Application\Repository\ReadVaultAccRepositoryInterface; use Core\AdditionalConnectorConfiguration\Application\Repository\WriteAccRepositoryInterface; use Core\AdditionalConnectorConfiguration\Application\Repository\WriteVaultAccRepositoryInterface; use Core\AdditionalConnectorConfiguration\Domain\Model\Acc; use Core\AdditionalConnectorConfiguration\Domain\Model\Poller; 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\Infrastructure\FeatureFlags; use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; final class UpdateAcc { use LoggerTrait; /** @var WriteVaultAccRepositoryInterface[] */ private array $writeVaultAccRepositories = []; /** @var ReadVaultAccRepositoryInterface[] */ private array $readVaultAccRepositories = []; /** * @param ReadAccRepositoryInterface $readAccRepository * @param WriteAccRepositoryInterface $writeAccRepository * @param ReadAccessGroupRepositoryInterface $readAccessGroupRepository, * @param ReadMonitoringServerRepositoryInterface $readMonitoringServerRepository, * @param Validator $validator * @param AccFactory $factory * @param DataStorageEngineInterface $dataStorageEngine * @param ContactInterface $user * @param FeatureFlags $flags * @param \Traversable<WriteVaultAccRepositoryInterface> $writeVaultAccRepositories * @param \Traversable<ReadVaultAccRepositoryInterface> $readVaultAccRepositories */ public function __construct( private readonly ReadAccRepositoryInterface $readAccRepository, private readonly WriteAccRepositoryInterface $writeAccRepository, private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository, private readonly ReadMonitoringServerRepositoryInterface $readMonitoringServerRepository, private readonly Validator $validator, private readonly AccFactory $factory, private readonly DataStorageEngineInterface $dataStorageEngine, private readonly ContactInterface $user, private readonly FeatureFlags $flags, \Traversable $writeVaultAccRepositories, \Traversable $readVaultAccRepositories, ) { $this->writeVaultAccRepositories = iterator_to_array($writeVaultAccRepositories); $this->readVaultAccRepositories = iterator_to_array($readVaultAccRepositories); } public function __invoke( UpdateAccRequest $request, PresenterInterface $presenter, ): void { try { if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_ACC_RW)) { $this->error( "User doesn't have sufficient rights to access additional connector configurations", ['user_id' => $this->user->getId()] ); $presenter->setResponseStatus( new ForbiddenResponse(AccException::accessNotAllowed()) ); return; } if (null === $acc = $this->getAcc($request->id)) { $presenter->setResponseStatus( new NotFoundResponse('Additional Connector Configuration') ); return; } $request->pollers = array_unique($request->pollers); $this->validator->validateRequestOrFail($request, $acc); $updatedAcc = $this->updateAcc($request, $acc); if ($this->flags->isEnabled('vault_gorgone')) { $parameters = $updatedAcc->getParameters(); foreach ($this->writeVaultAccRepositories as $repository) { if ($repository->isValidFor($updatedAcc->getType())) { $repository->deleteFromVault($acc); $parameters = $repository->saveCredentialInVault($updatedAcc->getParameters()); } } $vaultedAcc = $this->factory->createAcc( id: $updatedAcc->getId(), name: $updatedAcc->getName(), type: $updatedAcc->getType(), createdBy: $updatedAcc->getCreatedBy(), createdAt: $updatedAcc->getCreatedAt(), updatedBy: $updatedAcc->getUpdatedBy(), updatedAt: $updatedAcc->getUpdatedAt(), description: $updatedAcc->getDescription(), parameters: $parameters->getData(), ); $updatedAcc = $vaultedAcc; } $this->update($updatedAcc, $request->pollers); $presenter->setResponseStatus(new NoContentResponse()); } catch (AssertionFailedException|\InvalidArgumentException $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); $presenter->setResponseStatus(new InvalidArgumentResponse($ex)); } catch (\Throwable $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); $presenter->setResponseStatus(new ErrorResponse( $ex instanceof AccException ? $ex : AccException::updateAcc() )); } } /** * Get ACC based on user rights. * * @param int $id * * @throws \Throwable * * @return null|Acc */ private function getAcc(int $id): null|Acc { if (null === $acc = $this->readAccRepository->find($id)) { return null; } if (! $this->user->isAdmin()) { $pollerIds = array_map( static fn (Poller $poller): int => $poller->id, $this->readAccRepository->findPollersByAccId($acc->getId()) ); $accessGroups = $this->readAccessGroupRepository->findByContact($this->user); $validPollerIds = $this->readMonitoringServerRepository->existByAccessGroups($pollerIds, $accessGroups); if (array_diff($pollerIds, $validPollerIds) !== []) { return null; } } return $acc; } /** * @param UpdateAccRequest $request * @param Acc $acc * * @throws AssertionFailedException * * @return Acc */ private function updateAcc(UpdateAccRequest $request, Acc $acc): Acc { $acc = $this->retrieveCredentials($acc); return $this->factory->updateAcc( acc: $acc, name: $request->name, updatedBy: $this->user->getId(), description: $request->description, parameters: $request->parameters ); } /** * @param Acc $acc * * @throws \Throwable * * @return Acc */ private function retrieveCredentials(Acc $acc): Acc { $parameters = $acc->getParameters(); foreach ($this->readVaultAccRepositories as $repository) { if ($repository->isValidFor($acc->getType())) { $parameters = $repository->getCredentialsFromVault($acc->getParameters()); } } return $this->factory->createAcc( id: $acc->getId(), name: $acc->getName(), type: $acc->getType(), createdBy: $acc->getCreatedBy(), createdAt: $acc->getCreatedAt(), updatedBy: $acc->getUpdatedBy(), updatedAt: $acc->getUpdatedAt(), parameters: $parameters->getDecryptedData(), description: $acc->getDescription(), ); } /** * @param Acc $acc * @param int[] $pollers * * @throws \Throwable */ private function update(Acc $acc, array $pollers): void { try { $this->dataStorageEngine->startTransaction(); $this->writeAccRepository->update($acc); $this->writeAccRepository->removePollers($acc->getId()); $this->writeAccRepository->linkToPollers( $acc->getId(), $pollers ); $this->dataStorageEngine->commitTransaction(); } catch (\Throwable $ex) { $this->error("Rollback of 'UpdateAcc' transaction."); $this->dataStorageEngine->rollbackTransaction(); throw $ex; } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AdditionalConnectorConfiguration/Application/UseCase/UpdateAcc/UpdateAccRequest.php
centreon/src/Core/AdditionalConnectorConfiguration/Application/UseCase/UpdateAcc/UpdateAccRequest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\AdditionalConnectorConfiguration\Application\UseCase\UpdateAcc; final class UpdateAccRequest { public int $id = 0; public string $name = ''; public string $type = ''; public ?string $description = null; /** @var int[] */ public array $pollers = []; /** @var array<string,mixed> */ public array $parameters = []; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AdditionalConnectorConfiguration/Application/UseCase/UpdateAcc/Validator.php
centreon/src/Core/AdditionalConnectorConfiguration/Application/UseCase/UpdateAcc/Validator.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\AdditionalConnectorConfiguration\Application\UseCase\UpdateAcc; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Log\LoggerTrait; use Core\AdditionalConnectorConfiguration\Application\Exception\AccException; use Core\AdditionalConnectorConfiguration\Application\Repository\ReadAccRepositoryInterface; use Core\AdditionalConnectorConfiguration\Application\Validation\TypeDataValidatorInterface; use Core\AdditionalConnectorConfiguration\Domain\Model\Acc; use Core\AdditionalConnectorConfiguration\Domain\Model\Poller; use Core\AdditionalConnectorConfiguration\Domain\Model\Type; use Core\Common\Domain\TrimmedString; use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use ValueError; class Validator { use LoggerTrait; /** @var TypeDataValidatorInterface[] */ private array $parametersValidators = []; /** * @param ReadAccRepositoryInterface $readAccRepository * @param ContactInterface $user * @param ReadAccessGroupRepositoryInterface $readAccessGroupRepository * @param ReadMonitoringServerRepositoryInterface $readMonitoringServerRepository * @param \Traversable<TypeDataValidatorInterface> $parametersValidators */ public function __construct( private readonly ReadAccRepositoryInterface $readAccRepository, private readonly ContactInterface $user, private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository, private readonly ReadMonitoringServerRepositoryInterface $readMonitoringServerRepository, \Traversable $parametersValidators, ) { $this->parametersValidators = iterator_to_array($parametersValidators); } /** * @param UpdateAccRequest $request * @param Acc $acc * * @throws AccException|ValueError */ public function validateRequestOrFail(UpdateAccRequest $request, Acc $acc): void { $this->validateNameOrFail($request, $acc); $this->validateTypeOrFail($request, $acc); $this->validatePollersOrFail($request, $acc); $this->validateParametersOrFail($request); } /** * Validate that ACC name is not already used. * * @param UpdateAccRequest $request * @param Acc $acc * * @throws AccException */ public function validateNameOrFail(UpdateAccRequest $request, Acc $acc): void { $trimmedName = new TrimmedString($request->name); if ($acc->getName() !== $trimmedName->value && $this->readAccRepository->existsByName($trimmedName)) { throw AccException::nameAlreadyExists($trimmedName->value); } } /** * Check that pollers are not already linked to same ACC type. * * @param UpdateAccRequest $request * @param Acc $acc * * @throws AccException|ValueError */ public function validateTypeOrFail(UpdateAccRequest $request, Acc $acc): void { $type = Type::from($request->type); if ($type->name !== $acc->getType()->name) { throw AccException::typeChangeNotAllowed(); } } /** * Validate that requesting user has access to pollers. * * @param UpdateAccRequest $request * @param Acc $acc * * @throws AccException */ public function validatePollersOrFail(UpdateAccRequest $request, Acc $acc): void { if ($request->pollers === []) { throw AccException::arrayCanNotBeEmpty('pollers'); } // Check pollers have valid IDs according to user permissions. $invalidPollers = []; foreach ($request->pollers as $pollerId) { $isPollerIdValid = false; if ($this->user->isAdmin()) { $isPollerIdValid = $this->readMonitoringServerRepository->exists($pollerId); } else { $accessGroups = $this->readAccessGroupRepository->findByContact($this->user); $isPollerIdValid = $this->readMonitoringServerRepository->existsByAccessGroups($pollerId, $accessGroups); } if ($isPollerIdValid === false) { $invalidPollers[] = $pollerId; } } if ($invalidPollers !== []) { throw AccException::idsDoNotExist('pollers', $invalidPollers); } // Check pollers are not already associated to an ACC of same type. $actualPollers = $this->readAccRepository->findPollersByAccId($acc->getId()); $actualPollerIds = array_map(fn (Poller $poller) => $poller->id, $actualPollers); $unavailablePollers = $this->readAccRepository->findPollersByType($acc->getType()); $unavailablePollerIds = array_map(fn (Poller $poller) => $poller->id, $unavailablePollers); $unavailablePollerIds = array_diff($unavailablePollerIds, $actualPollerIds); if ([] !== $invalidPollers = array_intersect($unavailablePollerIds, $request->pollers)) { throw AccException::alreadyAssociatedPollers($acc->getType(), $invalidPollers); } } public function validateParametersOrFail(UpdateAccRequest $request): void { foreach ($this->parametersValidators as $validator) { if ($validator->isValidFor(Type::from($request->type))) { $validator->validateParametersOrFail($request); } } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AdditionalConnectorConfiguration/Application/Validation/VmWareV6DataValidator.php
centreon/src/Core/AdditionalConnectorConfiguration/Application/Validation/VmWareV6DataValidator.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\AdditionalConnectorConfiguration\Application\Validation; use Core\AdditionalConnectorConfiguration\Application\Exception\AccException; use Core\AdditionalConnectorConfiguration\Application\UseCase\AddAcc\AddAccRequest; use Core\AdditionalConnectorConfiguration\Application\UseCase\UpdateAcc\UpdateAccRequest; use Core\AdditionalConnectorConfiguration\Domain\Model\Type; use Core\AdditionalConnectorConfiguration\Domain\Model\VmWareV6\VmWareV6Parameters; /** * @phpstan-import-type _VmWareV6Parameters from VmWareV6Parameters */ class VmWareV6DataValidator implements TypeDataValidatorInterface { /** * @inheritDoc */ public function isValidFor(Type $type): bool { return $type === Type::VMWARE_V6; } /** * @inheritDoc */ public function validateParametersOrFail(AddAccRequest|UpdateAccRequest $request): void { /** @var _VmWareV6Parameters $parameters */ $parameters = $request->parameters; if ($parameters['vcenters'] === []) { throw AccException::arrayCanNotBeEmpty('parameters.vcenters[]'); } $vcenterNames = array_map(fn (array $vcenter) => $vcenter['name'], $parameters['vcenters']); if (count(array_unique($vcenterNames)) !== count($vcenterNames)) { throw AccException::duplicatesNotAllowed('parameters.vcenters[].name'); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AdditionalConnectorConfiguration/Application/Validation/TypeDataValidatorInterface.php
centreon/src/Core/AdditionalConnectorConfiguration/Application/Validation/TypeDataValidatorInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\AdditionalConnectorConfiguration\Application\Validation; use Centreon\Domain\Common\Assertion\AssertionException; use Core\AdditionalConnectorConfiguration\Application\Exception\AccException; use Core\AdditionalConnectorConfiguration\Application\UseCase\AddAcc\AddAccRequest; use Core\AdditionalConnectorConfiguration\Application\UseCase\UpdateAcc\UpdateAccRequest; use Core\AdditionalConnectorConfiguration\Domain\Model\Type; interface TypeDataValidatorInterface { /** * @param Type $type * * @return bool */ public function isValidFor(Type $type): bool; /** * @param AddAccRequest|UpdateAccRequest $request * * @throws AccException|AssertionException */ public function validateParametersOrFail(AddAccRequest|UpdateAccRequest $request): 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/AdditionalConnectorConfiguration/Application/Exception/AccException.php
centreon/src/Core/AdditionalConnectorConfiguration/Application/Exception/AccException.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\AdditionalConnectorConfiguration\Application\Exception; use Core\AdditionalConnectorConfiguration\Domain\Model\Type; class AccException extends \Exception { public const CODE_CONFLICT = 1; public static function addAcc(): self { return new self(_('Error while adding an additional configuration')); } public static function updateAcc(): self { return new self(_('Error while updating an additional configuration')); } public static function deleteAcc(): self { return new self(_('Error while deleting an additional configuration')); } public static function findAccs(): self { return new self(_('Error while searching for additional configurations')); } public static function accessNotAllowed(): self { return new self(_('You are not allowed to access additional configurations')); } public static function unsufficientRights(): self { return new self(_("You don't have sufficient permissions for this action")); } /** * @param string $propertyName * @param int[] $propertyValues * * @return self */ public static function idsDoNotExist(string $propertyName, array $propertyValues): self { return new self( sprintf( _("The %s does not exist with ID(s) '%s'"), $propertyName, implode(',', $propertyValues) ), self::CODE_CONFLICT ); } /** * @param Type $type * @param int[] $invalidPollers * * @return self */ public static function alreadyAssociatedPollers(Type $type, array $invalidPollers): self { return new self( sprintf( _("An additional configuration of type '%s' is already associated with poller ID(s) '%s'"), $type->value, implode(',', $invalidPollers) ), self::CODE_CONFLICT ); } public static function duplicatesNotAllowed(string $propertyName): self { return new self( sprintf( _("Duplicates not allowed for property '%s'"), $propertyName ), self::CODE_CONFLICT ); } public static function arrayCanNotBeEmpty(string $propertyName): self { return new self( sprintf( _("'%s' must contain at least one element"), $propertyName ), self::CODE_CONFLICT ); } public static function errorWhileRetrievingObject(): self { return new self(_('Error while retrieving an additional configuration')); } public static function nameAlreadyExists(string $name): self { return new self( sprintf(_("The additional configuration name '%s' already exists"), $name), self::CODE_CONFLICT ); } public static function typeChangeNotAllowed(): self { return new self( _('Changing type of an existing additional connector configuration is 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/AdditionalConnectorConfiguration/Application/Repository/ReadVaultAccRepositoryInterface.php
centreon/src/Core/AdditionalConnectorConfiguration/Application/Repository/ReadVaultAccRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\AdditionalConnectorConfiguration\Application\Repository; use Core\AdditionalConnectorConfiguration\Domain\Model\AccParametersInterface; use Core\AdditionalConnectorConfiguration\Domain\Model\Type; interface ReadVaultAccRepositoryInterface { public function isValidFor(Type $type): bool; /** * Retrieve credentials values in vault and return the parameters updated with values. * * @param AccParametersInterface $parameters * * @throws \Throwable * * @return AccParametersInterface */ public function getCredentialsFromVault(AccParametersInterface $parameters): AccParametersInterface; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AdditionalConnectorConfiguration/Application/Repository/ReadAccRepositoryInterface.php
centreon/src/Core/AdditionalConnectorConfiguration/Application/Repository/ReadAccRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Core\AdditionalConnectorConfiguration\Application\Repository; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Core\AdditionalConnectorConfiguration\Domain\Model\Acc; use Core\AdditionalConnectorConfiguration\Domain\Model\Poller; use Core\AdditionalConnectorConfiguration\Domain\Model\Type; use Core\Common\Domain\TrimmedString; use Core\Security\AccessGroup\Domain\Model\AccessGroup; interface ReadAccRepositoryInterface { /** * Determine if an Additional Connector (ACC) exists by its name. * * @param TrimmedString $name * * @throws \Throwable * * @return bool */ public function existsByName(TrimmedString $name): bool; /** * Find an Additional Connector (ACC). * * @param int $accId * * @throws \Throwable * * @return ?Acc */ public function find(int $accId): ?Acc; /** * Find alls Additional Connectors (ACCs). * * @throws \Throwable * * @return Acc[] */ public function findAll(): array; /** * Find all the pollers associated with any ACC of the specified type. * * @param Type $type * * @throws \Throwable * * @return Poller[] */ public function findPollersByType(Type $type): array; /** * Find all the pollers associated with an ACC ID. * * @param int $accId * * @throws \Throwable * * @return Poller[] */ public function findPollersByAccId(int $accId): array; /** * Find all ACC with request parameters. * * @param RequestParametersInterface $requestParameters * * @throws \Throwable * * @return Acc[] */ public function findByRequestParameters(RequestParametersInterface $requestParameters): array; /** * Find all ACC with request parameters. * * @param RequestParametersInterface $requestParameters * @param AccessGroup[] $accessGroups * * @throws \Throwable * * @return Acc[] */ public function findByRequestParametersAndAccessGroups( RequestParametersInterface $requestParameters, array $accessGroups, ): array; /** * Find an ACC for the given poller and type. * * @param int $pollerId * @param string $type * * @throws \Throwable * * @return Acc|null */ public function findByPollerAndType(int $pollerId, string $type): ?Acc; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false