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/ResourceAccess/Domain/Model/DatasetFilter/Providers/MetaServiceFilterType.php | centreon/src/Core/ResourceAccess/Domain/Model/DatasetFilter/Providers/MetaServiceFilterType.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ResourceAccess\Domain\Model\DatasetFilter\Providers;
use Core\ResourceAccess\Domain\Model\DatasetFilter\AbstractDatasetFilterType;
class MetaServiceFilterType extends AbstractDatasetFilterType
{
public const TYPE_NAME = 'meta_service';
protected string $name = self::TYPE_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/ResourceAccess/Domain/Model/DatasetFilter/Providers/HostCategoryFilterType.php | centreon/src/Core/ResourceAccess/Domain/Model/DatasetFilter/Providers/HostCategoryFilterType.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ResourceAccess\Domain\Model\DatasetFilter\Providers;
use Core\ResourceAccess\Domain\Model\DatasetFilter\AbstractDatasetFilterType;
class HostCategoryFilterType extends AbstractDatasetFilterType
{
public const TYPE_NAME = 'host_category';
protected string $name = self::TYPE_NAME;
protected array $possibleChildren = [
HostFilterType::TYPE_NAME,
ServiceGroupFilterType::TYPE_NAME,
ServiceCategoryFilterType::TYPE_NAME,
ServiceFilterType::TYPE_NAME,
HostGroupFilterType::TYPE_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/ResourceAccess/Domain/Model/DatasetFilter/Providers/HostGroupFilterType.php | centreon/src/Core/ResourceAccess/Domain/Model/DatasetFilter/Providers/HostGroupFilterType.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ResourceAccess\Domain\Model\DatasetFilter\Providers;
use Core\ResourceAccess\Domain\Model\DatasetFilter\AbstractDatasetFilterType;
class HostGroupFilterType extends AbstractDatasetFilterType
{
public const TYPE_NAME = 'hostgroup';
protected string $name = self::TYPE_NAME;
protected array $possibleChildren = [
HostFilterType::TYPE_NAME,
HostCategoryFilterType::TYPE_NAME,
ServiceGroupFilterType::TYPE_NAME,
ServiceCategoryFilterType::TYPE_NAME,
ServiceFilterType::TYPE_NAME,
];
/**
* @inheritDoc
*/
public function canResourceIdsBeEmpty(): bool
{
return true;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Domain/Model/DatasetFilter/Providers/ServiceFilterType.php | centreon/src/Core/ResourceAccess/Domain/Model/DatasetFilter/Providers/ServiceFilterType.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ResourceAccess\Domain\Model\DatasetFilter\Providers;
use Core\ResourceAccess\Domain\Model\DatasetFilter\AbstractDatasetFilterType;
class ServiceFilterType extends AbstractDatasetFilterType
{
public const TYPE_NAME = 'service';
protected string $name = self::TYPE_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/ResourceAccess/Domain/Model/DatasetFilter/Providers/ImageFolderFilterType.php | centreon/src/Core/ResourceAccess/Domain/Model/DatasetFilter/Providers/ImageFolderFilterType.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ResourceAccess\Domain\Model\DatasetFilter\Providers;
use Core\ResourceAccess\Domain\Model\DatasetFilter\AbstractDatasetFilterType;
final class ImageFolderFilterType extends AbstractDatasetFilterType
{
public const TYPE_NAME = 'image_folder';
protected string $name = self::TYPE_NAME;
/**
* @inheritDoc
*/
public function canResourceIdsBeEmpty(): bool
{
return true;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Domain/Model/DatasetFilter/Providers/ServiceCategoryFilterType.php | centreon/src/Core/ResourceAccess/Domain/Model/DatasetFilter/Providers/ServiceCategoryFilterType.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ResourceAccess\Domain\Model\DatasetFilter\Providers;
use Core\ResourceAccess\Domain\Model\DatasetFilter\AbstractDatasetFilterType;
class ServiceCategoryFilterType extends AbstractDatasetFilterType
{
public const TYPE_NAME = 'service_category';
protected string $name = self::TYPE_NAME;
protected array $possibleChildren = [
ServiceGroupFilterType::TYPE_NAME,
ServiceFilterType::TYPE_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/ResourceAccess/Infrastructure/Voters/RulesVoter.php | centreon/src/Core/ResourceAccess/Infrastructure/Voters/RulesVoter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ResourceAccess\Infrastructure\Voters;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
/**
* @extends Voter<string, mixed>
*/
final class RulesVoter extends Voter
{
public const LIST_RULES = 'list_rules';
/**
* {@inheritDoc}
*/
protected function supports(string $attribute, $subject): bool
{
return in_array($attribute, [self::LIST_RULES], true);
}
/**
* {@inheritDoc}
*/
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (! $user instanceof ContactInterface) {
return false;
}
return match ($attribute) {
self::LIST_RULES => $user->hasTopologyRole(Contact::ROLE_ADMINISTRATION_ACL_RESOURCE_ACCESS_MANAGEMENT_RW),
default => throw new \LogicException('Action on resource access rules 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/ResourceAccess/Infrastructure/Repository/DbWriteResourceAccessRepository.php | centreon/src/Core/ResourceAccess/Infrastructure/Repository/DbWriteResourceAccessRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ResourceAccess\Infrastructure\Repository;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Common\Infrastructure\Repository\RepositoryTrait;
use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait;
use Core\ResourceAccess\Application\Repository\WriteDatasetRepositoryInterface;
use Core\ResourceAccess\Application\Repository\WriteResourceAccessRepositoryInterface;
use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilter;
use Core\ResourceAccess\Domain\Model\NewRule;
use Core\ResourceAccess\Domain\Model\Rule;
final class DbWriteResourceAccessRepository extends AbstractRepositoryRDB implements WriteResourceAccessRepositoryInterface
{
use LoggerTrait;
use RepositoryTrait;
use SqlMultipleBindTrait;
/** @var WriteDatasetRepositoryInterface[] */
private array $repositoryProviders;
/**
* @param DatabaseConnection $db
* @param \Traversable<WriteDatasetRepositoryInterface> $repositoryProviders
*/
public function __construct(DatabaseConnection $db, \Traversable $repositoryProviders)
{
$this->db = $db;
$this->repositoryProviders = iterator_to_array($repositoryProviders);
}
/**
* @inheritDoc
*/
public function updateDatasetAccess(int $ruleId, int $datasetId, string $resourceType, bool $fullAccess): void
{
foreach ($this->repositoryProviders as $repositoryProvider) {
if ($repositoryProvider->isValidFor($resourceType) === true) {
$repositoryProvider->updateDatasetAccess(ruleId: $ruleId, datasetId: $datasetId, fullAccess: $fullAccess);
}
}
}
/**
* @inheritDoc
* Here are the deletions (on cascade or not) that will occur on rule deletion
* - Contact relations (ON DELETE CASCADE)
* - Contact Group relations (ON DELETE CASCADE)
* - Datasets relations + datasets (NEED MANUAL DELETION)
* - DatasetFilters (ON DELETE CASCADE).
*/
public function deleteRuleAndDatasets(int $ruleId): void
{
$datasetIds = $this->findDatasetIdsByRuleId($ruleId);
$alreadyInTransaction = $this->db->inTransaction();
if (! $alreadyInTransaction) {
$this->db->beginTransaction();
}
try {
$this->deleteDatasets($datasetIds);
$this->deleteRule($ruleId);
if (! $alreadyInTransaction) {
$this->db->commit();
}
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
if (! $alreadyInTransaction) {
$this->db->rollBack();
}
throw $ex;
}
}
/**
* @param int[] $ids
*/
public function deleteDatasets(array $ids): void
{
[$bindValues, $bindQuery] = $this->createMultipleBindQuery($ids, ':dataset_id_');
$request = <<<SQL
DELETE FROM `:db`.acl_resources WHERE acl_res_id IN ({$bindQuery})
SQL;
$statement = $this->db->prepare($this->translateDbName($request));
foreach ($bindValues as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
}
/**
* @inheritDoc
*/
public function update(Rule $rule): void
{
$alreadyInTransaction = $this->db->inTransaction();
if (! $alreadyInTransaction) {
$this->db->beginTransaction();
}
try {
$this->updateBasicInformation($rule);
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 deleteContactRuleRelations(int $ruleId): void
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
DELETE FROM `:db`.acl_group_contacts_relations WHERE acl_group_id = :ruleId
SQL
));
$statement->bindValue(':ruleId', $ruleId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @inheritDoc
*/
public function deleteContactGroupRuleRelations(int $ruleId): void
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
DELETE FROM `:db`.acl_group_contactgroups_relations WHERE acl_group_id = :ruleId
SQL
));
$statement->bindValue(':ruleId', $ruleId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @inheritDoc
*/
public function linkResourcesToDataset(int $ruleId, int $datasetId, string $resourceType, array $resourceIds): void
{
foreach ($this->repositoryProviders as $repositoryProvider) {
if ($repositoryProvider->isValidFor($resourceType) === true) {
$repositoryProvider->linkResourcesToDataset(datasetId: $datasetId, resourceIds: $resourceIds, ruleId: $ruleId);
}
}
}
/**
* @inheritDoc
*/
public function addDatasetFilter(int $ruleId, int $datasetId, DatasetFilter $filter, ?int $parentFilterId): int
{
$request = $this->translateDbName(
<<<'SQL'
INSERT INTO `:db`.dataset_filters (parent_id, type, acl_group_id, acl_resource_id, resource_ids)
VALUES (:parentFilterId, :type, :ruleId, :datasetId, :resourceIds)
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':parentFilterId', $parentFilterId, \PDO::PARAM_INT);
$statement->bindValue(':type', $filter->getType(), \PDO::PARAM_STR);
$statement->bindValue(':ruleId', $ruleId, \PDO::PARAM_INT);
$statement->bindValue(':datasetId', $datasetId, \PDO::PARAM_INT);
$statement->bindValue(':resourceIds', implode(',', $filter->getResourceIds()), \PDO::PARAM_STR);
$statement->execute();
return (int) $this->db->lastInsertId();
}
/**
* @inheritDoc
*/
public function linkDatasetToRule(int $ruleId, int $datasetId): void
{
$request = $this->translateDbName(
<<<'SQL'
INSERT INTO acl_res_group_relations (acl_res_id, acl_group_id) VALUES (:datasetId, :ruleId)
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':datasetId', $datasetId, \PDO::PARAM_INT);
$statement->bindValue(':ruleId', $ruleId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @inheritDoc
*/
public function addDataset(
string $name,
bool $accessAllHosts = false,
bool $accessAllHostGroups = false,
bool $accessAllServiceGroups = false,
bool $accessAllImageFolders = false,
): int {
$request = $this->translateDbName(
<<<'SQL'
INSERT INTO `:db`.acl_resources
(acl_res_name, all_hosts, all_hostgroups, all_servicegroups, all_image_folders, acl_res_activate, changed, cloud_specific)
VALUES (:name, :allHosts, :allHostGroups, :allServiceGroups, :allImageFolders, '1', 1, 1)
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':name', $name, \PDO::PARAM_STR);
$statement->bindValue(':allHosts', $accessAllHosts ? '1' : '0', \PDO::PARAM_STR);
$statement->bindValue(':allHostGroups', $accessAllHostGroups ? '1' : '0', \PDO::PARAM_STR);
$statement->bindValue(':allServiceGroups', $accessAllServiceGroups ? '1' : '0', \PDO::PARAM_STR);
$statement->bindValue(':allImageFolders', $accessAllImageFolders ? '1' : '0', \PDO::PARAM_STR);
$statement->execute();
return (int) $this->db->lastInsertId();
}
/**
* @inheritDoc
*/
public function linkContactsToRule(int $ruleId, array $contactIds): void
{
if ($contactIds === []) {
return;
}
$contactIds = array_values(array_unique($contactIds));
$bindValues = [];
$subValues = [];
foreach ($contactIds as $index => $contactId) {
$bindValues["contact_id_{$index}"] = $contactId;
$subValues[] = "(:contact_id_{$index}, :ruleId)";
}
$subQueries = implode(', ', $subValues);
$request = $this->translateDbName(
<<<SQL
INSERT INTO `:db`.acl_group_contacts_relations (contact_contact_id, acl_group_id)
VALUES {$subQueries}
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':ruleId', $ruleId, \PDO::PARAM_INT);
foreach ($bindValues as $bindKey => $bindValue) {
$statement->bindValue($bindKey, $bindValue, \PDO::PARAM_INT);
}
$statement->execute();
}
/**
* @inheritDoc
*/
public function add(NewRule $rule): int
{
$alreadyInTransaction = $this->db->inTransaction();
if (! $alreadyInTransaction) {
$this->db->beginTransaction();
}
try {
$ruleId = $this->addBasicInformation($rule);
if (! $alreadyInTransaction) {
$this->db->commit();
}
return $ruleId;
} catch (\Throwable $exception) {
$this->error($exception->getMessage(), ['trace' => $exception->getTraceAsString()]);
if (! $alreadyInTransaction) {
$this->db->rollBack();
}
throw $exception;
}
}
/**
* @inheritDoc
*/
public function linkContactGroupsToRule(int $ruleId, array $contactGroupIds): void
{
if ($contactGroupIds === []) {
return;
}
$contactGroupIds = array_values(array_unique($contactGroupIds));
$bindValues = [];
$subValues = [];
foreach ($contactGroupIds as $index => $contactGroupId) {
$bindValues["contact_group_id_{$index}"] = $contactGroupId;
$subValues[] = "(:contact_group_id_{$index}, :ruleId)";
}
$subQueries = implode(', ', $subValues);
$request = $this->translateDbName(
<<<SQL
INSERT INTO `:db`.acl_group_contactgroups_relations (cg_cg_id, acl_group_id)
VALUES {$subQueries}
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':ruleId', $ruleId, \PDO::PARAM_INT);
foreach ($bindValues as $bindKey => $bindValue) {
$statement->bindValue($bindKey, $bindValue, \PDO::PARAM_INT);
}
$statement->execute();
}
/**
* @inheritDoc
*/
public function updateDatasetResources(int $datasetId, array $resourceIds): void
{
if ($resourceIds === []) {
return;
}
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
UPDATE `:db`.dataset_filters
SET resource_ids = :resource_ids
WHERE id = :id
SQL
));
$statement->bindValue(':resource_ids', implode(',', $resourceIds), \PDO::PARAM_STR);
$statement->bindValue(':id', (int) $datasetId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @inheritDoc
*/
public function deleteDatasetFilter(int $datasetFilterid): void
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
DELETE FROM `:db`.dataset_filters
WHERE id = :id
SQL
));
$statement->bindValue(':id', $datasetFilterid, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @param int $ruleId
*
* @return int[]
*/
private function findDatasetIdsByRuleId(int $ruleId): array
{
// Retrieve first all the datasets linked to the rule
$statement = $this->db->prepare(
$this->translateDbName(
<<<'SQL'
SELECT acl_res_id FROM `:db`.acl_res_group_relations WHERE acl_group_id = :ruleId
SQL
)
);
$statement->bindValue(':ruleId', $ruleId, \PDO::PARAM_INT);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
return $statement->fetchAll(\PDO::FETCH_COLUMN);
}
/**
* @param int $ruleId
*/
private function deleteRule(int $ruleId): void
{
$statement = $this->db->prepare(
$this->translateDbName(
'DELETE FROM `:db`.acl_groups WHERE acl_group_id = :ruleId AND cloud_specific = 1'
)
);
$statement->bindValue(':ruleId', $ruleId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @inheritDoc
*/
private function updateBasicInformation(Rule $rule): void
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
UPDATE
`:db`.acl_groups
SET
acl_group_name = :name,
acl_group_alias = :alias,
acl_group_changed = '1',
cloud_description = :description,
acl_group_activate = :status,
cloud_specific = 1,
all_contacts = :applyToAllContacts,
all_contact_groups = :applyToAllContactGroups
WHERE
acl_group_id = :ruleId
SQL
));
$statement->bindValue(':name', $rule->getName(), \PDO::PARAM_STR);
$statement->bindValue(':alias', $rule->getName(), \PDO::PARAM_STR);
$statement->bindValue(
':description',
$this->emptyStringAsNull($rule->getDescription() ?? ''),
\PDO::PARAM_STR
);
$statement->bindValue(':status', $rule->isEnabled() ? '1' : '0', \PDO::PARAM_STR);
$statement->bindValue(':ruleId', $rule->getId(), \PDO::PARAM_INT);
$statement->bindValue(':applyToAllContacts', $rule->doesApplyToAllContacts() ? 1 : 0, \PDO::PARAM_INT);
$statement->bindValue(':applyToAllContactGroups', $rule->doesApplyToAllContactGroups() ? 1 : 0, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @param NewRule $rule
*
* @throws \PDOException
*
* @return int
*/
private function addBasicInformation(NewRule $rule): int
{
// cloud_specific field forced to 1 as we do create this from a cloud feature
$request = $this->translateDbName(
<<<'SQL'
INSERT INTO `:db`.acl_groups
(
acl_group_name,
acl_group_alias,
acl_group_changed,
cloud_description,
acl_group_activate,
cloud_specific,
all_contacts,
all_contact_groups
) VALUES
(
:name,
:alias,
'1',
:description,
:status,
1,
:applyToAllContacts,
:applyToAllContactGroups
)
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':name', $rule->getName(), \PDO::PARAM_STR);
$statement->bindValue(':alias', $rule->getName(), \PDO::PARAM_STR);
$statement->bindValue(
':description',
$this->emptyStringAsNull($rule->getDescription() ?? ''),
\PDO::PARAM_STR
);
$statement->bindValue(':status', $rule->isEnabled() ? '1' : '0', \PDO::PARAM_STR);
$statement->bindValue(':applyToAllContacts', $rule->doesApplyToAllContacts() ? 1 : 0, \PDO::PARAM_INT);
$statement->bindValue(':applyToAllContactGroups', $rule->doesApplyToAllContactGroups() ? 1 : 0, \PDO::PARAM_INT);
$statement->execute();
return (int) $this->db->lastInsertId();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Infrastructure/Repository/DbRuleFactory.php | centreon/src/Core/ResourceAccess/Infrastructure/Repository/DbRuleFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ResourceAccess\Infrastructure\Repository;
use Core\Infrastructure\Common\Repository\DbFactoryUtilitiesTrait;
use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilterValidator;
use Core\ResourceAccess\Domain\Model\Rule;
/**
* @phpstan-import-type _DatasetFilter from DbReadResourceAccessRepository
* @phpstan-import-type _TinyRule from DbReadResourceAccessRepository
*/
class DbRuleFactory
{
use DbFactoryUtilitiesTrait;
/**
* @param _TinyRule $record
* @param int[] $linkedContactIds
* @param int[] $linkedContactGroupIds
* @param non-empty-array<_DatasetFilter> $datasetFiltersRecord
* @param DatasetFilterValidator $datasetValidator
*
* @return Rule
*/
public static function createFromRecord(
array $record,
array $linkedContactIds,
array $linkedContactGroupIds,
array $datasetFiltersRecord,
DatasetFilterValidator $datasetValidator,
): Rule {
$datasets = [];
// gather filters by dataset
foreach ($datasetFiltersRecord as $datasetFilterRecord) {
$datasets[$datasetFilterRecord['dataset_name']][] = $datasetFilterRecord;
}
// and order the datasets by name
ksort($datasets);
$datasetFilters = [];
foreach ($datasets as $dataset) {
$datasetFilters[] = DbDatasetFilterFactory::createFromRecord($dataset, $datasetValidator);
}
return new Rule(
id: $record['id'],
name: $record['name'],
description: (string) $record['description'],
applyToAllContacts: $record['all_contacts'] === 1,
linkedContacts: $linkedContactIds,
applyToAllContactGroups: $record['all_contact_groups'] === 1,
linkedContactGroups: $linkedContactGroupIds,
datasets: $datasetFilters,
isEnabled: (bool) $record['is_enabled']
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Infrastructure/Repository/DbDatasetFilterFactory.php | centreon/src/Core/ResourceAccess/Infrastructure/Repository/DbDatasetFilterFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ResourceAccess\Infrastructure\Repository;
use Core\Infrastructure\Common\Repository\DbFactoryUtilitiesTrait;
use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilter;
use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilterValidator;
/**
* @phpstan-import-type _DatasetFilter from DbReadResourceAccessRepository
*/
class DbDatasetFilterFactory
{
use DbFactoryUtilitiesTrait;
/**
* @param non-empty-array<_DatasetFilter> $record
* @param DatasetFilterValidator $datasetValidator
*
* @throws \InvalidArgumentException
*
* @return DatasetFilter
*/
public static function createFromRecord(array $record, DatasetFilterValidator $datasetValidator): DatasetFilter
{
$datasetFilter = null;
$buildDatasetFilterWithHierarchy = function (
array $data,
?int $parentId,
?DatasetFilter $parentDatasetFilter,
) use (&$datasetFilter, &$buildDatasetFilterWithHierarchy, $datasetValidator): void {
if ($datasetFilter === null) {
/** @var non-empty-array<_DatasetFilter> $data */
$rootData = self::findRootFilter($data);
$datasetFilter = new DatasetFilter(
$rootData['dataset_filter_type'],
self::fromStringToArrayOfInts($rootData['dataset_filter_resources']),
$datasetValidator
);
$buildDatasetFilterWithHierarchy($data, $rootData['dataset_filter_id'], $datasetFilter);
} elseif (
$parentId !== null
&& $parentDatasetFilter !== null
) {
/** @var non-empty-array<_DatasetFilter> $data */
$childrenData = self::findSubFilter($parentId, $data);
if ($childrenData !== []) {
$childrenFilter = new DatasetFilter(
$childrenData['dataset_filter_type'],
self::fromStringToArrayOfInts($childrenData['dataset_filter_resources']),
$datasetValidator
);
$parentDatasetFilter->setDatasetFilter($childrenFilter);
$buildDatasetFilterWithHierarchy($data, $childrenData['dataset_filter_id'], $parentDatasetFilter->getDatasetFilter());
}
}
};
$buildDatasetFilterWithHierarchy($record, null, null);
/** @var DatasetFilter $datasetFilter */
return $datasetFilter;
}
/**
* @param int $parentId
* @param non-empty-array<_DatasetFilter> $data
*
* @return _DatasetFilter|array{}
*/
private static function findSubFilter(int $parentId, array $data): array
{
$subFilter = array_values(
array_filter(
$data,
static fn (array $data): bool => $data['dataset_filter_parent_id'] === $parentId
)
);
return $subFilter[0] ?? [];
}
/**
* @param non-empty-array<_DatasetFilter> $filters
*
* @return _DatasetFilter
*/
private static function findRootFilter(array $filters): array
{
$rootData = array_values(array_filter($filters, static fn (array $data): bool => $data['dataset_filter_parent_id'] === null));
return $rootData[0];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Infrastructure/Repository/DbReadResourceAccessRepository.php | centreon/src/Core/ResourceAccess/Infrastructure/Repository/DbReadResourceAccessRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ResourceAccess\Infrastructure\Repository;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait;
use Core\Contact\Domain\Model\ContactGroup;
use Core\ResourceAccess\Application\Repository\ReadResourceAccessRepositoryInterface;
use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilterRelation;
use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilterValidator;
use Core\ResourceAccess\Domain\Model\Rule;
use Core\ResourceAccess\Domain\Model\TinyRule;
/**
* @phpstan-type _TinyRule array{
* id: int,
* name: string,
* description: string|null,
* is_enabled: int,
* all_contacts: int,
* all_contact_groups: int,
* }
* @phpstan-type _DatasetFilter array{
* dataset_name: string,
* dataset_filter_id: int,
* dataset_filter_parent_id: int|null,
* dataset_filter_type: string,
* dataset_filter_resources: string,
* dataset_id: int,
* rule_id: int
* }
*/
final class DbReadResourceAccessRepository extends AbstractRepositoryRDB implements ReadResourceAccessRepositoryInterface
{
use LoggerTrait;
use SqlMultipleBindTrait;
/**
* @param DatabaseConnection $db
* @param DatasetFilterValidator $datasetValidator
*/
public function __construct(
DatabaseConnection $db,
private readonly DatasetFilterValidator $datasetValidator,
) {
$this->db = $db;
}
/**
* @inheritDoc
*/
public function exists(int $ruleId): bool
{
$request = $this->translateDbName(
<<<'SQL'
SELECT 1
FROM `:db`.acl_groups
WHERE acl_group_id = :ruleId
AND cloud_specific = 1
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':ruleId', $ruleId, \PDO::PARAM_INT);
$statement->execute();
return (bool) $statement->fetchColumn();
}
public function exist(array $ruleIds): array
{
if ($ruleIds === []) {
return [];
}
[$bindValues, $bindQuery] = $this->createMultipleBindQuery($ruleIds, ':rule_id_');
$statement = $this->db->prepare($this->translateDbName(
<<<SQL
SELECT acl_group_id
FROM `:db`.acl_groups
WHERE acl_group_id IN ({$bindQuery})
AND cloud_specific = 1
SQL
));
foreach ($bindValues as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->execute();
return $statement->fetchAll(\PDO::FETCH_COLUMN);
}
/**
* @inheritDoc
*/
public function existByContact(array $ruleIds, int $userId): array
{
if ($ruleIds === []) {
return [];
}
[$bindValues, $bindQuery] = $this->createMultipleBindQuery($ruleIds, ':ruleIds');
$query = <<<SQL
SELECT acl_group_id
FROM `:db`.acl_groups
WHERE cloud_specific = 1
AND (
all_contacts = 1
OR acl_group_id IN (
SELECT acl_group_id
FROM `:db`.acl_group_contacts_relations
WHERE contact_contact_id = :userId
)
)
AND (
acl_group_id IN ({$bindQuery})
)
SQL;
$statement = $this->db->prepare($this->translateDbName($query));
$statement->bindValue(':userId', $userId, \PDO::PARAM_INT);
foreach ($bindValues as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->execute();
return $statement->fetchAll(\PDO::FETCH_COLUMN);
}
/**
* @inheritDoc
*/
public function existByContactGroup(array $ruleIds, array $contactGroups): array
{
if ($ruleIds === [] || $contactGroups === []) {
return [];
}
[$bindValueContactGroups, $bindQueryContactGroups] = $this->createMultipleBindQuery(
array_map(
fn (ContactGroup $contactGroup) => $contactGroup->getId(),
$contactGroups
),
':contactgroup_'
);
[$bindValueRules, $bindQueryRules] = $this->createMultipleBindQuery($ruleIds, ':ruleIds');
$query = <<<SQL
SELECT acl_group_id
FROM `:db`.acl_groups
WHERE cloud_specific = 1
AND (
all_contact_groups = 1
OR acl_group_id IN (
SELECT acl_group_id
FROM `:db`.acl_group_contactgroups_relations
WHERE cg_cg_id IN ({$bindQueryContactGroups})
)
)
AND (
acl_group_id IN ({$bindQueryRules})
)
SQL;
$statement = $this->db->prepare($this->translateDbName($query));
foreach ($bindValueContactGroups as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
foreach ($bindValueRules as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->execute();
return $statement->fetchAll(\PDO::FETCH_COLUMN);
}
/**
* @inheritDoc
*/
public function findById(int $ruleId): ?Rule
{
$basicInformation = $this->findBasicInformation($ruleId);
if ($basicInformation === null) {
return null;
}
$linkedContactIds = $this->findLinkedContactsToRule($ruleId);
$linkedContactGroupIds = $this->findLinkedContactGroupsToRule($ruleId);
$datasets = $this->findDatasetsByRuleId($ruleId);
// Loop on datasets + exec requests to get names
if ($datasets === null) {
return null;
}
return DbRuleFactory::createFromRecord(
$basicInformation,
$linkedContactIds,
$linkedContactGroupIds,
$datasets,
$this->datasetValidator
);
}
/**
* @inheritDoc
*/
public function findDatasetIdsByRuleId(int $ruleId): array
{
$statement = $this->db->prepare(
$this->translateDbName(
<<<'SQL'
SELECT acl_res_id FROM `:db`.acl_res_group_relations WHERE acl_group_id = :ruleId
SQL
)
);
$statement->bindValue(':ruleId', $ruleId, \PDO::PARAM_INT);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
return $statement->fetchAll(\PDO::FETCH_COLUMN);
}
/**
* @inheritDoc
*/
public function existsByName(string $name): bool
{
$request = $this->translateDbName(
<<<'SQL'
SELECT 1
FROM `:db`.acl_groups
WHERE acl_group_name = :name
AND cloud_specific = 1
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':name', $name, \PDO::PARAM_STR);
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* @inheritDoc
*/
public function findAllByRequestParameters(RequestParametersInterface $requestParameters): array
{
$sqlTranslator = new SqlRequestParametersTranslator($requestParameters);
$sqlTranslator->setConcordanceArray([
'name' => 'acl_groups.acl_group_name',
'description' => 'acl_groups.cloud_description',
]);
$request = <<<'SQL_WRAP'
SELECT SQL_CALC_FOUND_ROWS
acl_group_id AS `id`,
acl_group_name AS `name`,
cloud_description AS `description`,
acl_group_activate AS `is_enabled`
FROM `:db`.acl_groups
SQL_WRAP;
$request .= $search = $sqlTranslator->translateSearchParameterToSql();
$request .= $search !== null
? ' AND cloud_specific = 1'
: ' WHERE cloud_specific = 1';
// handle sort parameter
$sort = $sqlTranslator->translateSortParameterToSql();
$request .= ! is_null($sort)
? $sort
: ' ORDER BY acl_group_name ASC';
// handle pagination parameter
$request .= $sqlTranslator->translatePaginationToSql();
$request = $this->translateDbName($request);
$statement = $this->db->prepare($request);
$rules = [];
if ($statement === false) {
return $rules;
}
foreach ($sqlTranslator->getSearchValues() as $key => $data) {
$type = key($data);
if ($type !== null) {
$value = $data[$type];
$statement->bindValue($key, $value, $type);
}
}
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
// Set total ACL groups found
$result = $this->db->query('SELECT FOUND_ROWS()');
if ($result !== false && ($total = $result->fetchColumn()) !== false) {
$sqlTranslator->getRequestParameters()->setTotal((int) $total);
}
foreach ($statement as $data) {
/** @var _TinyRule $data */
$rules[] = $this->createTinyRuleFromArray($data);
}
return $rules;
}
/**
* @inheritDoc
*/
public function findAllByRequestParametersAndUserId(RequestParametersInterface $requestParameters, int $userId): array
{
$sqlTranslator = new SqlRequestParametersTranslator($requestParameters);
$sqlTranslator->setConcordanceArray([
'name' => 'acl_groups.acl_group_name',
'description' => 'acl_groups.cloud_description',
]);
$request = <<<'SQL_WRAP'
SELECT SQL_CALC_FOUND_ROWS
acl_group_id AS `id`,
acl_group_name AS `name`,
cloud_description AS `description`,
acl_group_activate AS `is_enabled`
FROM `:db`.acl_groups
SQL_WRAP;
$request .= $search = $sqlTranslator->translateSearchParameterToSql();
$request .= $search !== null
? ' AND cloud_specific = 1'
: ' WHERE cloud_specific = 1';
$request .= ' AND (
acl_groups.all_contacts = 1
OR (
acl_groups.all_contact_groups = 1
AND (
SELECT 1
FROM `:db`.contactgroup_contact_relation
WHERE contact_contact_id = :userId
)
)
OR acl_groups.acl_group_id IN
(
SELECT acl_group_id
FROM `:db`.acl_group_contacts_relations
WHERE contact_contact_id = :userId
UNION
SELECT acl_group_id
FROM `:db`.acl_group_contactgroups_relations
JOIN `:db`.contactgroup_contact_relation
ON cg_cg_id = contactgroup_cg_id
WHERE contact_contact_id = :userId
)
)';
// handle sort parameter
$sort = $sqlTranslator->translateSortParameterToSql();
$request .= ! is_null($sort)
? $sort
: ' ORDER BY acl_group_name ASC';
// handle pagination parameter
$request .= $sqlTranslator->translatePaginationToSql();
$request = $this->translateDbName($request);
$statement = $this->db->prepare($request);
$rules = [];
if ($statement === false) {
return $rules;
}
foreach ($sqlTranslator->getSearchValues() as $key => $data) {
$type = key($data);
if ($type !== null) {
$value = $data[$type];
$statement->bindValue($key, $value, $type);
}
}
$statement->bindValue(':userId', $userId, \PDO::PARAM_INT);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
// Set total ACL groups found
$result = $this->db->query('SELECT FOUND_ROWS()');
if ($result !== false && ($total = $result->fetchColumn()) !== false) {
$sqlTranslator->getRequestParameters()->setTotal((int) $total);
}
foreach ($statement as $data) {
/** @var _TinyRule $data */
$rules[] = $this->createTinyRuleFromArray($data);
}
return $rules;
}
/**
* @inheritDoc
*/
public function findDatasetResourceIdsByHostGroupId(int $hostGroupId): array
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
SELECT id, resource_ids FROM dataset_filters
INNER JOIN acl_resources_hg_relations arhr
ON arhr.acl_res_id = dataset_filters.acl_resource_id
WHERE hg_hg_id = :hostGroupId
AND resource_ids != ''
SQL
));
$statement->bindValue(':hostGroupId', $hostGroupId, \PDO::PARAM_INT);
$statement->execute();
$datasetFilters = [];
while ($record = $statement->fetch(\PDO::FETCH_ASSOC)) {
/**
* @var array{id: int, resource_ids: string} $record
*/
$datasetFilters[$record['id']] = array_map('intval', explode(',', $record['resource_ids']));
}
return $datasetFilters;
}
/**
* @inheritDoc
*/
public function findLastLevelDatasetFilterByRuleIdsAndType(array $ruleIds, string $type): array
{
if ($ruleIds === []) {
return [];
}
[$bindValues, $bindQuery] = $this->createMultipleBindQuery($ruleIds, ':rule_id_');
$statement = $this->db->prepare(
$this->translateDbName(
<<<SQL
SELECT
id,
type,
parent_id,
acl_resource_id,
acl_group_id,
resource_ids
FROM `:db`.dataset_filters
INNER JOIN `:db`.acl_resources AS dataset
ON dataset.acl_res_id = dataset_filters.acl_resource_id
WHERE acl_group_id IN ({$bindQuery})
AND type = :type
AND parent_id IS NULL
SQL
)
);
foreach ($bindValues as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->bindValue(':type', $type, \PDO::PARAM_STR);
$statement->execute();
$datasetFilterRelations = [];
while ($record = $statement->fetch(\PDO::FETCH_ASSOC)) {
/**
* @var array{
* id: int,
* type: string,
* parent_id: int|null,
* acl_resource_id: int,
* acl_group_id: int,
* resource_ids: string
* } $record
*/
$datasetFilterRelations[] = new DatasetFilterRelation(
datasetFilterId: $record['id'],
datasetFilterType: $record['type'],
parentId: $record['parent_id'],
resourceAccessGroupId: $record['acl_resource_id'],
aclGroupId: $record['acl_group_id'],
resourceIds: array_map('intval', explode(',', $record['resource_ids']))
);
}
return $datasetFilterRelations;
}
/**
* @inheritDoc
*/
public function existByTypeAndResourceId(string $type, int $resourceId): array
{
$resourceIdPattern = '(^|,)' . $resourceId . '(,|$)';
$statement = $this->db->prepare(
$this->translateDbName(
<<<'SQL'
SELECT DISTINCT acl_group_id
FROM `:db`.dataset_filters
WHERE type = :type
AND resource_ids REGEXP(:resourceIdPattern)
SQL
)
);
$statement->bindValue(':type', $type, \PDO::PARAM_STR);
$statement->bindValue(':resourceIdPattern', $resourceIdPattern, \PDO::PARAM_STR);
$statement->execute();
return $statement->fetchAll(\PDO::FETCH_COLUMN);
}
/**
* @inheritDoc
*/
public function findRuleByResourceId(string $type, int $resourceId): array
{
$statement = $this->db->prepare($this->translateDbName(
<<<SQL
SELECT
acl_groups.acl_group_id AS `id`,
acl_groups.acl_group_name AS `name`,
acl_groups.cloud_description AS `description`,
acl_groups.acl_group_activate AS `is_enabled`
FROM `:db`.acl_groups
INNER JOIN `:db`.dataset_filters
ON dataset_filters.acl_group_id = acl_groups.acl_group_id
AND (
type = :type
OR type = 'all'
)
AND (
dataset_filters.resource_ids = ''
OR dataset_filters.resource_ids REGEXP('(^|,)({$resourceId})(,|$)')
)
WHERE acl_groups.cloud_specific = 1
SQL
));
$statement->bindValue(':type', $type, \PDO::PARAM_STR);
$statement->execute();
$rules = [];
foreach ($statement as $data) {
/** @var _TinyRule $data */
$rules[] = $this->createTinyRuleFromArray($data);
}
return $rules;
}
/**
* @inheritDoc
*/
public function findRuleByResourceIdAndContactId(string $type, int $resourceId, int $userId): array
{
$statement = $this->db->prepare($this->translateDbName(
<<<SQL
SELECT
acl_groups.acl_group_id AS `id`,
acl_groups.acl_group_name AS `name`,
acl_groups.cloud_description AS `description`,
acl_groups.acl_group_activate AS `is_enabled`
FROM `:db`.acl_groups
INNER JOIN `:db`.dataset_filters
ON dataset_filters.acl_group_id = acl_groups.acl_group_id
AND (
type = :type
OR type = 'all'
)
AND (
dataset_filters.resource_ids = ''
OR dataset_filters.resource_ids REGEXP('(^|,)({$resourceId})(,|$)')
)
WHERE acl_groups.cloud_specific = 1
AND (
all_contacts = 1
OR acl_groups.acl_group_id IN (
SELECT agcr.acl_group_id
FROM `:db`.acl_group_contacts_relations agcr
WHERE agcr.contact_contact_id = :userId
)
)
SQL
));
$statement->bindValue(':type', $type, \PDO::PARAM_STR);
$statement->bindValue(':userId', $userId, \PDO::PARAM_STR);
$statement->execute();
$rules = [];
foreach ($statement as $data) {
/** @var _TinyRule $data */
$rules[] = $this->createTinyRuleFromArray($data);
}
return $rules;
}
/**
* @inheritDoc
*/
public function findRuleByResourceIdAndContactGroups(string $type, int $resourceId, array $contactGroups): array
{
if ($contactGroups === []) {
return [];
}
[$bindValues, $bindQuery] = $this->createMultipleBindQuery(
array_map(
fn (ContactGroup $contactGroup) => $contactGroup->getId(),
$contactGroups
),
':contactgroup_'
);
$statement = $this->db->prepare($this->translateDbName(
<<<SQL
SELECT
acl_groups.acl_group_id AS `id`,
acl_groups.acl_group_name AS `name`,
acl_groups.cloud_description AS `description`,
acl_groups.acl_group_activate AS `is_enabled`
FROM `:db`.acl_groups
INNER JOIN `:db`.dataset_filters
ON dataset_filters.acl_group_id = acl_groups.acl_group_id
AND (
type = :type
OR type = 'all'
)
AND (
dataset_filters.resource_ids = ''
OR dataset_filters.resource_ids REGEXP('(^|,)({$resourceId})(,|$)')
)
WHERE acl_groups.cloud_specific = 1
AND (
all_contact_groups = 1
OR acl_groups.acl_group_id IN (
SELECT agcgr.acl_group_id
FROM `:db`.acl_group_contactgroups_relations agcgr
WHERE agcgr.cg_cg_id IN ({$bindQuery})
)
)
SQL
));
$statement->bindValue(':type', $type, \PDO::PARAM_STR);
foreach ($bindValues as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->execute();
$rules = [];
foreach ($statement as $data) {
/** @var _TinyRule $data */
$rules[] = $this->createTinyRuleFromArray($data);
}
return $rules;
}
/**
* @param int $ruleId
*
* @return int[]
*/
private function findLinkedContactsToRule(int $ruleId): array
{
$statement = $this->db->prepare(
$this->translatedbname(
<<<'SQL'
SELECT contact_contact_id FROM `:db`.acl_group_contacts_relations WHERE acl_group_id = :ruleId
SQL
)
);
$statement->bindValue(':ruleId', $ruleId, \PDO::PARAM_INT);
$statement->execute();
return $statement->fetchAll(\PDO::FETCH_COLUMN);
}
/**
* @param int $ruleId
*
* @return int[]
*/
private function findLinkedContactGroupsToRule(int $ruleId): array
{
$statement = $this->db->prepare(
$this->translatedbname(
<<<'SQL'
SELECT cg_cg_id FROM `:db`.acl_group_contactgroups_relations WHERE acl_group_id = :ruleId
SQL
)
);
$statement->bindValue(':ruleId', $ruleId, \PDO::PARAM_INT);
$statement->execute();
return $statement->fetchAll(\PDO::FETCH_COLUMN);
}
/**
* @param int $ruleId
*
* @throws \PDOException
*
* @return non-empty-list<_DatasetFilter>|null
*/
private function findDatasetsByRuleId(int $ruleId): ?array
{
$request = $this->translateDbName(
<<<'SQL'
SELECT
dataset.acl_res_name AS dataset_name,
id AS dataset_filter_id,
parent_id AS dataset_filter_parent_id,
type AS dataset_filter_type,
resource_ids AS dataset_filter_resources,
acl_resource_id AS dataset_id,
acl_group_id AS rule_id
FROM `:db`.dataset_filters
INNER JOIN `:db`.acl_resources AS dataset
ON dataset.acl_res_id = dataset_filters.acl_resource_id
WHERE dataset_filters.acl_group_id = :ruleId
ORDER BY dataset_name ASC
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':ruleId', $ruleId, \PDO::PARAM_INT);
$statement->execute();
if ($record = $statement->fetchAll(\PDO::FETCH_ASSOC)) {
/** @var non-empty-list<_DatasetFilter> $record */
return $record;
}
return null;
}
/**
* @param int $ruleId
*
* @throws \PDOException
*
* @return _TinyRule|null
*/
private function findBasicInformation(int $ruleId): ?array
{
$request = $this->translateDbName(
<<<'SQL'
SELECT
acl_groups.acl_group_id AS `id`,
acl_group_name AS `name`,
cloud_description AS `description`,
acl_group_activate AS `is_enabled`,
all_contacts,
all_contact_groups
FROM `:db`.acl_groups
WHERE acl_groups.acl_group_id = :ruleId
AND cloud_specific = 1
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':ruleId', $ruleId, \PDO::PARAM_INT);
$statement->execute();
if ($record = $statement->fetch(\PDO::FETCH_ASSOC)) {
/** @var _TinyRule $record */
return $record;
}
return null;
}
/**
* @param _TinyRule $data
*
* @return TinyRule
*/
private function createTinyRuleFromArray(array $data): TinyRule
{
return new TinyRule(
id: (int) $data['id'],
name: $data['name'],
description: (string) $data['description'],
isEnabled: (bool) $data['is_enabled']
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Infrastructure/Repository/Dataset/DbWriteServiceGroupRepository.php | centreon/src/Core/ResourceAccess/Infrastructure/Repository/Dataset/DbWriteServiceGroupRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ResourceAccess\Infrastructure\Repository\Dataset;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\ResourceAccess\Application\Repository\WriteDatasetRepositoryInterface;
use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\ServiceGroupFilterType;
class DbWriteServiceGroupRepository extends AbstractRepositoryRDB implements WriteDatasetRepositoryInterface
{
use LoggerTrait;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function isValidFor(string $type): bool
{
return $type === ServiceGroupFilterType::TYPE_NAME;
}
/**
* @inheritDoc
*/
public function linkResourcesToDataset(int $ruleId, int $datasetId, array $resourceIds): void
{
$this->debug(
'Add relation between servicegroups and dataset',
['rule_id' => $ruleId, 'dataset_id' => $datasetId, 'servicegroup_ids' => $resourceIds]
);
if ($resourceIds === []) {
return;
}
$bindValues = [];
$subValues = [];
foreach ($resourceIds as $index => $servicegroupId) {
$bindValues[":servicegroup_id_{$index}"] = $servicegroupId;
$subValues[] = "(:servicegroup_id_{$index}, :datasetId)";
}
$subQueries = implode(', ', $subValues);
$request = $this->translateDbName(
<<<SQL
INSERT INTO `:db`.acl_resources_sg_relations (sg_id, acl_res_id)
VALUES {$subQueries}
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':datasetId', $datasetId, \PDO::PARAM_INT);
foreach ($bindValues as $bindKey => $bindValue) {
$statement->bindValue($bindKey, $bindValue, \PDO::PARAM_INT);
}
$statement->execute();
}
/**
* @inheritDoc
*/
public function updateDatasetAccess(int $ruleId, int $datasetId, bool $fullAccess): void
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
UPDATE `:db`.acl_resources SET all_servicegroups = :access WHERE acl_res_id = :datasetId
SQL
));
$statement->bindValue(':datasetId', $datasetId, \PDO::PARAM_INT);
$statement->bindValue(':access', $fullAccess ? '1' : '0', \PDO::PARAM_STR);
$statement->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Infrastructure/Repository/Dataset/DbWriteImageFolderRepository.php | centreon/src/Core/ResourceAccess/Infrastructure/Repository/Dataset/DbWriteImageFolderRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ResourceAccess\Infrastructure\Repository\Dataset;
use Adaptation\Database\Connection\Collection\BatchInsertParameters;
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Core\Common\Domain\Exception\CollectionException;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Common\Domain\Exception\ValueObjectException;
use Core\Common\Infrastructure\Repository\DatabaseRepository;
use Core\ResourceAccess\Application\Repository\WriteDatasetRepositoryInterface;
use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\ImageFolderFilterType;
final class DbWriteImageFolderRepository extends DatabaseRepository implements WriteDatasetRepositoryInterface
{
/**
* @inheritDoc
*/
public function linkResourcesToDataset(int $ruleId, int $datasetId, array $resourceIds): void
{
try {
if ($resourceIds === []) {
return;
}
$insertQueryParameters = [];
foreach ($resourceIds as $index => $value) {
$insertQueryParameters[] = QueryParameters::create([
QueryParameter::int('datasetId', $datasetId),
QueryParameter::int('folderId' . $index, $value),
]);
}
$this->connection->batchInsert(
tableName: 'acl_resources_image_folder_relations',
columns: [
'acl_res_id',
'dir_id',
],
batchInsertParameters: BatchInsertParameters::create($insertQueryParameters)
);
} catch (ValueObjectException|CollectionException|ConnectionException $ex) {
throw new RepositoryException(
message: "An error occurred while linking resources to dataset: {$ex->getMessage()}",
context: [
'rule_id' => $ruleId,
'dataset_id' => $datasetId,
'resource_ids' => $resourceIds,
],
previous: $ex
);
}
}
/**
* @inheritDoc
*/
public function isValidFor(string $type): bool
{
return $type === ImageFolderFilterType::TYPE_NAME;
}
/**
* @inheritDoc
*/
public function updateDatasetAccess(int $ruleId, int $datasetId, bool $fullAccess): void
{
try {
$queryParameters = QueryParameters::create([
QueryParameter::int('datasetId', $datasetId),
QueryParameter::string('access', $fullAccess ? '1' : '0'),
]);
$query = <<<'SQL'
UPDATE `:db`.acl_resources SET all_image_folders = :access WHERE acl_res_id = :datasetId
SQL;
$this->connection->update($this->translateDbName($query), $queryParameters);
} catch (ValueObjectException|CollectionException|ConnectionException $ex) {
throw new RepositoryException(
message: "An error occurred while updating dataset access: {$ex->getMessage()}",
context: [
'rule_id' => $ruleId,
'dataset_id' => $datasetId,
'full_access' => $fullAccess,
],
previous: $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/ResourceAccess/Infrastructure/Repository/Dataset/DbWriteHostGroupRepository.php | centreon/src/Core/ResourceAccess/Infrastructure/Repository/Dataset/DbWriteHostGroupRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ResourceAccess\Infrastructure\Repository\Dataset;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\ResourceAccess\Application\Repository\WriteDatasetRepositoryInterface;
use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\HostGroupFilterType;
class DbWriteHostGroupRepository extends AbstractRepositoryRDB implements WriteDatasetRepositoryInterface
{
use LoggerTrait;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function isValidFor(string $type): bool
{
return $type === HostGroupFilterType::TYPE_NAME;
}
/**
* @inheritDoc
*/
public function linkResourcesToDataset(int $ruleId, int $datasetId, array $resourceIds): void
{
$this->debug(
'Add relation between hostgroups and dataset for rule',
['rule_id' => $ruleId, 'dataset_id' => $datasetId, 'hostgroup_ids' => $resourceIds]
);
if ($resourceIds === []) {
return;
}
$bindValues = [];
$subValues = [];
foreach ($resourceIds as $index => $hostgroupId) {
$bindValues[":hostgroup_id_{$index}"] = $hostgroupId;
$subValues[] = "(:hostgroup_id_{$index}, :datasetId)";
}
$subQueries = implode(', ', $subValues);
$request = $this->translateDbName(
<<<SQL
INSERT INTO `:db`.acl_resources_hg_relations (hg_hg_id, acl_res_id)
VALUES {$subQueries}
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':datasetId', $datasetId, \PDO::PARAM_INT);
foreach ($bindValues as $bindKey => $bindValue) {
$statement->bindValue($bindKey, $bindValue, \PDO::PARAM_INT);
}
$statement->execute();
}
/**
* @inheritDoc
*/
public function updateDatasetAccess(int $ruleId, int $datasetId, bool $fullAccess): void
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
UPDATE `:db`.acl_resources SET all_hostgroups = :access WHERE acl_res_id = :datasetId
SQL
));
$statement->bindValue(':datasetId', $datasetId, \PDO::PARAM_INT);
$statement->bindValue(':access', $fullAccess ? '1' : '0', \PDO::PARAM_STR);
$statement->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Infrastructure/Repository/Dataset/DbWriteHostCategoryRepository.php | centreon/src/Core/ResourceAccess/Infrastructure/Repository/Dataset/DbWriteHostCategoryRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ResourceAccess\Infrastructure\Repository\Dataset;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\ResourceAccess\Application\Repository\WriteDatasetRepositoryInterface;
use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\HostCategoryFilterType;
class DbWriteHostCategoryRepository extends AbstractRepositoryRDB implements WriteDatasetRepositoryInterface
{
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function isValidFor(string $type): bool
{
return $type === HostCategoryFilterType::TYPE_NAME;
}
/**
* @inheritDoc
*/
public function linkResourcesToDataset(int $ruleId, int $datasetId, array $resourceIds): void
{
if ($resourceIds === []) {
return;
}
$bindValues = [];
$subValues = [];
foreach ($resourceIds as $index => $hostCategoryId) {
$bindValues[":host_category_id_{$index}"] = $hostCategoryId;
$subValues[] = "(:host_category_id_{$index}, :datasetId)";
}
$subQueries = implode(', ', $subValues);
$request = $this->translateDbName(
<<<SQL
INSERT INTO `:db`.acl_resources_hc_relations (hc_id, acl_res_id)
VALUES {$subQueries}
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':datasetId', $datasetId, \PDO::PARAM_INT);
foreach ($bindValues as $bindKey => $bindValue) {
$statement->bindValue($bindKey, $bindValue, \PDO::PARAM_INT);
}
$statement->execute();
}
/**
* @inheritDoc
*/
public function updateDatasetAccess(int $ruleId, int $datasetId, bool $fullAccess): void
{
return;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Infrastructure/Repository/Dataset/DbWriteMetaServiceRepository.php | centreon/src/Core/ResourceAccess/Infrastructure/Repository/Dataset/DbWriteMetaServiceRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ResourceAccess\Infrastructure\Repository\Dataset;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\ResourceAccess\Application\Repository\WriteDatasetRepositoryInterface;
use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\MetaServiceFilterType;
class DbWriteMetaServiceRepository extends AbstractRepositoryRDB implements WriteDatasetRepositoryInterface
{
use LoggerTrait;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function isValidFor(string $type): bool
{
return $type === MetaServiceFilterType::TYPE_NAME;
}
/**
* @inheritDoc
*/
public function linkResourcesToDataset(int $ruleId, int $datasetId, array $resourceIds): void
{
$this->debug(
'Add relation between meta services and dataset',
['rule_id' => $ruleId, 'dataset_id' => $datasetId, 'meta_service_ids' => $resourceIds]
);
if ($resourceIds === []) {
return;
}
$bindValues = [];
$subValues = [];
foreach ($resourceIds as $index => $metaServiceId) {
$bindValues[":meta_service_id_{$index}"] = $metaServiceId;
$subValues[] = "(:meta_service_id_{$index}, :datasetId)";
}
$subQueries = implode(', ', $subValues);
$request = $this->translateDbName(
<<<SQL
INSERT INTO `:db`.acl_resources_meta_relations (meta_id, acl_res_id)
VALUES {$subQueries}
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':datasetId', $datasetId, \PDO::PARAM_INT);
foreach ($bindValues as $bindKey => $bindValue) {
$statement->bindValue($bindKey, $bindValue, \PDO::PARAM_INT);
}
$statement->execute();
}
/**
* @inheritDoc
*/
public function updateDatasetAccess(int $ruleId, int $datasetId, bool $fullAccess): void
{
return;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Infrastructure/Repository/Dataset/DbWriteServiceCategoryRepository.php | centreon/src/Core/ResourceAccess/Infrastructure/Repository/Dataset/DbWriteServiceCategoryRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ResourceAccess\Infrastructure\Repository\Dataset;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\ResourceAccess\Application\Repository\WriteDatasetRepositoryInterface;
use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\ServiceCategoryFilterType;
class DbWriteServiceCategoryRepository extends AbstractRepositoryRDB implements WriteDatasetRepositoryInterface
{
use LoggerTrait;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function isValidFor(string $type): bool
{
return $type === ServiceCategoryFilterType::TYPE_NAME;
}
/**
* @inheritDoc
*/
public function linkResourcesToDataset(int $ruleId, int $datasetId, array $resourceIds): void
{
$this->debug(
'Add relation between service categories and dataset for rule',
['rule_id' => $ruleId, 'dataset_id' => $datasetId, 'service_category_ids' => $resourceIds]
);
if ($resourceIds === []) {
return;
}
$bindValues = [];
$subValues = [];
foreach ($resourceIds as $index => $serviceCategoryId) {
$bindValues[":service_category_id_{$index}"] = $serviceCategoryId;
$subValues[] = "(:service_category_id_{$index}, :datasetId)";
}
$subQueries = implode(', ', $subValues);
$request = $this->translateDbName(
<<<SQL
INSERT INTO `:db`.acl_resources_sc_relations (sc_id, acl_res_id)
VALUES {$subQueries}
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':datasetId', $datasetId, \PDO::PARAM_INT);
foreach ($bindValues as $bindKey => $bindValue) {
$statement->bindValue($bindKey, $bindValue, \PDO::PARAM_INT);
}
$statement->execute();
}
/**
* @inheritDoc
*/
public function updateDatasetAccess(int $ruleId, int $datasetId, bool $fullAccess): void
{
return;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Infrastructure/Repository/Dataset/DbWriteHostRepository.php | centreon/src/Core/ResourceAccess/Infrastructure/Repository/Dataset/DbWriteHostRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ResourceAccess\Infrastructure\Repository\Dataset;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\ResourceAccess\Application\Repository\WriteDatasetRepositoryInterface;
use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\HostFilterType;
class DbWriteHostRepository extends AbstractRepositoryRDB implements WriteDatasetRepositoryInterface
{
use LoggerTrait;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function isValidFor(string $type): bool
{
return $type === HostFilterType::TYPE_NAME;
}
/**
* @inheritDoc
*/
public function linkResourcesToDataset(int $ruleId, int $datasetId, array $resourceIds): void
{
$this->debug(
'Add relation between hosts and dataset for rule',
['rule_id' => $ruleId, 'dataset_id' => $datasetId, 'host_ids' => $resourceIds]
);
if ($resourceIds === []) {
return;
}
$bindValues = [];
$subValues = [];
foreach ($resourceIds as $index => $hostId) {
$bindValues[":host_id_{$index}"] = $hostId;
$subValues[] = "(:host_id_{$index}, :datasetId)";
}
$subQueries = implode(', ', $subValues);
$request = $this->translateDbName(
<<<SQL
INSERT INTO `:db`.acl_resources_host_relations (host_host_id, acl_res_id)
VALUES {$subQueries}
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':datasetId', $datasetId, \PDO::PARAM_INT);
foreach ($bindValues as $bindKey => $bindValue) {
$statement->bindValue($bindKey, $bindValue, \PDO::PARAM_INT);
}
$statement->execute();
}
/**
* @inheritDoc
*/
public function updateDatasetAccess(int $ruleId, int $datasetId, bool $fullAccess): void
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
UPDATE `:db`.acl_resources SET all_hosts = :access WHERE acl_res_id = :datasetId
SQL
));
$statement->bindValue(':datasetId', $datasetId, \PDO::PARAM_INT);
$statement->bindValue(':access', $fullAccess ? '1' : '0', \PDO::PARAM_STR);
$statement->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Infrastructure/API/AddRule/AddRuleController.php | centreon/src/Core/ResourceAccess/Infrastructure/API/AddRule/AddRuleController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ResourceAccess\Infrastructure\API\AddRule;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\ResourceAccess\Application\Exception\RuleException;
use Core\ResourceAccess\Application\UseCase\AddRule\AddRule;
use Core\ResourceAccess\Application\UseCase\AddRule\AddRuleRequest;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
/**
* @phpstan-type _AddRequestData array{
* name: string,
* description: ?string,
* is_enabled: bool,
* contacts: array{
* ids: list<int>,
* all: bool
* },
* contact_groups: array{
* ids: list<int>,
* all: bool
* },
* dataset_filters: non-empty-list<array{
* type:string,
* resources: list<int>,
* ...
* }>
* }
*/
final class AddRuleController extends AbstractController
{
use LoggerTrait;
/**
* @param Request $request
* @param AddRule $useCase
* @param AddRulePresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
Request $request,
AddRule $useCase,
AddRulePresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
try {
/** @var _AddRequestData $data */
$data = $this->validateAndRetrieveDataSent($request, __DIR__ . '/AddRuleSchema.json');
$useCase($this->createDtoFromData($data), $presenter);
} catch (\InvalidArgumentException $exception) {
$this->error($exception->getMessage(), ['trace' => $exception->getTraceAsString()]);
$presenter->setResponseStatus(new InvalidArgumentResponse($exception));
} catch (\Throwable $exception) {
$this->error($exception->getMessage(), ['trace' => $exception->getTraceAsString()]);
$presenter->setResponseStatus(new ErrorResponse(RuleException::addRule()));
}
return $presenter->show();
}
/**
* @param _AddRequestData $data
*
* @return AddRuleRequest
*/
private function createDtoFromData(array $data): AddRuleRequest
{
$dto = new AddRuleRequest();
$dto->name = $data['name'];
$dto->isEnabled = $data['is_enabled'];
$dto->description = $data['description'] ?? '';
$dto->contactIds = $data['contacts']['ids'];
$dto->contactGroupIds = $data['contact_groups']['ids'];
$dto->applyToAllContacts = $data['contacts']['all'];
$dto->applyToAllContactGroups = $data['contact_groups']['all'];
$dto->datasetFilters = $data['dataset_filters'];
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/ResourceAccess/Infrastructure/API/AddRule/AddRulePresenter.php | centreon/src/Core/ResourceAccess/Infrastructure/API/AddRule/AddRulePresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ResourceAccess\Infrastructure\API\AddRule;
use Centreon\Domain\Log\Logger;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ConflictResponse;
use Core\Application\Common\UseCase\CreatedResponse;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Common\Infrastructure\ExceptionLogger\ExceptionLogger;
use Core\Infrastructure\Common\Presenter\PresenterTrait;
use Core\ResourceAccess\Application\UseCase\AddRule\AddRulePresenterInterface;
use Core\ResourceAccess\Application\UseCase\AddRule\AddRuleResponse;
final class AddRulePresenter extends AbstractPresenter implements AddRulePresenterInterface
{
use PresenterTrait;
public function presentResponse(AddRuleResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
if ($response instanceof ErrorResponse && ! is_null($response->getException())) {
ExceptionLogger::create()->log($response->getException(), $response->getContext());
} elseif (
($response instanceof ConflictResponse || $response instanceof InvalidArgumentResponse)
&& isset($response->getContext()['exception'])
&& $response->getContext()['exception'] instanceof \Throwable
) {
ExceptionLogger::create()->log($response->getContext()['exception']);
} elseif ($response instanceof ForbiddenResponse) {
Logger::create()->warning(
"User doesn't have sufficient rights to add a rule",
$response->getContext()
);
}
$this->setResponseStatus($response);
return;
}
$this->present(
new CreatedResponse(
$response->id,
[
'id' => $response->id,
'name' => $response->name,
'description' => $response->description,
'is_enabled' => $response->isEnabled,
'contacts' => [
'ids' => $response->contactIds,
'all' => $response->applyToAllContacts,
],
'contact_groups' => [
'ids' => $response->contactGroupIds,
'all' => $response->applyToAllContactGroups,
],
'dataset_filters' => $response->datasetFilters,
]
)
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Infrastructure/API/PartialRuleUpdate/PartialRuleUpdateController.php | centreon/src/Core/ResourceAccess/Infrastructure/API/PartialRuleUpdate/PartialRuleUpdateController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ResourceAccess\Infrastructure\API\PartialRuleUpdate;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\ResourceAccess\Application\UseCase\PartialRuleUpdate\PartialRuleUpdate;
use Core\ResourceAccess\Application\UseCase\PartialRuleUpdate\PartialRuleUpdateRequest;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
final class PartialRuleUpdateController extends AbstractController
{
use LoggerTrait;
public function __invoke(
int $ruleId,
Request $request,
PartialRuleUpdate $useCase,
DefaultPresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
try {
$dto = $this->createDtoFromRequest($ruleId, $request);
$useCase($dto, $presenter);
} catch (\InvalidArgumentException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
}
return $presenter->show();
}
/**
* @param int $ruleId
* @param Request $request
*
* @throws \InvalidArgumentException
*
* @return PartialRuleUpdateRequest
*/
private function createDtoFromRequest(int $ruleId, Request $request): PartialRuleUpdateRequest
{
/**
* @var array{
* name?: string,
* description?: string|null,
* is_enabled?: bool
* }
*/
$data = $this->validateAndRetrieveDataSent($request, __DIR__ . '/PartialRuleUpdateSchema.json');
$dto = new PartialRuleUpdateRequest();
$dto->id = $ruleId;
if (\array_key_exists('name', $data)) {
$dto->name = $data['name'];
}
if (\array_key_exists('description', $data)) {
$dto->description = $data['description'];
}
if (\array_key_exists('is_enabled', $data)) {
$dto->isEnabled = $data['is_enabled'];
}
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/ResourceAccess/Infrastructure/API/DeleteRule/DeleteRuleController.php | centreon/src/Core/ResourceAccess/Infrastructure/API/DeleteRule/DeleteRuleController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ResourceAccess\Infrastructure\API\DeleteRule;
use Centreon\Application\Controller\AbstractController;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\ResourceAccess\Application\UseCase\DeleteRule\DeleteRule;
use Symfony\Component\HttpFoundation\Response;
final class DeleteRuleController extends AbstractController
{
public function __invoke(
int $ruleId,
DeleteRule $useCase,
DefaultPresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($ruleId, $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/ResourceAccess/Infrastructure/API/DeleteRules/DeleteRulesController.php | centreon/src/Core/ResourceAccess/Infrastructure/API/DeleteRules/DeleteRulesController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ResourceAccess\Infrastructure\API\DeleteRules;
use Centreon\Application\Controller\AbstractController;
use Core\ResourceAccess\Application\UseCase\DeleteRules\DeleteRules;
use Core\ResourceAccess\Application\UseCase\DeleteRules\DeleteRulesRequest;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
final class DeleteRulesController extends AbstractController
{
/**
* @param Request $request
* @param DeleteRules $useCase
* @param DeleteRulesPresenter $presenter
*
* @return Response
*/
public function __invoke(
Request $request,
DeleteRules $useCase,
DeleteRulesPresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
/**
* @var array{
* ids: int[]
* } $data
*/
$data = $this->validateAndRetrieveDataSent($request, __DIR__ . '/DeleteRulesSchema.json');
$useCase($this->createDtoFromData($data), $presenter);
return $presenter->show();
}
/**
* @param array{
* ids: int[]
* } $data
*
* @return DeleteRulesRequest
*/
private function createDtoFromData(array $data): DeleteRulesRequest
{
$dto = new DeleteRulesRequest();
$dto->ids = $data['ids'];
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/ResourceAccess/Infrastructure/API/DeleteRules/DeleteRulesPresenter.php | centreon/src/Core/ResourceAccess/Infrastructure/API/DeleteRules/DeleteRulesPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ResourceAccess\Infrastructure\API\DeleteRules;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Infrastructure\Common\Api\Router;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\ResourceAccess\Application\UseCase\DeleteRules\DeleteRulesPresenterInterface;
use Core\ResourceAccess\Application\UseCase\DeleteRules\DeleteRulesResponse;
use Core\ResourceAccess\Application\UseCase\DeleteRules\DeleteRulesStatusResponse;
use Core\ResourceAccess\Domain\Model\ResponseCode;
use Symfony\Component\HttpFoundation\Response;
final class DeleteRulesPresenter extends AbstractPresenter implements DeleteRulesPresenterInterface
{
use LoggerTrait;
private const ROUTE_NAME = 'DeleteRule';
/**
* @param PresenterFormatterInterface $presenterFormatter
* @param Router $router
*/
public function __construct(
protected PresenterFormatterInterface $presenterFormatter,
private readonly Router $router,
) {
parent::__construct($presenterFormatter);
}
/**
* @inheritDoc
*/
public function presentResponse(DeleteRulesResponse|ResponseStatusInterface $response): void
{
if ($response instanceof DeleteRulesResponse) {
$multiStatusResponse = [
'results' => array_map(fn (DeleteRulesStatusResponse $dto) => [
'self' => $this->getDeletedNotificationHref($dto->id),
'status' => $this->enumToIntConverter($dto->status),
'message' => $dto->message,
], $response->responseStatuses),
];
$this->present($multiStatusResponse);
} else {
$this->setResponseStatus($response);
}
}
/**
* @param ResponseCode $code
*
* @return int
*/
private function enumToIntConverter(ResponseCode $code): int
{
return match ($code) {
ResponseCode::OK => Response::HTTP_NO_CONTENT,
ResponseCode::NotFound => Response::HTTP_NOT_FOUND,
ResponseCode::Error => Response::HTTP_INTERNAL_SERVER_ERROR,
};
}
/**
* @param int $id
*
* @return string|null
*/
private function getDeletedNotificationHref(int $id): ?string
{
try {
return $this->router->generate(self::ROUTE_NAME, ['ruleId' => $id]);
} catch (\Throwable $ex) {
$this->error('Impossible to generate the deleted entity route', [
'message' => $ex->getMessage(),
'trace' => $ex->getTraceAsString(),
'route' => self::ROUTE_NAME,
'payload' => $id,
]);
return 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/ResourceAccess/Infrastructure/API/UpdateRule/UpdateRuleController.php | centreon/src/Core/ResourceAccess/Infrastructure/API/UpdateRule/UpdateRuleController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ResourceAccess\Infrastructure\API\UpdateRule;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\ResourceAccess\Application\UseCase\UpdateRule\UpdateRule;
use Core\ResourceAccess\Application\UseCase\UpdateRule\UpdateRuleRequest;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* @phpstan-type _UpdateRequestData array{
* name: string,
* description: ?string,
* is_enabled: bool,
* contacts: array{
* ids: list<int>,
* all: bool
* },
* contact_groups: array{
* ids: list<int>,
* all: bool
* },
* dataset_filters: non-empty-list<array{
* type:string,
* resources: list<int>,
* ...
* }>
* }
*/
final class UpdateRuleController extends AbstractController
{
use LoggerTrait;
public function __invoke(
int $ruleId,
Request $request,
UpdateRule $useCase,
UpdateRulePresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
/** @var _UpdateRequestData $data */
$data = $this->validateAndRetrieveDataSent($request, __DIR__ . '/UpdateRuleSchema.json');
$useCase($this->createDtoFromData($ruleId, $data), $presenter);
return $presenter->show();
}
/**
* @param int $ruleId
* @param _UpdateRequestData $data
*
* @return UpdateRuleRequest
*/
private function createDtoFromData(int $ruleId, array $data): UpdateRuleRequest
{
$dto = new UpdateRuleRequest();
$dto->id = $ruleId;
$dto->name = $data['name'];
$dto->description = $data['description'] ?? '';
$dto->isEnabled = $data['is_enabled'];
$dto->contactIds = $data['contacts']['ids'];
$dto->contactGroupIds = $data['contact_groups']['ids'];
$dto->applyToAllContacts = $data['contacts']['all'];
$dto->applyToAllContactGroups = $data['contact_groups']['all'];
$dto->datasetFilters = $data['dataset_filters'];
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/ResourceAccess/Infrastructure/API/UpdateRule/UpdateRulePresenter.php | centreon/src/Core/ResourceAccess/Infrastructure/API/UpdateRule/UpdateRulePresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ResourceAccess\Infrastructure\API\UpdateRule;
use Centreon\Domain\Log\Logger;
use Core\Application\Common\UseCase\ConflictResponse;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Common\Infrastructure\ExceptionLogger\ExceptionLogger;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\ResourceAccess\Application\UseCase\UpdateRule\UpdateRulePresenterInterface;
class UpdateRulePresenter extends DefaultPresenter implements UpdateRulePresenterInterface
{
public function presentResponse(ResponseStatusInterface $response): void
{
if ($response instanceof ErrorResponse && ! is_null($response->getException())) {
ExceptionLogger::create()->log($response->getException(), $response->getContext());
} elseif (
($response instanceof ConflictResponse || $response instanceof InvalidArgumentResponse)
&& isset($response->getContext()['exception'])
&& $response->getContext()['exception'] instanceof \Throwable
) {
ExceptionLogger::create()->log($response->getContext()['exception'], $response->getContext());
} elseif ($response instanceof ForbiddenResponse) {
Logger::create()->warning(
"User doesn't have sufficient rights to update a resource access rule",
$response->getContext()
);
}
$this->setResponseStatus($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/ResourceAccess/Infrastructure/API/FindRules/FindRulesController.php | centreon/src/Core/ResourceAccess/Infrastructure/API/FindRules/FindRulesController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ResourceAccess\Infrastructure\API\FindRules;
use Centreon\Application\Controller\AbstractController;
use Core\ResourceAccess\Application\UseCase\FindRules\FindRules;
use Core\ResourceAccess\Application\UseCase\FindRules\FindRulesPresenterInterface;
use Core\ResourceAccess\Infrastructure\Voters\RulesVoter;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted(
RulesVoter::LIST_RULES,
null,
'You are not allowed to list resource access rules',
Response::HTTP_FORBIDDEN
)]
final class FindRulesController extends AbstractController
{
public function __invoke(
FindRules $useCase,
FindRulesPresenterInterface $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($presenter);
return $presenter->show();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Infrastructure/API/FindRules/FindRulesPresenter.php | centreon/src/Core/ResourceAccess/Infrastructure/API/FindRules/FindRulesPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ResourceAccess\Infrastructure\API\FindRules;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\ResourceAccess\Application\UseCase\FindRules\FindRulesPresenterInterface;
use Core\ResourceAccess\Application\UseCase\FindRules\FindRulesResponse;
final class FindRulesPresenter extends AbstractPresenter implements FindRulesPresenterInterface
{
/**
* @param RequestParametersInterface $requestParameters
* @param PresenterFormatterInterface $presenterFormatter
*/
public function __construct(
private readonly RequestParametersInterface $requestParameters,
protected PresenterFormatterInterface $presenterFormatter,
) {
parent::__construct($presenterFormatter);
}
public function presentResponse(FindRulesResponse|ResponseStatusInterface $response): void
{
$result = [];
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
foreach ($response->rulesDto as $dto) {
$result[] = [
'id' => $dto->id,
'name' => $dto->name,
'description' => $dto->description,
'is_enabled' => $dto->isEnabled,
];
}
}
$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/ResourceAccess/Infrastructure/API/FindRule/FindRuleController.php | centreon/src/Core/ResourceAccess/Infrastructure/API/FindRule/FindRuleController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ResourceAccess\Infrastructure\API\FindRule;
use Centreon\Application\Controller\AbstractController;
use Core\ResourceAccess\Application\UseCase\FindRule\FindRule;
use Core\ResourceAccess\Application\UseCase\FindRule\FindRulePresenterInterface;
use Symfony\Component\HttpFoundation\Response;
final class FindRuleController extends AbstractController
{
/**
* @param FindRule $useCase
* @param FindRulePresenterInterface $presenter
* @param int $ruleId
*
* @return Response
*/
public function __invoke(
int $ruleId,
FindRule $useCase,
FindRulePresenterInterface $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($ruleId, $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/ResourceAccess/Infrastructure/API/FindRule/FindRulePresenter.php | centreon/src/Core/ResourceAccess/Infrastructure/API/FindRule/FindRulePresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ResourceAccess\Infrastructure\API\FindRule;
use Centreon\Domain\Log\Logger;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Common\Infrastructure\ExceptionLogger\ExceptionLogger;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\ResourceAccess\Application\UseCase\FindRule\FindRulePresenterInterface;
use Core\ResourceAccess\Application\UseCase\FindRule\FindRuleResponse;
final class FindRulePresenter extends AbstractPresenter implements FindRulePresenterInterface
{
/**
* @param PresenterFormatterInterface $presenterFormatter
*/
public function __construct(
protected PresenterFormatterInterface $presenterFormatter,
) {
parent::__construct($presenterFormatter);
}
/**
* @param FindRuleResponse|ResponseStatusInterface $response
*/
public function presentResponse(FindRuleResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
if ($response instanceof ErrorResponse && ! is_null($response->getException())) {
ExceptionLogger::create()->log($response->getException(), $response->getContext());
} elseif ($response instanceof ForbiddenResponse) {
Logger::create()->warning("User doesn't have sufficient rights to list resource access rules", $response->getContext());
} elseif ($response instanceof NotFoundResponse) {
Logger::create()->warning('Resource Access Rule (%s) not found', $response->getContext());
}
$this->setResponseStatus($response);
return;
}
$this->present([
'id' => $response->id,
'name' => $response->name,
'description' => $response->description,
'is_enabled' => $response->isEnabled,
'contacts' => [
'values' => $response->contacts,
'all' => $response->applyToAllContacts,
],
'contact_groups' => [
'values' => $response->contactGroups,
'all' => $response->applyToAllContactGroups,
],
'dataset_filters' => $response->datasetFilters,
]);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Application/Model/NotificationTypeConverter.php | centreon/src/Core/Service/Application/Model/NotificationTypeConverter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Core\Service\Domain\Model\NotificationType;
class NotificationTypeConverter
{
public const NONE_AS_BIT = 0b000000;
public const WARNING_AS_BIT = 0b000001;
public const UNKNOWN_AS_BIT = 0b000010;
public const CRITICAL_AS_BIT = 0b000100;
public const RECOVERY_AS_BIT = 0b001000;
public const FLAPPING_AS_BIT = 0b010000;
public const DOWNTIME_SCHEDULED_AS_BIT = 0b100000;
public const ALL_TYPE = 0b111111;
/**
* @param int $bitFlag
*
* @throws AssertionFailedException
*
* @return list<NotificationType>
*/
public static function fromBits(int $bitFlag): array
{
Assertion::range($bitFlag, 0, self::ALL_TYPE);
if ($bitFlag === self::NONE_AS_BIT) {
return [NotificationType::None];
}
$notificationTypes = [];
foreach (NotificationType::cases() as $notificationType) {
if ($bitFlag & self::toBit($notificationType)) {
$notificationTypes[] = $notificationType;
}
}
return $notificationTypes;
}
/**
* @param NotificationType $notificationType
*
* @return int
*/
public static function toBit(NotificationType $notificationType): int
{
return match ($notificationType) {
NotificationType::Warning => self::WARNING_AS_BIT,
NotificationType::Unknown => self::UNKNOWN_AS_BIT,
NotificationType::Critical => self::CRITICAL_AS_BIT,
NotificationType::Recovery => self::RECOVERY_AS_BIT,
NotificationType::Flapping => self::FLAPPING_AS_BIT,
NotificationType::DowntimeScheduled => self::DOWNTIME_SCHEDULED_AS_BIT,
NotificationType::None => self::NONE_AS_BIT,
};
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Application/Model/YesNoDefaultConverter.php | centreon/src/Core/Service/Application/Model/YesNoDefaultConverter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Common\Domain\YesNoDefault;
class YesNoDefaultConverter
{
/**
* @param int $yesNoDefault
*
* @throws \Assert\AssertionFailedException
*
* @return YesNoDefault
*/
public static function fromInt(int $yesNoDefault): YesNoDefault
{
return match ($yesNoDefault) {
0 => YesNoDefault::No,
1 => YesNoDefault::Yes,
2 => YesNoDefault::Default,
default => throw AssertionException::range($yesNoDefault, 0, 2),
};
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Application/UseCase/FindRealTimeUniqueServiceNames/FindRealTimeUniqueServiceNames.php | centreon/src/Core/Service/Application/UseCase/FindRealTimeUniqueServiceNames/FindRealTimeUniqueServiceNames.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\UseCase\FindRealTimeUniqueServiceNames;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Infrastructure\RequestParameters\RequestParametersTranslatorException;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Core\Service\Application\Exception\ServiceException;
use Core\Service\Application\Repository\ReadRealTimeServiceRepositoryInterface;
final class FindRealTimeUniqueServiceNames
{
use LoggerTrait;
public const AUTHORIZED_ACL_GROUPS = ['customer_admin_acl'];
/**
* @param ContactInterface $user
* @param ReadAccessGroupRepositoryInterface $accessGroupRepository
* @param RequestParametersInterface $requestParameters
* @param ReadRealTimeServiceRepositoryInterface $repository
*/
public function __construct(
private readonly ContactInterface $user,
private readonly ReadAccessGroupRepositoryInterface $accessGroupRepository,
private readonly RequestParametersInterface $requestParameters,
private readonly ReadRealTimeServiceRepositoryInterface $repository,
) {
}
/**
* @param FindRealTimeUniqueServiceNamesPresenterInterface $presenter
*/
public function __invoke(FindRealTimeUniqueServiceNamesPresenterInterface $presenter): void
{
if (! $this->isAuthorized()) {
$this->error(
'User does not have sufficient rights to list real time services',
[
'user_id' => $this->user->getId(),
]
);
$presenter->presentResponse(
new ForbiddenResponse(ServiceException::accessNotAllowed()->getMessage())
);
return;
}
try {
$names = $this->isUserAdmin()
? $this->findServiceNamesAsAdmin($this->requestParameters)
: $this->findServiceNamesAsUser($this->requestParameters);
$this->info('Find unique real time service names');
$this->debug(
'Find unique real time service names',
[
'user_id' => $this->user->getId(),
'request_parameters' => $this->requestParameters->toArray(),
]
);
$presenter->presentResponse($this->createResponse($names));
} catch (RequestParametersTranslatorException $ex) {
$presenter->presentResponse(new ErrorResponse($ex->getMessage()));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (\Throwable $exception) {
$presenter->presentResponse(new ErrorResponse(ServiceException::errorWhileSearching($exception)));
$this->error($exception->getMessage(), ['trace' => $exception->getTraceAsString()]);
}
}
/**
* @param string[] $data
*
* @return FindRealTimeUniqueServiceNamesResponse
*/
private function createResponse(array $data): FindRealTimeUniqueServiceNamesResponse
{
$response = new FindRealTimeUniqueServiceNamesResponse();
$response->names = $data;
return $response;
}
/**
* @param RequestParametersInterface $requestParameters
*
* @return string[]
*/
private function findServiceNamesAsAdmin(RequestParametersInterface $requestParameters): array
{
return $this->repository->findUniqueServiceNamesByRequestParameters($requestParameters);
}
/**
* @param RequestParametersInterface $requestParameters
*
* @return string[]
*/
private function findServiceNamesAsUser(RequestParametersInterface $requestParameters): array
{
$accessGroupIds = array_map(
static fn (AccessGroup $accessGroup): int => $accessGroup->getId(),
$this->accessGroupRepository->findByContact($this->user)
);
return $this->repository->findUniqueServiceNamesByRequestParametersAndAccessGroupIds(
$requestParameters,
$accessGroupIds
);
}
/**
* Indicates if the current user is admin or not (cloud + onPremise context).
*
* @return bool
*/
private function isUserAdmin(): bool
{
if ($this->user->isAdmin()) {
return true;
}
$userAccessGroupNames = array_map(
static fn (AccessGroup $accessGroup): string => $accessGroup->getName(),
$this->accessGroupRepository->findByContact($this->user)
);
return ! empty(array_intersect($userAccessGroupNames, self::AUTHORIZED_ACL_GROUPS));
}
/**
* @return bool
*/
private function isAuthorized(): bool
{
if ($this->isUserAdmin()) {
return true;
}
return $this->user->hasTopologyRole(Contact::ROLE_MONITORING_RESOURCES_STATUS_RW);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Application/UseCase/FindRealTimeUniqueServiceNames/FindRealTimeUniqueServiceNamesPresenterInterface.php | centreon/src/Core/Service/Application/UseCase/FindRealTimeUniqueServiceNames/FindRealTimeUniqueServiceNamesPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\UseCase\FindRealTimeUniqueServiceNames;
use Core\Application\Common\UseCase\PresenterInterface;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface FindRealTimeUniqueServiceNamesPresenterInterface extends PresenterInterface
{
public function presentResponse(FindRealTimeUniqueServiceNamesResponse|ResponseStatusInterface $response): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Application/UseCase/FindRealTimeUniqueServiceNames/FindRealTimeUniqueServiceNamesResponse.php | centreon/src/Core/Service/Application/UseCase/FindRealTimeUniqueServiceNames/FindRealTimeUniqueServiceNamesResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\UseCase\FindRealTimeUniqueServiceNames;
final class FindRealTimeUniqueServiceNamesResponse
{
/** @var string[] */
public array $names = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Application/UseCase/FindServices/FindServicesResponse.php | centreon/src/Core/Service/Application/UseCase/FindServices/FindServicesResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\UseCase\FindServices;
final class FindServicesResponse
{
/** @var ServiceDto[] */
public array $services = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Application/UseCase/FindServices/FindServices.php | centreon/src/Core/Service/Application/UseCase/FindServices/FindServices.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\UseCase\FindServices;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Infrastructure\RequestParameters\RequestParametersTranslatorException;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Service\Application\Exception\ServiceException;
use Core\Service\Application\Repository\ReadServiceRepositoryInterface;
use Core\Service\Domain\Model\ServiceLight;
use Core\ServiceCategory\Application\Repository\ReadServiceCategoryRepositoryInterface;
use Core\ServiceGroup\Application\Repository\ReadServiceGroupRepositoryInterface;
use Core\ServiceGroup\Domain\Model\ServiceGroupRelation;
final class FindServices
{
use LoggerTrait;
public function __construct(
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly ReadServiceRepositoryInterface $readServiceRepository,
private readonly ReadHostRepositoryInterface $readHostRepository,
private readonly ReadServiceCategoryRepositoryInterface $readServiceCategoryRepository,
private readonly ReadServiceGroupRepositoryInterface $readServiceGroupRepository,
private readonly RequestParametersInterface $requestParameters,
private readonly ContactInterface $user,
) {
}
/**
* @param FindServicesPresenterInterface $presenter
*/
public function __invoke(FindServicesPresenterInterface $presenter): void
{
try {
if (
! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_SERVICES_READ)
&& ! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_SERVICES_WRITE)
) {
$this->error(
"User doesn't have sufficient rights to see services",
['user_id' => $this->user->getId()]
);
$presenter->presentResponse(
new ForbiddenResponse(ServiceException::accessNotAllowed())
);
return;
}
if ($this->user->isAdmin()) {
$services = $this->readServiceRepository->findByRequestParameter($this->requestParameters);
} else {
$accessGroups = $this->readAccessGroupRepository->findByContact($this->user);
$services = $this->readServiceRepository->findByRequestParameterAndAccessGroup($this->requestParameters, $accessGroups);
}
$presenter->presentResponse($this->createResponse($services));
} catch (RequestParametersTranslatorException $ex) {
$presenter->presentResponse(new ErrorResponse($ex->getMessage()));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (\Throwable $ex) {
$presenter->presentResponse(
new ErrorResponse(ServiceException::errorWhileSearching($ex))
);
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
}
}
/**
* @param ServiceLight[] $services
*
* @return FindServicesResponse
*/
private function createResponse(array $services): FindServicesResponse
{
$categoryIds = [];
$groupIds = [];
$hostIds = [];
foreach ($services as $service) {
$categoryIds[] = $service->getCategoryIds();
$hostIds[] = $service->getHostIds();
$hostIds[] = ServiceGroupRelation::getHostIds($service->getGroups());
$groupIds[] = ServiceGroupRelation::getServiceGroupIds($service->getGroups());
}
$categoryIds = array_merge(...$categoryIds);
$hostIds = array_merge(...$hostIds);
$groupIds = array_merge(...$groupIds);
$categoryNames = $categoryIds ? $this->readServiceCategoryRepository->findNames($categoryIds) : null;
$groupNames = $groupIds ? $this->readServiceGroupRepository->findNames($groupIds) : null;
$hostNames = $hostIds ? $this->readHostRepository->findNames($hostIds) : null;
$response = new FindServicesResponse();
foreach ($services as $service) {
$dto = new ServiceDto();
$dto->id = $service->getId();
$dto->name = $service->getName();
$dto->normalCheckInterval = $service->getNormalCheckInterval();
$dto->retryCheckInterval = $service->getRetryCheckInterval();
$dto->isActivated = $service->isActivated();
$dto->checkTimePeriod = $service->getCheckTimePeriod() !== null
? [
'id' => $service->getCheckTimePeriod()->getId(),
'name' => $service->getCheckTimePeriod()->getName() ?? '',
]
: null;
$dto->notificationTimePeriod = $service->getNotificationTimePeriod() !== null
? [
'id' => $service->getNotificationTimePeriod()->getId(),
'name' => $service->getNotificationTimePeriod()->getName() ?? '',
]
: null;
$dto->serviceTemplate = $service->getServiceTemplate() !== null
? [
'id' => $service->getServiceTemplate()->getId(),
'name' => $service->getServiceTemplate()->getName() ?? '',
]
: null;
$dto->severity = $service->getSeverity() !== null
? [
'id' => $service->getSeverity()->getId(),
'name' => $service->getSeverity()->getName() ?? '',
]
: null;
$dto->hosts = array_map(
fn (int $hostId): array => ['id' => $hostId, 'name' => $hostNames?->getName($hostId) ?? ''],
$service->getHostIds()
);
$dto->categories = $service->getCategoryIds() !== []
? array_map(
fn (int $categoryId): array => ['id' => $categoryId, 'name' => $categoryNames?->getName($categoryId) ?? ''],
$service->getCategoryIds()
)
: [];
$dto->groups = $service->getGroups() !== []
? array_map(
fn (ServiceGroupRelation $sgRel): array => [
'id' => $sgRel->getServiceGroupId(),
'name' => $groupNames?->getName($sgRel->getServiceGroupId()) ?? '',
'hostId' => $sgRel->getHostId() ?? 0,
'hostName' => $hostNames?->getName($sgRel->getHostId() ?? 0) ?? '',
],
$service->getGroups()
)
: [];
$response->services[] = $dto;
}
return $response;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Application/UseCase/FindServices/ServiceDto.php | centreon/src/Core/Service/Application/UseCase/FindServices/ServiceDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\UseCase\FindServices;
final class ServiceDto
{
public int $id = 0;
public string $name = '';
public bool $isActivated = false;
public int|null $normalCheckInterval = null;
public int|null $retryCheckInterval = null;
/** @var null|array{id:int,name:string} */
public null|array $serviceTemplate = null;
/** @var null|array{id:int,name:string}> */
public null|array $checkTimePeriod = null;
/** @var null|array{id:int,name:string} */
public null|array $notificationTimePeriod = null;
/** @var null|array{id:int,name:string} */
public null|array $severity = null;
/** @var array<array{id:int,name:string}> */
public array $hosts = [];
/** @var array<array{id:int,name:string}> */
public array $categories = [];
/** @var array<array{id:int,name:string,hostId:int,hostName:string}> */
public array $groups = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Application/UseCase/FindServices/FindServicesPresenterInterface.php | centreon/src/Core/Service/Application/UseCase/FindServices/FindServicesPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\UseCase\FindServices;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface FindServicesPresenterInterface
{
public function presentResponse(FindServicesResponse|ResponseStatusInterface $response): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Application/UseCase/FindRealTimeServiceStatusesCount/FindRealTimeServiceStatusesCountPresenterInterface.php | centreon/src/Core/Service/Application/UseCase/FindRealTimeServiceStatusesCount/FindRealTimeServiceStatusesCountPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\UseCase\FindRealTimeServiceStatusesCount;
use Core\Application\Common\UseCase\PresenterInterface;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface FindRealTimeServiceStatusesCountPresenterInterface extends PresenterInterface
{
/**
* @param FindRealTimeServiceStatusesCountResponse|ResponseStatusInterface $response
*/
public function presentResponse(FindRealTimeServiceStatusesCountResponse|ResponseStatusInterface $response): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Application/UseCase/FindRealTimeServiceStatusesCount/FindRealTimeServiceStatusesCount.php | centreon/src/Core/Service/Application/UseCase/FindRealTimeServiceStatusesCount/FindRealTimeServiceStatusesCount.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\UseCase\FindRealTimeServiceStatusesCount;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Infrastructure\RequestParameters\RequestParametersTranslatorException;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Core\Service\Application\Exception\ServiceException;
use Core\Service\Application\Repository\ReadRealTimeServiceRepositoryInterface;
use Core\Service\Domain\Model\ServiceStatusesCount;
final class FindRealTimeServiceStatusesCount
{
use LoggerTrait;
public const AUTHORIZED_ACL_GROUPS = ['customer_admin_acl'];
/**
* @param ContactInterface $user
* @param ReadRealTimeServiceRepositoryInterface $repository
* @param ReadAccessGroupRepositoryInterface $accessGroupRepository
* @param RequestParametersInterface $requestParameters
*/
public function __construct(
private readonly ContactInterface $user,
private readonly ReadRealTimeServiceRepositoryInterface $repository,
private readonly ReadAccessGroupRepositoryInterface $accessGroupRepository,
private readonly RequestParametersInterface $requestParameters,
) {
}
/**
* @param FindRealTimeServiceStatusesCountPresenterInterface $presenter
*/
public function __invoke(FindRealTimeServiceStatusesCountPresenterInterface $presenter): void
{
try {
if (! $this->isAuthorized()) {
$this->error(
"User doesn't have sufficient rights to get services information",
[
'user_id' => $this->user->getId(),
]
);
$presenter->presentResponse(
new ForbiddenResponse(ServiceException::accessNotAllowedForRealTime()->getMessage())
);
return;
}
$statuses = $this->isUserAdmin()
? $this->findStatusesCountAsAdmin()
: $this->findStatusesCountAsUser();
$this->info('Find service statuses distribution');
$this->debug(
'Find service statuses distribution',
[
'user_id' => $this->user->getId(),
'request_parameters' => $this->requestParameters->toArray(),
]
);
$presenter->presentResponse($this->createResponse($statuses));
} catch (RequestParametersTranslatorException $ex) {
$presenter->presentResponse(new ErrorResponse($ex->getMessage()));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (\Throwable $exception) {
$presenter->presentResponse(new ErrorResponse(ServiceException::errorWhileRetrievingServiceStatusesCount()));
$this->error($exception->getMessage(), ['trace' => $exception->getTraceAsString()]);
}
}
/**
* @return ServiceStatusesCount
*/
private function findStatusesCountAsAdmin(): ServiceStatusesCount
{
return $this->repository->findStatusesByRequestParameters($this->requestParameters);
}
/**
* @return ServiceStatusesCount
*/
private function findStatusesCountAsUser(): ServiceStatusesCount
{
$accessGroupIds = array_map(
static fn (AccessGroup $accessGroup): int => $accessGroup->getId(),
$this->accessGroupRepository->findByContact($this->user)
);
return $this->repository->findStatusesByRequestParametersAndAccessGroupIds($this->requestParameters, $accessGroupIds);
}
/**
* @param ServiceStatusesCount $status
*
* @return FindRealTimeServiceStatusesCountResponse
*/
private function createResponse(ServiceStatusesCount $status): FindRealTimeServiceStatusesCountResponse
{
$response = new FindRealTimeServiceStatusesCountResponse();
$response->okStatuses = $status->getTotalOk();
$response->warningStatuses = $status->getTotalWarning();
$response->unknownStatuses = $status->getTotalUnknown();
$response->criticalStatuses = $status->getTotalCritical();
$response->pendingStatuses = $status->getTotalPending();
$response->total = $status->getTotal();
return $response;
}
/**
* @return bool
*/
private function isAuthorized(): bool
{
return $this->user->isAdmin()
|| (
$this->user->hasTopologyRole(Contact::ROLE_MONITORING_RESOURCES_STATUS_RW)
|| $this->user->hasTopologyRole(Contact::ROLE_MONITORING_RW)
);
}
/**
* Indicates if the current user is admin or not (cloud + onPremise context).
*
* @return bool
*/
private function isUserAdmin(): bool
{
if ($this->user->isAdmin()) {
return true;
}
$userAccessGroupNames = array_map(
static fn (AccessGroup $accessGroup): string => $accessGroup->getName(),
$this->accessGroupRepository->findByContact($this->user)
);
return ! empty(array_intersect($userAccessGroupNames, self::AUTHORIZED_ACL_GROUPS));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Application/UseCase/FindRealTimeServiceStatusesCount/FindRealTimeServiceStatusesCountResponse.php | centreon/src/Core/Service/Application/UseCase/FindRealTimeServiceStatusesCount/FindRealTimeServiceStatusesCountResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\UseCase\FindRealTimeServiceStatusesCount;
final class FindRealTimeServiceStatusesCountResponse
{
public int $okStatuses = 0;
public int $warningStatuses = 0;
public int $unknownStatuses = 0;
public int $criticalStatuses = 0;
public int $pendingStatuses = 0;
public int $total = 0;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Application/UseCase/PartialUpdateService/PartialUpdateService.php | centreon/src/Core/Service/Application/UseCase/PartialUpdateService/PartialUpdateService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\UseCase\PartialUpdateService;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Option\OptionService;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Core\Application\Common\UseCase\ConflictResponse;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Application\Common\UseCase\PresenterInterface;
use Core\CommandMacro\Application\Repository\ReadCommandMacroRepositoryInterface;
use Core\CommandMacro\Domain\Model\CommandMacro;
use Core\CommandMacro\Domain\Model\CommandMacroType;
use Core\Common\Application\Repository\ReadVaultRepositoryInterface;
use Core\Common\Application\Repository\WriteVaultRepositoryInterface;
use Core\Common\Application\Type\NoValue;
use Core\Common\Application\UseCase\VaultTrait;
use Core\Common\Infrastructure\Repository\AbstractVaultRepository;
use Core\Domain\Common\GeoCoords;
use Core\Macro\Application\Repository\ReadServiceMacroRepositoryInterface;
use Core\Macro\Application\Repository\WriteServiceMacroRepositoryInterface;
use Core\Macro\Domain\Model\Macro;
use Core\Macro\Domain\Model\MacroDifference;
use Core\Macro\Domain\Model\MacroManager;
use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Core\MonitoringServer\Application\Repository\WriteMonitoringServerRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Core\Service\Application\Exception\ServiceException;
use Core\Service\Application\Model\NotificationTypeConverter;
use Core\Service\Application\Model\YesNoDefaultConverter;
use Core\Service\Application\Repository\ReadServiceRepositoryInterface;
use Core\Service\Application\Repository\WriteServiceRepositoryInterface;
use Core\Service\Domain\Model\Service;
use Core\Service\Domain\Model\ServiceInheritance;
use Core\ServiceCategory\Application\Repository\ReadServiceCategoryRepositoryInterface;
use Core\ServiceCategory\Application\Repository\WriteServiceCategoryRepositoryInterface;
use Core\ServiceCategory\Domain\Model\ServiceCategory;
use Core\ServiceGroup\Application\Repository\ReadServiceGroupRepositoryInterface;
use Core\ServiceGroup\Application\Repository\WriteServiceGroupRepositoryInterface;
use Core\ServiceGroup\Domain\Model\ServiceGroupRelation;
use Utility\Difference\BasicDifference;
final class PartialUpdateService
{
use LoggerTrait;
use VaultTrait;
private const VERTICAL_INHERITANCE_MODE = 1;
/** @var AccessGroup[] */
private array $accessGroups;
public function __construct(
private readonly ReadMonitoringServerRepositoryInterface $readMonitoringServerRepository,
private readonly WriteMonitoringServerRepositoryInterface $writeMonitoringServerRepository,
private readonly ReadServiceRepositoryInterface $readServiceRepository,
private readonly WriteServiceRepositoryInterface $writeServiceRepository,
private readonly ReadServiceMacroRepositoryInterface $readServiceMacroRepository,
private readonly ReadCommandMacroRepositoryInterface $readCommandMacroRepository,
private readonly WriteServiceMacroRepositoryInterface $writeServiceMacroRepository,
private readonly ReadServiceCategoryRepositoryInterface $readServiceCategoryRepository,
private readonly WriteServiceCategoryRepositoryInterface $writeServiceCategoryRepository,
private readonly ReadServiceGroupRepositoryInterface $readServiceGroupRepository,
private readonly WriteServiceGroupRepositoryInterface $writeServiceGroupRepository,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly DataStorageEngineInterface $dataStorageEngine,
private readonly PartialUpdateServiceValidation $validation,
private readonly OptionService $optionService,
private readonly ContactInterface $user,
private readonly bool $isCloudPlatform,
private readonly WriteVaultRepositoryInterface $writeVaultRepository,
private readonly ReadVaultRepositoryInterface $readVaultRepository,
) {
$this->writeVaultRepository->setCustomPath(AbstractVaultRepository::SERVICE_VAULT_PATH);
}
/**
* @param PartialUpdateServiceRequest $request
* @param PresenterInterface $presenter
* @param int $serviceId
*/
public function __invoke(PartialUpdateServiceRequest $request, PresenterInterface $presenter, int $serviceId): void
{
try {
if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_SERVICES_WRITE)) {
$this->error(
"User doesn't have sufficient rights to edit a service",
['user_id' => $this->user->getId()]
);
$presenter->setResponseStatus(
new ForbiddenResponse(ServiceException::editNotAllowed())
);
return;
}
if (! $this->user->isAdmin()) {
$this->accessGroups = $this->readAccessGroupRepository->findByContact($this->user);
$this->validation->accessGroups = $this->accessGroups;
}
if (
(
! $this->user->isAdmin()
&& ! $this->readServiceRepository->existsByAccessGroups($serviceId, $this->accessGroups)
)
|| ! ($service = $this->readServiceRepository->findById($serviceId))
) {
$this->error(
'Service not found',
['service_id' => $serviceId]
);
$presenter->setResponseStatus(new NotFoundResponse('Service'));
return;
}
$this->updatePropertiesInTransaction($request, $service);
$presenter->setResponseStatus(new NoContentResponse());
} catch (ServiceException $ex) {
$presenter->setResponseStatus(
match ($ex->getCode()) {
ServiceException::CODE_CONFLICT => new ConflictResponse($ex),
default => new ErrorResponse($ex),
}
);
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (AssertionFailedException $ex) {
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (\Throwable $ex) {
$presenter->setResponseStatus(new ErrorResponse(ServiceException::errorWhileEditing()));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
}
}
private function updatePropertiesInTransaction(PartialUpdateServiceRequest $request, Service $service): void
{
$this->dataStorageEngine->startTransaction();
try {
if ($this->writeVaultRepository->isVaultConfigured()) {
$this->retrieveServiceUuidFromVault($service->getId());
}
$previousMonitoringServer = $this->readMonitoringServerRepository->findByHost($service->getHostId());
$this->updateService($request, $service);
$this->updateCategories($request, $service);
// Groups MUST be updated after the service as they are dependent on host ID.
$this->updateGroups($request, $service);
// Macros PUST be updated after the service as they are dependent on the template ID.
$this->updateMacros($request, $service);
$newMonitoringServer = $this->readMonitoringServerRepository->findByHost($service->getHostId());
if ($newMonitoringServer !== null) {
$this->writeMonitoringServerRepository->notifyConfigurationChange($newMonitoringServer->getId());
}
if ($previousMonitoringServer !== null) {
// Host change implies a possible monitoring server change, notify previous monitoring server of configuration changes.
$this->writeMonitoringServerRepository->notifyConfigurationChange($previousMonitoringServer->getId());
}
$this->dataStorageEngine->commitTransaction();
} catch (\Throwable $ex) {
$this->error("Rollback of 'PartialUpdateService' transaction", ['trace' => $ex->getTraceAsString()]);
$this->dataStorageEngine->rollbackTransaction();
throw $ex;
}
}
/**
* @param PartialUpdateServiceRequest $dto
* @param Service $service
*
* @throws \Throwable|AssertionFailedException|ServiceException
*/
private function updateService(PartialUpdateServiceRequest $dto, Service $service): void
{
$this->info('PartialUpdateService: update service', ['service_id' => $service->getId()]);
$inheritanceMode = $this->optionService->findSelectedOptions(['inheritance_mode']);
$inheritanceMode = isset($inheritanceMode[0])
? (int) $inheritanceMode[0]->getValue()
: null;
if (! $dto->hostId instanceof NoValue) {
$this->validation->assertIsValidHost($dto->hostId);
$service->setHostId($dto->hostId);
}
// Must be called AFTER host validation
if (! $dto->name instanceof NoValue) {
$this->validation->assertIsValidName($dto->name, $service);
$service->setName($dto->name);
}
if (! $dto->template instanceof NoValue) {
$this->validation->assertIsValidTemplate($dto->template);
$service->setServiceTemplateParentId($dto->template);
}
if (! $dto->activeChecks instanceof NoValue) {
$service->setActiveChecks(YesNoDefaultConverter::fromInt($dto->activeChecks));
}
if (! $dto->passiveCheck instanceof NoValue) {
$service->setPassiveCheck(YesNoDefaultConverter::fromInt($dto->passiveCheck));
}
if (! $dto->volatility instanceof NoValue) {
$service->setVolatility(YesNoDefaultConverter::fromInt($dto->volatility));
}
if (! $dto->checkFreshness instanceof NoValue) {
$service->setCheckFreshness(YesNoDefaultConverter::fromInt($dto->checkFreshness));
}
if (! $dto->eventHandlerEnabled instanceof NoValue) {
$service->setEventHandlerEnabled(YesNoDefaultConverter::fromInt($dto->eventHandlerEnabled));
}
if (! $dto->flapDetectionEnabled instanceof NoValue) {
$service->setFlapDetectionEnabled(YesNoDefaultConverter::fromInt($dto->flapDetectionEnabled));
}
if (! $dto->notificationsEnabled instanceof NoValue) {
$service->setNotificationsEnabled(YesNoDefaultConverter::fromInt($dto->notificationsEnabled));
}
if (! $dto->comment instanceof NoValue) {
$service->setComment($dto->comment);
}
if (! $dto->note instanceof NoValue) {
$service->setNote($dto->note);
}
if (! $dto->noteUrl instanceof NoValue) {
$service->setNoteUrl($dto->noteUrl);
}
if (! $dto->actionUrl instanceof NoValue) {
$service->setActionUrl($dto->actionUrl);
}
if (! $dto->iconAlternativeText instanceof NoValue) {
$service->setIconAlternativeText($dto->iconAlternativeText);
}
if (! $dto->maxCheckAttempts instanceof NoValue) {
$service->setMaxCheckAttempts($dto->maxCheckAttempts);
}
if (! $dto->normalCheckInterval instanceof NoValue) {
$service->setNormalCheckInterval($dto->normalCheckInterval);
}
if (! $dto->retryCheckInterval instanceof NoValue) {
$service->setRetryCheckInterval($dto->retryCheckInterval);
}
if (! $dto->freshnessThreshold instanceof NoValue) {
$service->setFreshnessThreshold($dto->freshnessThreshold);
}
if (! $dto->lowFlapThreshold instanceof NoValue) {
$service->setLowFlapThreshold($dto->lowFlapThreshold);
}
if (! $dto->highFlapThreshold instanceof NoValue) {
$service->setHighFlapThreshold($dto->highFlapThreshold);
}
if (! $dto->notificationInterval instanceof NoValue) {
$service->setNotificationInterval($dto->notificationInterval);
}
if (! $dto->recoveryNotificationDelay instanceof NoValue) {
$service->setRecoveryNotificationDelay($dto->recoveryNotificationDelay);
}
if (! $dto->firstNotificationDelay instanceof NoValue) {
$service->setFirstNotificationDelay($dto->firstNotificationDelay);
}
if (! $dto->acknowledgementTimeout instanceof NoValue) {
$service->setAcknowledgementTimeout($dto->acknowledgementTimeout);
}
// Must be called AFTER template validation
if (! $dto->commandId instanceof NoValue) {
if ($this->isCloudPlatform === false) {
// No assertion on the check command for Saas platform as it will be inherited from the service template.
$this->validation->assertIsValidCommand($dto->commandId, $service->getServiceTemplateParentId());
}
$service->setCommandId($dto->commandId);
}
if (! $dto->graphTemplateId instanceof NoValue) {
$this->validation->assertIsValidGraphTemplate($dto->graphTemplateId);
$service->setGraphTemplateId($dto->graphTemplateId);
}
if (! $dto->eventHandlerId instanceof NoValue) {
$this->validation->assertIsValidEventHandler($dto->eventHandlerId);
$service->setEventHandlerId($dto->eventHandlerId);
}
if (! $dto->notificationTimePeriodId instanceof NoValue) {
$this->validation->assertIsValidTimePeriod($dto->notificationTimePeriodId, 'notification_timeperiod_id');
$service->setNotificationTimePeriodId($dto->notificationTimePeriodId);
}
if (! $dto->checkTimePeriodId instanceof NoValue) {
$this->validation->assertIsValidTimePeriod($dto->checkTimePeriodId, 'check_timeperiod_id');
$service->setCheckTimePeriodId($dto->checkTimePeriodId);
}
if (! $dto->iconId instanceof NoValue) {
$this->validation->assertIsValidIcon($dto->iconId);
$service->setIconId($dto->iconId);
}
if (! $dto->severityId instanceof NoValue) {
$this->validation->assertIsValidSeverity($dto->severityId);
$service->setSeverityId($dto->severityId);
}
if (! $dto->isActivated instanceof NoValue) {
$service->setActivated($dto->isActivated);
}
if (! $dto->geoCoords instanceof NoValue) {
$service->setGeoCoords(
$dto->geoCoords === '' || $dto->geoCoords === null
? null
: GeoCoords::fromString($dto->geoCoords)
);
}
if (! $dto->notificationTypes instanceof NoValue) {
$service->setNotificationTypes(
$dto->notificationTypes === null
? []
: NotificationTypeConverter::fromBits($dto->notificationTypes)
);
}
if (! $dto->commandArguments instanceof NoValue) {
$service->setCommandArguments($dto->commandArguments);
}
if (! $dto->eventHandlerArguments instanceof NoValue) {
$service->setEventHandlerArguments($dto->eventHandlerArguments);
}
if (! $dto->isContactAdditiveInheritance instanceof NoValue) {
$service->setContactAdditiveInheritance(
$inheritanceMode === self::VERTICAL_INHERITANCE_MODE ? $dto->isContactAdditiveInheritance : false
);
}
if (! $dto->isContactGroupAdditiveInheritance instanceof NoValue) {
$service->setContactGroupAdditiveInheritance(
$inheritanceMode === self::VERTICAL_INHERITANCE_MODE ? $dto->isContactGroupAdditiveInheritance : false
);
}
$this->writeServiceRepository->update($service);
}
/**
* @param PartialUpdateServiceRequest $dto
* @param Service $service
*
* @throws \Throwable
*/
private function updateCategories(PartialUpdateServiceRequest $dto, Service $service): void
{
$this->info(
'PartialUpdateService: update categories',
['service_id' => $service->getId(), 'categories' => $dto->categories]
);
if ($dto->categories instanceof NoValue) {
$this->info('Categories not provided, nothing to update');
return;
}
$categoryIds = array_unique($dto->categories);
$this->validation->assertAreValidCategories($categoryIds);
if ($this->user->isAdmin()) {
$originalCategories = $this->readServiceCategoryRepository->findByService($service->getId());
} else {
$originalCategories = $this->readServiceCategoryRepository->findByServiceAndAccessGroups(
$service->getId(),
$this->accessGroups
);
}
$originalCategoryIds = array_map(
static fn (ServiceCategory $category): int => $category->getId(),
$originalCategories
);
$categoryDiff = new BasicDifference($originalCategoryIds, $categoryIds);
$addedCategories = $categoryDiff->getAdded();
$removedCategories = $categoryDiff->getRemoved();
$this->writeServiceCategoryRepository->linkToService($service->getId(), $addedCategories);
$this->writeServiceCategoryRepository->unlinkFromService($service->getId(), $removedCategories);
}
/**
* @param PartialUpdateServiceRequest $dto
* @param Service $service
*
* @throws \Throwable
*/
private function updateGroups(PartialUpdateServiceRequest $dto, Service $service): void
{
$this->info(
'PartialUpdateService: update groups',
['service_id' => $service->getId(), 'groups' => $dto->groups]
);
if ($dto->groups instanceof NoValue) {
$this->info('Groups not provided, nothing to update');
return;
}
$this->validation->assertAreValidGroups($dto->groups);
if ($this->user->isAdmin()) {
$originalGroups = $this->readServiceGroupRepository->findByService($service->getId());
} else {
$originalGroups = $this->readServiceGroupRepository->findByServiceAndAccessGroups(
$service->getId(),
$this->accessGroups
);
}
$this->writeServiceGroupRepository->unlink(array_column($originalGroups, 'relation'));
$groupRelations = [];
foreach (array_unique($dto->groups) as $groupId) {
$groupRelations[] = new ServiceGroupRelation(
$groupId,
$service->getId(),
$service->getHostId()
);
}
$this->writeServiceGroupRepository->link($groupRelations);
}
/**
* @param PartialUpdateServiceRequest $dto
* @param Service $service
*
* @throws \Throwable
*/
private function updateMacros(PartialUpdateServiceRequest $dto, Service $service): void
{
$this->debug(
'PartialUpdateService: update macros',
['service_id' => $service->getId(), 'macros' => $dto->macros]
);
if ($dto->macros instanceof NoValue) {
$this->debug('Macros not provided, nothing to update');
return;
}
/**
* @var array<string,Macro> $directMacros
* @var array<string,Macro> $inheritedMacros
* @var array<string,CommandMacro> $commandMacros
*/
[$directMacros, $inheritedMacros, $commandMacros] = $this->findOriginalMacros($service);
$macros = [];
foreach ($dto->macros as $data) {
$macro = MacroFactory::create($data, $service->getId(), $directMacros, $inheritedMacros);
$macros[$macro->getName()] = $macro;
}
$macrosDiff = new MacroDifference();
$macrosDiff->compute($directMacros, $inheritedMacros, $commandMacros, $macros);
MacroManager::setOrder($macrosDiff, $macros, $directMacros);
foreach ($macrosDiff->removedMacros as $macro) {
$this->updateMacroInVault($macro, 'DELETE');
$this->writeServiceMacroRepository->delete($macro);
}
foreach ($macrosDiff->updatedMacros as $macro) {
$macro = $this->updateMacroInVault($macro, 'INSERT');
$this->writeServiceMacroRepository->update($macro);
}
foreach ($macrosDiff->addedMacros as $macro) {
if ($macro->getDescription() === '') {
$macro->setDescription(
isset($commandMacros[$macro->getName()])
? $commandMacros[$macro->getName()]->getDescription()
: ''
);
}
$macro = $this->updateMacroInVault($macro, 'INSERT');
$this->writeServiceMacroRepository->add($macro);
}
}
/**
* Find macros of a service:
* - macros linked directly,
* - macros linked through template inheritance,
* - macros linked through command inheritance.
*
* @param Service $service
*
* @throws \Throwable
*
* @return array{
* array<string,Macro>,
* array<string,Macro>,
* array<string,CommandMacro>
* }
*/
private function findOriginalMacros(Service $service): array
{
$parentTemplates = $this->readServiceRepository->findParents($service->getId());
$inheritanceLine = ServiceInheritance::createInheritanceLine($service->getId(), $parentTemplates);
$existingMacros = $this->readServiceMacroRepository->findByServiceIds($service->getId(), ...$inheritanceLine);
[$directMacros, $inheritedMacros] = Macro::resolveInheritance(
$existingMacros,
$inheritanceLine,
$service->getId()
);
/** @var array<string,CommandMacro> $commandMacros */
$commandMacros = [];
if ($service->getCommandId() !== null) {
$existingCommandMacros = $this->readCommandMacroRepository->findByCommandIdAndType(
$service->getCommandId(),
CommandMacroType::Service
);
$commandMacros = MacroManager::resolveInheritanceForCommandMacro($existingCommandMacros);
}
return [
$this->writeVaultRepository->isVaultConfigured()
? $this->retrieveMacrosVaultValues($directMacros)
: $directMacros,
$this->writeVaultRepository->isVaultConfigured()
? $this->retrieveMacrosVaultValues($inheritedMacros)
: $inheritedMacros,
$commandMacros,
];
}
/**
* @param int $serviceId
*
* @throws \Throwable
*/
private function retrieveServiceUuidFromVault(int $serviceId): void
{
$macros = $this->readServiceMacroRepository->findByServiceIds($serviceId);
foreach ($macros as $macro) {
if (
$macro->isPassword() === true
&& null !== ($this->uuid = $this->getUuidFromPath($macro->getValue()))
) {
break;
}
}
}
/**
* Upsert or delete macro for vault storage and return macro with updated value (aka vaultPath).
*
* @param Macro $macro
* @param string $action
*
* @throws \Throwable
*
* @return Macro
*/
private function updateMacroInVault(Macro $macro, string $action): Macro
{
if ($this->writeVaultRepository->isVaultConfigured() && $macro->isPassword() === true) {
$macroPrefixName = '_SERVICE' . $macro->getName();
$vaultPaths = $this->writeVaultRepository->upsert(
$this->uuid ?? null,
$action === 'INSERT' ? [$macroPrefixName => $macro->getValue()] : [],
$action === 'DELETE' ? [$macroPrefixName => $macro->getValue()] : [],
);
// No need to update the macro if it is being deleted
if ($action === 'DELETE') {
return $macro;
}
$vaultPath = $vaultPaths[$macroPrefixName];
$this->uuid ??= $this->getUuidFromPath($vaultPath);
$inVaultMacro = new Macro($macro->getId(), $macro->getOwnerId(), $macro->getName(), $vaultPath);
$inVaultMacro->setDescription($macro->getDescription());
$inVaultMacro->setIsPassword($macro->isPassword());
$inVaultMacro->setOrder($macro->getOrder());
return $inVaultMacro;
}
return $macro;
}
/**
* @param array<string,Macro> $macros
*
* @throws \Throwable
*
* @return array<string,Macro>
*/
private function retrieveMacrosVaultValues(array $macros): array
{
$updatedMacros = [];
foreach ($macros as $key => $macro) {
if ($macro->isPassword() === false) {
$updatedMacros[$key] = $macro;
continue;
}
$vaultData = $this->readVaultRepository->findFromPath($macro->getValue());
$vaultKey = '_SERVICE' . $macro->getName();
if (isset($vaultData[$vaultKey])) {
$inVaultMacro = new Macro($macro->getId(), $macro->getOwnerId(), $macro->getName(), $vaultData[$vaultKey]);
$inVaultMacro->setDescription($macro->getDescription());
$inVaultMacro->setIsPassword($macro->isPassword());
$inVaultMacro->setOrder($macro->getOrder());
$updatedMacros[$key] = $inVaultMacro;
}
}
return $updatedMacros;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Application/UseCase/PartialUpdateService/PartialUpdateServiceValidation.php | centreon/src/Core/Service/Application/UseCase/PartialUpdateService/PartialUpdateServiceValidation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\UseCase\PartialUpdateService;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Command\Application\Repository\ReadCommandRepositoryInterface;
use Core\Command\Domain\Model\CommandType;
use Core\Common\Domain\TrimmedString;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
use Core\PerformanceGraph\Application\Repository\ReadPerformanceGraphRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Core\Service\Application\Exception\ServiceException;
use Core\Service\Application\Repository\ReadServiceRepositoryInterface;
use Core\Service\Domain\Model\Service;
use Core\ServiceCategory\Application\Repository\ReadServiceCategoryRepositoryInterface;
use Core\ServiceGroup\Application\Repository\ReadServiceGroupRepositoryInterface;
use Core\ServiceSeverity\Application\Repository\ReadServiceSeverityRepositoryInterface;
use Core\ServiceTemplate\Application\Repository\ReadServiceTemplateRepositoryInterface;
use Core\TimePeriod\Application\Repository\ReadTimePeriodRepositoryInterface;
use Core\ViewImg\Application\Repository\ReadViewImgRepositoryInterface;
class PartialUpdateServiceValidation
{
use LoggerTrait;
/** @var AccessGroup[] */
public array $accessGroups = [];
public function __construct(
private readonly ReadServiceTemplateRepositoryInterface $readServiceTemplateRepository,
private readonly ReadServiceRepositoryInterface $readServiceRepository,
private readonly ReadServiceSeverityRepositoryInterface $serviceSeverityRepository,
private readonly ReadPerformanceGraphRepositoryInterface $performanceGraphRepository,
private readonly ReadCommandRepositoryInterface $commandRepository,
private readonly ReadTimePeriodRepositoryInterface $timePeriodRepository,
private readonly ReadViewImgRepositoryInterface $imageRepository,
private readonly ReadHostRepositoryInterface $readHostRepository,
private readonly ReadServiceCategoryRepositoryInterface $readServiceCategoryRepository,
private readonly ReadServiceGroupRepositoryInterface $readServiceGroupRepository,
private readonly ContactInterface $user,
) {
}
/**
* @param int $hostId
*
* @throws ServiceException
*/
public function assertIsValidHost(int $hostId): void
{
$hostIdFound = $this->user->isAdmin()
? $this->readHostRepository->exists($hostId)
: $this->readHostRepository->existsByAccessGroups($hostId, $this->accessGroups);
if ($hostIdFound === false) {
throw ServiceException::idDoesNotExist('host_id', $hostId);
}
}
/**
* @param string $name
* @param Service $service
*
* @throws \Throwable
*/
public function assertIsValidName(string $name, Service $service): void
{
if ($service->isNameIdentical($name)) {
return;
}
$nameToCheck = new TrimmedString(Service::formatName($name));
$serviceNamesByHost = $this->readServiceRepository->findServiceNamesByHost($service->getHostId());
if ($serviceNamesByHost === null) {
// Should not be called if this assertion is called after assertion on host IDs
throw ServiceException::idDoesNotExist('host', $service->getHostId());
}
if ($serviceNamesByHost->contains($nameToCheck)) {
throw ServiceException::nameAlreadyExists((string) $nameToCheck, $service->getHostId());
}
}
/**
* @param int|null $serviceTemplateId
*
* @throws ServiceException
* @throws \Throwable
*/
public function assertIsValidTemplate(?int $serviceTemplateId): void
{
if ($serviceTemplateId !== null && ! $this->readServiceTemplateRepository->exists($serviceTemplateId)) {
$this->error('Service does not exist', ['service_template_id' => $serviceTemplateId]);
throw ServiceException::idDoesNotExist('service_template_id', $serviceTemplateId);
}
}
/**
* @param int|null $commandId
* @param int|null $serviceTemplateId
*
* @throws ServiceException
*/
public function assertIsValidCommand(?int $commandId, ?int $serviceTemplateId): void
{
if ($commandId === null && $serviceTemplateId === null) {
throw ServiceException::checkCommandCannotBeNull();
}
if ($commandId !== null && ! $this->commandRepository->existsByIdAndCommandType($commandId, CommandType::Check)) {
$this->error('The check command does not exist', ['check_command_id' => $commandId]);
throw ServiceException::idDoesNotExist('check_command_id', $commandId);
}
}
/**
* @param int|null $graphTemplateId
*
* @throws ServiceException
* @throws \Throwable
*/
public function assertIsValidGraphTemplate(?int $graphTemplateId): void
{
if ($graphTemplateId !== null && ! $this->performanceGraphRepository->exists($graphTemplateId)) {
$this->error('Performance graph does not exist', ['graph_template_id' => $graphTemplateId]);
throw ServiceException::idDoesNotExist('graph_template_id', $graphTemplateId);
}
}
/**
* @param int|null $eventHandlerId
*
* @throws ServiceException
*/
public function assertIsValidEventHandler(?int $eventHandlerId): void
{
if ($eventHandlerId !== null && ! $this->commandRepository->exists($eventHandlerId)) {
$this->error('Event handler command does not exist', ['event_handler_command_id' => $eventHandlerId]);
throw ServiceException::idDoesNotExist('event_handler_command_id', $eventHandlerId);
}
}
/**
* @param int|null $timePeriodId
* @param ?string $propertyName
*
* @throws ServiceException
* @throws \Throwable
*/
public function assertIsValidTimePeriod(?int $timePeriodId, ?string $propertyName = null): void
{
if ($timePeriodId !== null && ! $this->timePeriodRepository->exists($timePeriodId)) {
$this->error('Time period does not exist', [$propertyName ?? 'timeperiod' => $timePeriodId]);
throw ServiceException::idDoesNotExist($propertyName ?? 'timeperiod', $timePeriodId);
}
}
/**
* @param int|null $iconId
*
* @throws ServiceException
* @throws \Throwable
*/
public function assertIsValidIcon(?int $iconId): void
{
if ($iconId !== null && ! $this->imageRepository->existsOne($iconId)) {
$this->error('Icon does not exist', ['icon_id' => $iconId]);
throw ServiceException::idDoesNotExist('icon_id', $iconId);
}
}
/**
* @param int|null $severityId
*
* @throws ServiceException
* @throws \Throwable
*/
public function assertIsValidSeverity(?int $severityId): void
{
if ($severityId !== null) {
$exists = ($this->accessGroups === [])
? $this->serviceSeverityRepository->exists($severityId)
: $this->serviceSeverityRepository->existsByAccessGroups($severityId, $this->accessGroups);
if (! $exists) {
$this->error('Service severity does not exist', ['severity_id' => $severityId]);
throw ServiceException::idDoesNotExist('severity_id', $severityId);
}
}
}
/**
* @param list<int> $categoriesIds
*
* @throws ServiceException
* @throws \Throwable
*/
public function assertAreValidCategories(array $categoriesIds): void
{
if ($this->user->isAdmin()) {
$categoriesIdsFound = $this->readServiceCategoryRepository->findAllExistingIds(
$categoriesIds
);
} else {
$categoriesIdsFound = $this->readServiceCategoryRepository->findAllExistingIdsByAccessGroups(
$categoriesIds,
$this->accessGroups
);
}
if ([] !== ($idsNotFound = array_diff($categoriesIds, $categoriesIdsFound))) {
throw ServiceException::idsDoNotExist('service_categories', $idsNotFound);
}
}
/**
* @param int[] $groupIds
*
* @throws ServiceException
* @throws \Throwable
*/
public function assertAreValidGroups(array $groupIds): void
{
if ($groupIds === []) {
return;
}
if ($this->user->isAdmin()) {
$groupIdsFound = $this->readServiceGroupRepository->exist($groupIds);
} else {
$groupIdsFound = $this->readServiceGroupRepository->existByAccessGroups(
$groupIds,
$this->accessGroups
);
}
if ([] !== ($idsNotFound = array_diff($groupIds, $groupIdsFound))) {
throw ServiceException::idsDoNotExist('service_groups', $idsNotFound);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Application/UseCase/PartialUpdateService/MacroDto.php | centreon/src/Core/Service/Application/UseCase/PartialUpdateService/MacroDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\UseCase\PartialUpdateService;
class MacroDto
{
public function __construct(
public string $name,
public ?string $value,
public bool $isPassword,
public ?string $description,
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Application/UseCase/PartialUpdateService/MacroFactory.php | centreon/src/Core/Service/Application/UseCase/PartialUpdateService/MacroFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\UseCase\PartialUpdateService;
use Assert\AssertionFailedException;
use Core\Macro\Domain\Model\Macro;
final class MacroFactory
{
/**
* Create macros object from the request data.
* Use direct and inherited macros to retrieve value of macro with isPassword when not provided in dto.
*
* @param MacroDto $dto
* @param int $serviceId
* @param array<string,Macro> $directMacros
* @param array<string,Macro> $inheritedMacros
*
* @throws \Throwable
* @throws AssertionFailedException
*
* @return Macro
*/
public static function create(MacroDto $dto, int $serviceId, array $directMacros, array $inheritedMacros): Macro
{
$macroName = mb_strtoupper($dto->name);
$macroValue = $dto->value ?? '';
$passwordHasNotChanged = ($dto->value === null) && $dto->isPassword;
// Note: do not handle vault storage at the moment
if ($passwordHasNotChanged) {
$macroValue = match (true) {
// retrieve actual password value
isset($directMacros[$macroName]) => $directMacros[$macroName]->getValue(),
isset($inheritedMacros[$macroName]) => $inheritedMacros[$macroName]->getValue(),
default => $macroValue,
};
}
$macro = new Macro(
null,
$serviceId,
$dto->name,
$macroValue,
);
$macro->setIsPassword($dto->isPassword);
$macro->setDescription($dto->description ?? '');
return $macro;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Application/UseCase/PartialUpdateService/PartialUpdateServiceRequest.php | centreon/src/Core/Service/Application/UseCase/PartialUpdateService/PartialUpdateServiceRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\UseCase\PartialUpdateService;
use Core\Common\Application\Type\NoValue;
final class PartialUpdateServiceRequest
{
/**
* @param NoValue|string $name
* @param NoValue|int $hostId
* @param NoValue|null|int $template
* @param NoValue|int $activeChecks
* @param NoValue|int $passiveCheck
* @param NoValue|int $volatility
* @param NoValue|int $checkFreshness
* @param NoValue|int $eventHandlerEnabled
* @param NoValue|int $flapDetectionEnabled
* @param NoValue|int $notificationsEnabled
* @param NoValue|null|string $comment
* @param NoValue|null|string $note
* @param NoValue|null|string $noteUrl
* @param NoValue|null|string $actionUrl
* @param NoValue|null|string $iconAlternativeText
* @param NoValue|null|string $geoCoords
* @param NoValue|null|int $commandId
* @param NoValue|null|int $graphTemplateId
* @param NoValue|null|int $eventHandlerId
* @param NoValue|null|int $notificationTimePeriodId
* @param NoValue|null|int $checkTimePeriodId
* @param NoValue|null|int $iconId
* @param NoValue|null|int $severityId
* @param NoValue|null|int $maxCheckAttempts
* @param NoValue|null|int $normalCheckInterval
* @param NoValue|null|int $retryCheckInterval
* @param NoValue|null|int $freshnessThreshold
* @param NoValue|null|int $lowFlapThreshold
* @param NoValue|null|int $highFlapThreshold
* @param NoValue|null|int $notificationTypes
* @param NoValue|null|int $notificationInterval
* @param NoValue|null|int $recoveryNotificationDelay
* @param NoValue|null|int $firstNotificationDelay
* @param NoValue|null|int $acknowledgementTimeout
* @param NoValue|string[] $commandArguments
* @param NoValue|string[] $eventHandlerArguments
* @param NoValue|MacroDto[] $macros
* @param NoValue|int[] $categories
* @param NoValue|int[] $groups
* @param NoValue|bool $isContactAdditiveInheritance
* @param NoValue|bool $isContactGroupAdditiveInheritance
* @param NoValue|bool $isActivated
*/
public function __construct(
public NoValue|string $name = new NoValue(),
public NoValue|int $hostId = new NoValue(),
public NoValue|null|int $template = new NoValue(),
public NoValue|int $activeChecks = new NoValue(),
public NoValue|int $passiveCheck = new NoValue(),
public NoValue|int $volatility = new NoValue(),
public NoValue|int $checkFreshness = new NoValue(),
public NoValue|int $eventHandlerEnabled = new NoValue(),
public NoValue|int $flapDetectionEnabled = new NoValue(),
public NoValue|int $notificationsEnabled = new NoValue(),
public NoValue|null|string $comment = new NoValue(),
public NoValue|null|string $note = new NoValue(),
public NoValue|null|string $noteUrl = new NoValue(),
public NoValue|null|string $actionUrl = new NoValue(),
public NoValue|null|string $iconAlternativeText = new NoValue(),
public NoValue|null|string $geoCoords = new NoValue(),
public NoValue|null|int $commandId = new NoValue(),
public NoValue|null|int $graphTemplateId = new NoValue(),
public NoValue|null|int $eventHandlerId = new NoValue(),
public NoValue|null|int $notificationTimePeriodId = new NoValue(),
public NoValue|null|int $checkTimePeriodId = new NoValue(),
public NoValue|null|int $iconId = new NoValue(),
public NoValue|null|int $severityId = new NoValue(),
public NoValue|null|int $maxCheckAttempts = new NoValue(),
public NoValue|null|int $normalCheckInterval = new NoValue(),
public NoValue|null|int $retryCheckInterval = new NoValue(),
public NoValue|null|int $freshnessThreshold = new NoValue(),
public NoValue|null|int $lowFlapThreshold = new NoValue(),
public NoValue|null|int $highFlapThreshold = new NoValue(),
public NoValue|null|int $notificationTypes = new NoValue(),
public NoValue|null|int $notificationInterval = new NoValue(),
public NoValue|null|int $recoveryNotificationDelay = new NoValue(),
public NoValue|null|int $firstNotificationDelay = new NoValue(),
public NoValue|null|int $acknowledgementTimeout = new NoValue(),
public NoValue|array $commandArguments = new NoValue(),
public NoValue|array $eventHandlerArguments = new NoValue(),
public NoValue|array $macros = new NoValue(),
public NoValue|array $categories = new NoValue(),
public NoValue|array $groups = new NoValue(),
public NoValue|bool $isContactAdditiveInheritance = new NoValue(),
public NoValue|bool $isContactGroupAdditiveInheritance = new NoValue(),
public NoValue|bool $isActivated = new NoValue(),
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Application/UseCase/DeleteService/DeleteService.php | centreon/src/Core/Service/Application/UseCase/DeleteService/DeleteService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\UseCase\DeleteService;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Application\Common\UseCase\PresenterInterface;
use Core\Common\Application\Repository\WriteVaultRepositoryInterface;
use Core\Common\Application\UseCase\VaultTrait;
use Core\Common\Infrastructure\Repository\AbstractVaultRepository;
use Core\Macro\Application\Repository\ReadServiceMacroRepositoryInterface;
use Core\MonitoringServer\Application\Repository\WriteMonitoringServerRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Service\Application\Exception\ServiceException;
use Core\Service\Application\Repository\ReadServiceRepositoryInterface;
use Core\Service\Application\Repository\WriteServiceRepositoryInterface;
final class DeleteService
{
use LoggerTrait;
use VaultTrait;
/**
* @param ReadServiceRepositoryInterface $readRepository
* @param WriteServiceRepositoryInterface $writeRepository
* @param ReadAccessGroupRepositoryInterface $readAccessGroupRepository
* @param ContactInterface $user
* @param WriteMonitoringServerRepositoryInterface $writeMonitoringServerRepository
* @param DataStorageEngineInterface $storageEngine
* @param WriteVaultRepositoryInterface $writeVaultRepository
* @param ReadServiceMacroRepositoryInterface $readServiceMacroRepository
*/
public function __construct(
private readonly ReadServiceRepositoryInterface $readRepository,
private readonly WriteServiceRepositoryInterface $writeRepository,
private readonly WriteMonitoringServerRepositoryInterface $writeMonitoringServerRepository,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly DataStorageEngineInterface $storageEngine,
private readonly ContactInterface $user,
private readonly WriteVaultRepositoryInterface $writeVaultRepository,
private readonly ReadServiceMacroRepositoryInterface $readServiceMacroRepository,
) {
$this->writeVaultRepository->setCustomPath(AbstractVaultRepository::SERVICE_VAULT_PATH);
}
/**
* @param int $serviceId
* @param PresenterInterface $presenter
*/
public function __invoke(int $serviceId, PresenterInterface $presenter): void
{
try {
if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_SERVICES_WRITE)) {
$this->error(
"User doesn't have sufficient rights to delete a service",
['user_id' => $this->user->getId(), 'service_id' => $serviceId]
);
$presenter->setResponseStatus(
new ForbiddenResponse(ServiceException::deleteNotAllowed())
);
return;
}
if ($this->user->isAdmin()) {
$doesServiceExists = $this->readRepository->exists($serviceId);
} else {
$accessGroups = $this->readAccessGroupRepository->findByContact($this->user);
$doesServiceExists = $this->readRepository->existsByAccessGroups($serviceId, $accessGroups);
}
if ($doesServiceExists === false) {
$this->error('Service not found', ['service_id' => $serviceId]);
$presenter->setResponseStatus(new NotFoundResponse('Service'));
return;
}
try {
$this->storageEngine->startTransaction();
$monitoringServerId = $this->readRepository->findMonitoringServerId($serviceId);
$this->info("Delete service #{$serviceId}");
if ($this->writeVaultRepository->isVaultConfigured()) {
$this->retrieveServiceUuidFromVault($serviceId);
if ($this->uuid !== null) {
$this->writeVaultRepository->delete($this->uuid);
}
}
$this->writeRepository->delete($serviceId);
$this->info("Notify monitoiring server #{$monitoringServerId} of configuration change");
$this->writeMonitoringServerRepository->notifyConfigurationChange($monitoringServerId);
$this->storageEngine->commitTransaction();
} catch (\Throwable $ex) {
$this->error("Rollback of 'Delete Service' transaction.");
$this->storageEngine->rollbackTransaction();
throw $ex;
}
$presenter->setResponseStatus(new NoContentResponse());
$this->info(
'Service deleted',
[
'service_id' => $serviceId,
'user_id' => $this->user->getId(),
]
);
} catch (\Throwable $ex) {
$presenter->setResponseStatus(new ErrorResponse(ServiceException::errorWhileDeleting($ex)));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
}
}
/**
* @param int $serviceId
*
* @throws \Throwable
*/
private function retrieveServiceUuidFromVault(int $serviceId): void
{
$macros = $this->readServiceMacroRepository->findByServiceIds($serviceId);
foreach ($macros as $macro) {
if (
$macro->isPassword() === true
&& null !== ($this->uuid = $this->getUuidFromPath($macro->getValue()))
) {
break;
}
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Application/UseCase/DeployServices/DeployServices.php | centreon/src/Core/Service/Application/UseCase/DeployServices/DeployServices.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\UseCase\DeployServices;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
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\Common\Domain\TrimmedString;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Core\Service\Application\Repository\ReadServiceRepositoryInterface;
use Core\Service\Application\Repository\WriteRealTimeServiceRepositoryInterface;
use Core\Service\Application\Repository\WriteServiceRepositoryInterface;
use Core\Service\Domain\Model\NewService;
use Core\Service\Domain\Model\Service;
use Core\ServiceTemplate\Application\Repository\ReadServiceTemplateRepositoryInterface;
final class DeployServices
{
use LoggerTrait;
public function __construct(
private readonly ContactInterface $contact,
private readonly DataStorageEngineInterface $dataStorageEngine,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly ReadHostRepositoryInterface $readHostRepository,
private readonly ReadServiceRepositoryInterface $readServiceRepository,
private readonly ReadServiceTemplateRepositoryInterface $readServiceTemplateRepository,
private readonly WriteServiceRepositoryInterface $writeServiceRepository,
private readonly WriteRealTimeServiceRepositoryInterface $writeRealTimeServiceRepository,
) {
}
/**
* @param DeployServicesPresenterInterface $presenter
* @param int $hostId
*/
public function __invoke(DeployServicesPresenterInterface $presenter, int $hostId): void
{
try {
if (
! $this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_HOSTS_READ)
&& ! $this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_HOSTS_WRITE)
) {
$this->error('User does not have sufficient rights', ['user_id' => $this->contact->getId()]);
$response = new ForbiddenResponse('User does not have sufficient rights');
$presenter->presentResponse($response);
return;
}
$hostParents = $this->readHostRepository->findParents($hostId);
if ($hostParents === []) {
$this->info(
'Services cannot be deployed: requested host does not have associated host templates',
['host_id' => $hostId]
);
$response = new NoContentResponse();
$presenter->presentResponse($response);
return;
}
if ($this->contact->isAdmin()) {
if (! $this->readHostRepository->exists($hostId)) {
$this->error('Host with provided id is not found', ['host_id' => $hostId]);
$response = new NotFoundResponse('Host');
$presenter->presentResponse($response);
return;
}
$deployedServices = $this->deployServicesInTransaction($hostParents, $hostId);
} else {
$accessGroups = $this->readAccessGroupRepository->findByContact($this->contact);
if (! $this->readHostRepository->existsByAccessGroups($hostId, $accessGroups)) {
$this->error('Host with provided id is not found', ['host_id' => $hostId]);
$response = new NotFoundResponse('Host');
$presenter->presentResponse($response);
return;
}
$deployedServices = $this->deployServicesInTransaction($hostParents, $hostId, $accessGroups);
}
if ($deployedServices === []) {
$this->info(
'Services cannot be deployed: requested host already contains all deployed services',
['host_id' => $hostId]
);
$response = new NoContentResponse();
$presenter->presentResponse($response);
return;
}
$response = $this->createResponse($deployedServices);
$presenter->presentResponse($response);
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$response = new ErrorResponse($ex->getMessage());
$presenter->presentResponse($response);
}
}
/**
* @param Service[] $deployedServices
*
* @return DeployServicesResponse
*/
private function createResponse(array $deployedServices): DeployServicesResponse
{
$response = new DeployServicesResponse();
foreach ($deployedServices as $deployedService) {
$deployServiceDto = new DeployServiceDto();
$deployServiceDto->id = $deployedService->getId();
$deployServiceDto->name = $deployedService->getName();
$deployServiceDto->hostId = $deployedService->getHostId();
$deployServiceDto->geoCoords = $deployedService->getGeoCoords()?->__toString();
$deployServiceDto->comment = $deployedService->getComment();
$deployServiceDto->serviceTemplateId = $deployedService->getServiceTemplateParentId();
$deployServiceDto->commandId = $deployedService->getCommandId();
$deployServiceDto->commandArguments = $deployedService->getCommandArguments();
$deployServiceDto->checkTimePeriodId = $deployedService->getCheckTimePeriodId();
$deployServiceDto->maxCheckAttempts = $deployedService->getMaxCheckAttempts();
$deployServiceDto->normalCheckInterval = $deployedService->getNormalCheckInterval();
$deployServiceDto->retryCheckInterval = $deployedService->getRetryCheckInterval();
$deployServiceDto->activeChecksEnabled = $deployedService->getActiveChecks();
$deployServiceDto->passiveChecksEnabled = $deployedService->getPassiveCheck();
$deployServiceDto->volatilityEnabled = $deployedService->getVolatility();
$deployServiceDto->notificationsEnabled = $deployedService->getNotificationsEnabled();
$deployServiceDto->isContactAdditiveInheritance = $deployedService->isContactAdditiveInheritance();
$deployServiceDto->isContactGroupAdditiveInheritance = $deployedService->isContactGroupAdditiveInheritance();
$deployServiceDto->notificationInterval = $deployedService->getNotificationInterval();
$deployServiceDto->notificationTimePeriodId = $deployedService->getNotificationTimePeriodId();
$deployServiceDto->notificationTypes = $deployedService->getNotificationTypes();
$deployServiceDto->firstNotificationDelay = $deployedService->getFirstNotificationDelay();
$deployServiceDto->recoveryNotificationDelay = $deployedService->getRecoveryNotificationDelay();
$deployServiceDto->acknowledgementTimeout = $deployedService->getAcknowledgementTimeout();
$deployServiceDto->checkFreshness = $deployedService->getCheckFreshness();
$deployServiceDto->freshnessThreshold = $deployedService->getFreshnessThreshold();
$deployServiceDto->flapDetectionEnabled = $deployedService->getFlapDetectionEnabled();
$deployServiceDto->lowFlapThreshold = $deployedService->getLowFlapThreshold();
$deployServiceDto->highFlapThreshold = $deployedService->getHighFlapThreshold();
$deployServiceDto->eventHandlerEnabled = $deployedService->getEventHandlerEnabled();
$deployServiceDto->eventHandlerCommandId = $deployedService->getEventHandlerId();
$deployServiceDto->eventHandlerArguments = $deployedService->getEventHandlerArguments();
$deployServiceDto->graphTemplateId = $deployedService->getGraphTemplateId();
$deployServiceDto->note = $deployedService->getNote();
$deployServiceDto->noteUrl = $deployedService->getNoteUrl();
$deployServiceDto->actionUrl = $deployedService->getActionUrl();
$deployServiceDto->iconId = $deployedService->getIconId();
$deployServiceDto->iconAlternative = $deployedService->getIconAlternativeText();
$deployServiceDto->severityId = $deployedService->getSeverityId();
$deployServiceDto->isActivated = $deployedService->isActivated();
$response->services[] = $deployServiceDto;
}
return $response;
}
/**
* @param array<array{parent_id:int,child_id:int,order:int}> $hostParents
* @param int $hostId
* @param AccessGroup[] $accessGroups
*
* @throws \Throwable
*
* @return Service[]
*/
private function deployServicesInTransaction(array $hostParents, int $hostId, array $accessGroups = []): array
{
$deployedServices = [];
$this->dataStorageEngine->startTransaction();
try {
foreach ($hostParents as $hostParent) {
$serviceTemplates = $this->readServiceTemplateRepository->findByHostId($hostParent['parent_id']);
foreach ($serviceTemplates as $serviceTemplate) {
$serviceNames = $this->readServiceRepository->findServiceNamesByHost($hostId);
if (
$serviceNames === null
|| $serviceNames->contains(new TrimmedString($serviceTemplate->getAlias()))
) {
continue;
}
$service = new NewService(
$serviceTemplate->getAlias(),
$hostId,
null // command line must be inherited from template when you deploy services from a host
);
$service->setServiceTemplateParentId($serviceTemplate->getId());
$service->setActivated(true);
$serviceId = $this->writeServiceRepository->add($service);
$service = $this->readServiceRepository->findById($serviceId);
if ($service !== null) {
$deployedServices[] = $service;
}
}
}
if ($accessGroups !== []) {
foreach ($deployedServices as $deployedService) {
$this->writeRealTimeServiceRepository->addServiceToResourceAcls(
$hostId,
$deployedService->getId(),
$accessGroups
);
}
}
$this->dataStorageEngine->commitTransaction();
return $deployedServices;
} catch (\Throwable $ex) {
$this->error("Rollback of 'DeployServices' transaction", ['trace' => $ex->getTraceAsString()]);
$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/Service/Application/UseCase/DeployServices/DeployServiceDto.php | centreon/src/Core/Service/Application/UseCase/DeployServices/DeployServiceDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\UseCase\DeployServices;
use Core\Common\Domain\YesNoDefault;
use Core\Service\Domain\Model\NotificationType;
final class DeployServiceDto
{
public int $id = 0;
public string $name = '';
public int $hostId = 0;
public ?string $geoCoords = null;
public ?string $comment = null;
public ?int $serviceTemplateId = null;
public ?int $commandId = null;
/** @var string[] */
public array $commandArguments = [];
public ?int $checkTimePeriodId = null;
public ?int $maxCheckAttempts = null;
public ?int $normalCheckInterval = null;
public ?int $retryCheckInterval = null;
public YesNoDefault $activeChecksEnabled = YesNoDefault::Default;
public YesNoDefault $passiveChecksEnabled = YesNoDefault::Default;
public YesNoDefault $volatilityEnabled = YesNoDefault::Default;
public YesNoDefault $notificationsEnabled = YesNoDefault::Default;
public bool $isContactAdditiveInheritance = false;
public bool $isContactGroupAdditiveInheritance = false;
public ?int $notificationInterval = null;
public ?int $notificationTimePeriodId = null;
/** @var NotificationType[] */
public array $notificationTypes = [];
public ?int $firstNotificationDelay = null;
public ?int $recoveryNotificationDelay = null;
public ?int $acknowledgementTimeout = null;
public YesNoDefault $checkFreshness = YesNoDefault::Default;
public ?int $freshnessThreshold = null;
public YesNoDefault $flapDetectionEnabled = YesNoDefault::Default;
public ?int $lowFlapThreshold = null;
public ?int $highFlapThreshold = null;
public YesNoDefault $eventHandlerEnabled = YesNoDefault::Default;
public ?int $eventHandlerCommandId = null;
/** @var string[] */
public array $eventHandlerArguments = [];
public ?int $graphTemplateId = null;
public ?string $note = null;
public ?string $noteUrl = null;
public ?string $actionUrl = null;
public ?int $iconId = null;
public ?string $iconAlternative = null;
public ?int $severityId = null;
public bool $isActivated = false;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Application/UseCase/DeployServices/DeployServicesPresenterInterface.php | centreon/src/Core/Service/Application/UseCase/DeployServices/DeployServicesPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\UseCase\DeployServices;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface DeployServicesPresenterInterface
{
/**
* @param DeployServicesResponse|ResponseStatusInterface $response
*/
public function presentResponse(DeployServicesResponse|ResponseStatusInterface $response): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Application/UseCase/DeployServices/DeployServicesResponse.php | centreon/src/Core/Service/Application/UseCase/DeployServices/DeployServicesResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\UseCase\DeployServices;
final class DeployServicesResponse
{
/** @var DeployServiceDto[] */
public array $services = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Application/UseCase/DeleteServices/DeleteServicesRequest.php | centreon/src/Core/Service/Application/UseCase/DeleteServices/DeleteServicesRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\UseCase\DeleteServices;
final readonly class DeleteServicesRequest
{
/**
* @param int[] $serviceIds
*/
public function __construct(public array $serviceIds)
{
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Application/UseCase/DeleteServices/DeleteServices.php | centreon/src/Core/Service/Application/UseCase/DeleteServices/DeleteServices.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\UseCase\DeleteServices;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Common\Domain\ResponseCodeEnum;
use Core\MonitoringServer\Application\Repository\WriteMonitoringServerRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Service\Application\Exception\ServiceException;
use Core\Service\Application\Repository\ReadServiceRepositoryInterface;
use Core\Service\Application\Repository\WriteServiceRepositoryInterface;
final class DeleteServices
{
use LoggerTrait;
/**
* @param ContactInterface $user
* @param WriteServiceRepositoryInterface $writeServiceRepository
* @param ReadServiceRepositoryInterface $readServiceRepository
* @param WriteMonitoringServerRepositoryInterface $writeMonitoringServerRepository
* @param ReadAccessGroupRepositoryInterface $readAccessGroupRepository
* @param DataStorageEngineInterface $storageEngine
*/
public function __construct(
private readonly ContactInterface $user,
private readonly WriteServiceRepositoryInterface $writeServiceRepository,
private readonly ReadServiceRepositoryInterface $readServiceRepository,
private readonly WriteMonitoringServerRepositoryInterface $writeMonitoringServerRepository,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly DataStorageEngineInterface $storageEngine,
) {
}
/**
* @param DeleteServicesRequest $request
*
* @return DeleteServicesResponse
*/
public function __invoke(DeleteServicesRequest $request): DeleteServicesResponse
{
$results = [];
foreach ($request->serviceIds as $serviceId) {
$statusResponse = new DeleteServicesStatusResponse();
$statusResponse->id = $serviceId;
try {
if (! $this->serviceExists($serviceId)) {
$statusResponse->status = ResponseCodeEnum::NotFound;
$statusResponse->message = (new NotFoundResponse('Service'))->getMessage();
$results[] = $statusResponse;
continue;
}
if (! $this->storageEngine->isAlreadyInTransaction()) {
$this->storageEngine->startTransaction();
}
$this->writeServiceRepository->delete($serviceId);
$this->writeMonitoringServerRepository->notifyConfigurationChange(
monitoringServerId: $this->readServiceRepository->findMonitoringServerId($serviceId)
);
$this->storageEngine->commitTransaction();
$results[] = $statusResponse;
} catch (\Throwable $ex) {
$this->error(
"Error while deleting services : {$ex->getMessage()}",
[
'serviceIds' => $request->serviceIds,
'current_serviceId' => $serviceId,
'exception' => ['message' => $ex->getMessage(), 'trace' => $ex->getTraceAsString()],
]
);
if (! $this->storageEngine->isAlreadyInTransaction()) {
$this->info('Rollback transaction for service ID ' . $serviceId);
$this->storageEngine->rollbackTransaction();
}
$statusResponse->status = ResponseCodeEnum::Error;
$statusResponse->message = ServiceException::errorWhileDeleting($ex)->getMessage();
$results[] = $statusResponse;
}
}
return new DeleteServicesResponse($results);
}
/**
* Check that service exists for the user regarding ACLs
*
* @param int $serviceId
*
* @return bool
*/
private function serviceExists(int $serviceId): bool
{
return $this->user->isAdmin()
? $this->readServiceRepository->exists($serviceId)
: $this->readServiceRepository->existsByAccessGroups(
$serviceId,
$this->readAccessGroupRepository->findByContact($this->user)
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Application/UseCase/DeleteServices/DeleteServicesResponse.php | centreon/src/Core/Service/Application/UseCase/DeleteServices/DeleteServicesResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\UseCase\DeleteServices;
use Core\Application\Common\UseCase\BulkResponseInterface;
final class DeleteServicesResponse implements BulkResponseInterface
{
/**
* @param DeleteServicesStatusResponse[] $results
*/
public function __construct(private readonly array $results)
{
}
/**
* {@inheritDoc}
*
* @return DeleteServicesStatusResponse[]
*/
public function getData(): 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/Service/Application/UseCase/DeleteServices/DeleteServicesStatusResponse.php | centreon/src/Core/Service/Application/UseCase/DeleteServices/DeleteServicesStatusResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\UseCase\DeleteServices;
use Core\Common\Domain\ResponseCodeEnum;
final class DeleteServicesStatusResponse
{
public int $id = 0;
public ResponseCodeEnum $status = ResponseCodeEnum::OK;
public ?string $message = 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/Service/Application/UseCase/AddService/AddService.php | centreon/src/Core/Service/Application/UseCase/AddService/AddService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\UseCase\AddService;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Option\OptionService;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Core\Application\Common\UseCase\ConflictResponse;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\CommandMacro\Application\Repository\ReadCommandMacroRepositoryInterface;
use Core\CommandMacro\Domain\Model\CommandMacro;
use Core\CommandMacro\Domain\Model\CommandMacroType;
use Core\Common\Application\Repository\ReadVaultRepositoryInterface;
use Core\Common\Application\Repository\WriteVaultRepositoryInterface;
use Core\Common\Application\UseCase\VaultTrait;
use Core\Common\Infrastructure\Repository\AbstractVaultRepository;
use Core\Macro\Application\Repository\ReadServiceMacroRepositoryInterface;
use Core\Macro\Application\Repository\WriteServiceMacroRepositoryInterface;
use Core\Macro\Domain\Model\Macro;
use Core\Macro\Domain\Model\MacroDifference;
use Core\Macro\Domain\Model\MacroManager;
use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Core\MonitoringServer\Application\Repository\WriteMonitoringServerRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Core\Service\Application\Exception\ServiceException;
use Core\Service\Application\Repository\ReadServiceRepositoryInterface;
use Core\Service\Application\Repository\WriteRealTimeServiceRepositoryInterface;
use Core\Service\Application\Repository\WriteServiceRepositoryInterface;
use Core\Service\Domain\Model\NewService;
use Core\Service\Domain\Model\Service;
use Core\Service\Domain\Model\ServiceInheritance;
use Core\ServiceCategory\Application\Repository\ReadServiceCategoryRepositoryInterface;
use Core\ServiceCategory\Application\Repository\WriteServiceCategoryRepositoryInterface;
use Core\ServiceCategory\Domain\Model\ServiceCategory;
use Core\ServiceGroup\Application\Repository\ReadServiceGroupRepositoryInterface;
use Core\ServiceGroup\Application\Repository\WriteServiceGroupRepositoryInterface;
use Core\ServiceGroup\Domain\Model\ServiceGroup;
use Core\ServiceGroup\Domain\Model\ServiceGroupRelation;
final class AddService
{
use LoggerTrait;
use VaultTrait;
/** @var AccessGroup[] */
private array $accessGroups = [];
public function __construct(
private readonly ReadMonitoringServerRepositoryInterface $readMonitoringServerRepository,
private readonly WriteMonitoringServerRepositoryInterface $writeMonitoringServerRepository,
private readonly ReadServiceRepositoryInterface $readServiceRepository,
private readonly WriteServiceRepositoryInterface $writeServiceRepository,
private readonly ReadServiceMacroRepositoryInterface $readServiceMacroRepository,
private readonly ReadCommandMacroRepositoryInterface $readCommandMacroRepository,
private readonly WriteServiceMacroRepositoryInterface $writeServiceMacroRepository,
private readonly DataStorageEngineInterface $storageEngine,
private readonly ReadServiceCategoryRepositoryInterface $readServiceCategoryRepository,
private readonly WriteServiceCategoryRepositoryInterface $writeServiceCategoryRepository,
private readonly ReadServiceGroupRepositoryInterface $readServiceGroupRepository,
private readonly WriteServiceGroupRepositoryInterface $writeServiceGroupRepository,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly AddServiceValidation $validation,
private readonly OptionService $optionService,
private readonly ContactInterface $user,
private readonly bool $isCloudPlatform,
private readonly WriteVaultRepositoryInterface $writeVaultRepository,
private readonly ReadVaultRepositoryInterface $readVaultRepository,
private readonly WriteRealTimeServiceRepositoryInterface $writeRealTimeServiceRepository,
) {
$this->writeVaultRepository->setCustomPath(AbstractVaultRepository::SERVICE_VAULT_PATH);
}
/**
* @param AddServiceRequest $request
* @param AddServicePresenterInterface $presenter
*/
public function __invoke(AddServiceRequest $request, AddServicePresenterInterface $presenter): void
{
try {
if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_SERVICES_WRITE)) {
$this->error(
"User doesn't have sufficient rights to add a service",
['user_id' => $this->user->getId()]
);
$presenter->presentResponse(
new ForbiddenResponse(ServiceException::addNotAllowed())
);
return;
}
if (! $this->user->isAdmin()) {
$this->accessGroups = $this->readAccessGroupRepository->findByContact($this->user);
$this->validation->accessGroups = $this->accessGroups;
}
$this->assertParameters($request);
$newServiceId = $this->createService($request);
if ($this->accessGroups !== []) {
$this->writeRealTimeServiceRepository->addServiceToResourceAcls(
$request->hostId,
$newServiceId,
$this->accessGroups
);
}
$this->info('New service created', ['service_id' => $newServiceId]);
$service = $this->readServiceRepository->findById($newServiceId);
if (! $service) {
$presenter->presentResponse(
new ErrorResponse(ServiceException::errorWhileRetrieving())
);
return;
}
if ($this->user->isAdmin()) {
$serviceCategories = $this->readServiceCategoryRepository->findByService($newServiceId);
$serviceGroups = $this->readServiceGroupRepository->findByService($newServiceId);
} else {
$serviceCategories = $this->readServiceCategoryRepository->findByServiceAndAccessGroups(
$newServiceId,
$this->accessGroups
);
$serviceGroups = $this->readServiceGroupRepository->findByServiceAndAccessGroups(
$newServiceId,
$this->accessGroups
);
}
$presenter->presentResponse($this->createResponse($service, $serviceCategories, $serviceGroups));
} catch (AssertionFailedException $ex) {
$presenter->presentResponse(new InvalidArgumentResponse($ex));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (ServiceException $ex) {
$presenter->presentResponse(
match ($ex->getCode()) {
ServiceException::CODE_CONFLICT => new ConflictResponse($ex),
default => new ErrorResponse($ex),
}
);
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (\Throwable $ex) {
$presenter->presentResponse(new ErrorResponse(ServiceException::errorWhileAdding($ex)));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
}
}
/**
* @param int $serviceId
* @param AddServiceRequest $request
*
* @throws AssertionFailedException
* @throws \Throwable
*/
private function addMacros(int $serviceId, AddServiceRequest $request): void
{
$this->info('Add macros', ['service_id' => $serviceId]);
/**
* @var array<string,Macro> $inheritedMacros
* @var array<string,CommandMacro> $commandMacros
*/
[$inheritedMacros, $commandMacros] = $this->findAllInheritedMacros($serviceId, $request->commandId);
$macros = [];
foreach ($request->macros as $macro) {
$macro = MacroFactory::create($macro, $serviceId, $inheritedMacros);
$macros[$macro->getName()] = $macro;
}
$macrosDiff = new MacroDifference();
$macrosDiff->compute([], $inheritedMacros, $commandMacros, $macros);
MacroManager::setOrder($macrosDiff, $macros, []);
foreach ($macrosDiff->addedMacros as $macro) {
if ($macro->getDescription() === '') {
$macro->setDescription(
isset($commandMacros[$macro->getName()])
? $commandMacros[$macro->getName()]->getDescription()
: ''
);
}
$this->info('Add the macro ' . $macro->getName());
if ($this->writeVaultRepository->isVaultConfigured() === true && $macro->isPassword() === true) {
$vaultPaths = $this->writeVaultRepository->upsert(
$this->uuid ?? null,
['_SERVICE' . $macro->getName() => $macro->getValue()],
);
$vaultPath = $vaultPaths['_SERVICE' . $macro->getName()];
$this->uuid ??= $this->getUuidFromPath($vaultPath);
$inVaultMacro = new Macro($macro->getId(), $macro->getOwnerId(), $macro->getName(), $vaultPath);
$inVaultMacro->setDescription($macro->getDescription());
$inVaultMacro->setIsPassword($macro->isPassword());
$inVaultMacro->setOrder($macro->getOrder());
$macro = $inVaultMacro;
}
$this->writeServiceMacroRepository->add($macro);
}
}
/**
* @param AddServiceRequest $request
*
* @throws \Exception
* @throws AssertionFailedException
*
* @return NewService
*/
private function createNewService(AddServiceRequest $request): NewService
{
$inheritanceMode = $this->optionService->findSelectedOptions(['inheritance_mode']);
$inheritanceMode = isset($inheritanceMode[0])
? (int) $inheritanceMode[0]->getValue()
: 0;
return NewServiceFactory::create((int) $inheritanceMode, $request, $this->isCloudPlatform);
}
/**
* @param int $serviceId
* @param AddServiceRequest $request
*
* @throws \Throwable
*/
private function linkServiceToServiceCategories(int $serviceId, AddServiceRequest $request): void
{
if ($request->serviceCategories === []) {
return;
}
$this->info(
'Link existing service categories to service',
['service_categories' => $request->serviceCategories]
);
$this->writeServiceCategoryRepository->linkToService($serviceId, $request->serviceCategories);
}
/**
* @param int $serviceId
* @param AddServiceRequest $request
*
* @throws \Throwable
*/
private function linkServiceToServiceGroups(int $serviceId, AddServiceRequest $request): void
{
if ($request->serviceGroups === []) {
return;
}
$this->info(
'Link existing service groups to service',
['service_groups' => $request->serviceGroups]
);
$serviceGroupRelations = [];
foreach ($request->serviceGroups as $serviceGroupId) {
$serviceGroupRelations[] = new ServiceGroupRelation(
$serviceGroupId,
$serviceId,
$request->hostId
);
}
$this->writeServiceGroupRepository->link($serviceGroupRelations);
}
/**
* @param Service $service
* @param ServiceCategory[] $serviceCategories
* @param array<array{relation:ServiceGroupRelation,serviceGroup:ServiceGroup}> $serviceGroups
*
* @throws \Throwable
*
* @return AddServiceResponse
*/
private function createResponse(Service $service, array $serviceCategories, array $serviceGroups): AddServiceResponse
{
$macros = $this->readServiceMacroRepository->findByServiceIds($service->getId());
$response = new AddServiceResponse();
$response->id = $service->getId();
$response->name = $service->getName();
$response->commandArguments = $service->getCommandArguments();
$response->eventHandlerArguments = $service->getEventHandlerArguments();
$response->notificationTypes = $service->getNotificationTypes();
$response->isContactAdditiveInheritance = $service->isContactAdditiveInheritance();
$response->isContactGroupAdditiveInheritance = $service->isContactGroupAdditiveInheritance();
$response->isActivated = $service->isActivated();
$response->activeChecks = $service->getActiveChecks();
$response->passiveCheck = $service->getPassiveCheck();
$response->volatility = $service->getVolatility();
$response->checkFreshness = $service->getCheckFreshness();
$response->eventHandlerEnabled = $service->getEventHandlerEnabled();
$response->flapDetectionEnabled = $service->getFlapDetectionEnabled();
$response->notificationsEnabled = $service->getNotificationsEnabled();
$response->comment = $service->getComment();
$response->note = $service->getNote();
$response->noteUrl = $service->getNoteUrl();
$response->actionUrl = $service->getActionUrl();
$response->iconAlternativeText = $service->getIconAlternativeText();
$response->graphTemplateId = $service->getGraphTemplateId();
$response->serviceTemplateId = $service->getServiceTemplateParentId();
$response->commandId = $service->getCommandId();
$response->eventHandlerId = $service->getEventHandlerId();
$response->notificationTimePeriodId = $service->getNotificationTimePeriodId();
$response->checkTimePeriodId = $service->getCheckTimePeriodId();
$response->iconId = $service->getIconId();
$response->severityId = $service->getSeverityId();
$response->hostId = $service->getHostId();
$response->maxCheckAttempts = $service->getMaxCheckAttempts();
$response->normalCheckInterval = $service->getNormalCheckInterval();
$response->retryCheckInterval = $service->getRetryCheckInterval();
$response->freshnessThreshold = $service->getFreshnessThreshold();
$response->lowFlapThreshold = $service->getLowFlapThreshold();
$response->highFlapThreshold = $service->getHighFlapThreshold();
$response->notificationInterval = $service->getNotificationInterval();
$response->recoveryNotificationDelay = $service->getRecoveryNotificationDelay();
$response->firstNotificationDelay = $service->getFirstNotificationDelay();
$response->acknowledgementTimeout = $service->getAcknowledgementTimeout();
$response->geoCoords = $service->getGeoCoords()?->__toString();
$response->macros = array_map(
fn (Macro $macro): MacroDto => new MacroDto(
$macro->getName(),
$macro->getValue(),
$macro->isPassword(),
$macro->getDescription()
),
$macros
);
$response->categories = array_map(
fn (ServiceCategory $category) => ['id' => $category->getId(), 'name' => $category->getName()],
$serviceCategories
);
$response->groups = array_map(
fn (array $group) => [
'id' => $group['serviceGroup']->getId(),
'name' => $group['serviceGroup']->getName(),
],
$serviceGroups,
);
return $response;
}
/**
* @param AddServiceRequest $request
*
* @throws ServiceException
* @throws \Throwable
*/
private function assertParameters(AddServiceRequest $request): void
{
$this->validation->assertIsValidSeverity($request->severityId);
$this->validation->assertIsValidPerformanceGraph($request->graphTemplateId);
$this->validation->assertIsValidServiceTemplate($request->serviceTemplateParentId);
$this->validation->assertIsValidEventHandler($request->eventHandlerId);
$this->validation->assertIsValidTimePeriod($request->checkTimePeriodId);
$this->validation->assertIsValidNotificationTimePeriod($request->notificationTimePeriodId);
$this->validation->assertIsValidIcon($request->iconId);
$this->validation->assertIsValidHost($request->hostId);
$this->validation->assertIsValidServiceCategories($request->serviceCategories);
// No assertion on the check command for Saas platform as it will be inherited from the service template.
if (! $this->isCloudPlatform) {
$this->validation->assertIsValidCommandForOnPremPlatform($request->commandId, $request->serviceTemplateParentId);
}
// Should be called after assertion on host IDs
$this->validation->assertServiceName($request);
$this->validation->assertIsValidServiceGroups($request->serviceGroups, $request->hostId);
}
/**
* @param AddServiceRequest $request
*
* @throws AssertionFailedException
* @throws ServiceException
* @throws \Throwable
*
* @return int
*/
private function createService(AddServiceRequest $request): int
{
$newServiceTemplate = $this->createNewService($request);
$this->storageEngine->startTransaction();
try {
$newServiceId = $this->writeServiceRepository->add($newServiceTemplate);
$this->addMacros($newServiceId, $request);
$this->linkServiceToServiceCategories($newServiceId, $request);
$this->linkServiceToServiceGroups($newServiceId, $request);
if (($monitoringServer = $this->readMonitoringServerRepository->findByHost($request->hostId))) {
$this->writeMonitoringServerRepository->notifyConfigurationChange($monitoringServer->getId());
}
$this->storageEngine->commitTransaction();
return $newServiceId;
} catch (\Throwable $ex) {
$this->error("Rollback of 'Add Service' transaction.");
$this->storageEngine->rollbackTransaction();
throw $ex;
}
}
/**
* @param int $serviceId
* @param int|null $checkCommandId
*
* @throws \Throwable
*
* @return array{
* array<string,Macro>,
* array<string,CommandMacro>
* }
*/
private function findAllInheritedMacros(int $serviceId, ?int $checkCommandId): array
{
$serviceTemplateInheritances = $this->readServiceRepository->findParents($serviceId);
$inheritanceLine = ServiceInheritance::createInheritanceLine(
$serviceId,
$serviceTemplateInheritances
);
$existingMacros = $this->readServiceMacroRepository->findByServiceIds(...$inheritanceLine);
[, $inheritedMacros] = Macro::resolveInheritance($existingMacros, $inheritanceLine, $serviceId);
/** @var array<string,CommandMacro> $commandMacros */
$commandMacros = [];
if ($checkCommandId !== null) {
$existingCommandMacros = $this->readCommandMacroRepository->findByCommandIdAndType(
$checkCommandId,
CommandMacroType::Service
);
$commandMacros = MacroManager::resolveInheritanceForCommandMacro($existingCommandMacros);
}
return [
$this->writeVaultRepository->isVaultConfigured()
? $this->retrieveMacrosVaultValues($inheritedMacros)
: $inheritedMacros,
$commandMacros,
];
}
/**
* @param array<string,Macro> $macros
*
* @throws \Throwable
*
* @return array<string,Macro>
*/
private function retrieveMacrosVaultValues(array $macros): array
{
$updatedMacros = [];
foreach ($macros as $key => $macro) {
if ($macro->isPassword() === false) {
$updatedMacros[$key] = $macro;
continue;
}
$vaultData = $this->readVaultRepository->findFromPath($macro->getValue());
$vaultKey = '_SERVICE' . $macro->getName();
if (isset($vaultData[$vaultKey])) {
$inVaultMacro = new Macro($macro->getId(), $macro->getOwnerId(), $macro->getName(), $vaultData[$vaultKey]);
$inVaultMacro->setDescription($macro->getDescription());
$inVaultMacro->setIsPassword($macro->isPassword());
$inVaultMacro->setOrder($macro->getOrder());
$updatedMacros[$key] = $inVaultMacro;
}
}
return $updatedMacros;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Application/UseCase/AddService/AddServiceResponse.php | centreon/src/Core/Service/Application/UseCase/AddService/AddServiceResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\UseCase\AddService;
use Core\Common\Domain\YesNoDefault;
use Core\Service\Domain\Model\NotificationType;
final class AddServiceResponse
{
public int $id = 0;
public string $name = '';
public int $hostId = 0;
public string|null $comment = null;
public int|null $acknowledgementTimeout = null;
public string|null $actionUrl = null;
public bool $isContactAdditiveInheritance = false;
public bool $isContactGroupAdditiveInheritance = false;
public int|null $commandId = null;
/** @var string[] */
public array $commandArguments = [];
public int|null $eventHandlerId = null;
/** @var string[] */
public array $eventHandlerArguments = [];
public int|null $checkTimePeriodId = null;
public int|null $firstNotificationDelay = null;
public int|null $freshnessThreshold = null;
public int|null $graphTemplateId = null;
public int|null $lowFlapThreshold = null;
public int|null $highFlapThreshold = null;
public int|null $iconId = null;
public string|null $iconAlternativeText = null;
public bool $isActivated = false;
public YesNoDefault $activeChecks = YesNoDefault::Default;
public YesNoDefault $eventHandlerEnabled = YesNoDefault::Default;
public YesNoDefault $flapDetectionEnabled = YesNoDefault::Default;
public YesNoDefault $checkFreshness = YesNoDefault::Default;
public YesNoDefault $notificationsEnabled = YesNoDefault::Default;
public YesNoDefault $passiveCheck = YesNoDefault::Default;
public YesNoDefault $volatility = YesNoDefault::Default;
public int|null $maxCheckAttempts = null;
public int|null $normalCheckInterval = null;
public string|null $note = null;
public string|null $noteUrl = null;
public int|null $notificationInterval = null;
public int|null $notificationTimePeriodId = null;
/** @var NotificationType[] */
public array $notificationTypes = [];
public int|null $recoveryNotificationDelay = null;
public int|null $retryCheckInterval = null;
public int|null $serviceTemplateId = null;
public int|null $severityId = null;
/** @var MacroDto[] */
public array $macros = [];
/** @var array<array{id:int,name:string}> */
public array $categories = [];
/** @var array<array{id:int,name:string}> */
public array $groups = [];
public string|null $geoCoords = 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/Service/Application/UseCase/AddService/NewServiceFactory.php | centreon/src/Core/Service/Application/UseCase/AddService/NewServiceFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\UseCase\AddService;
use Assert\AssertionFailedException;
use Core\Domain\Common\GeoCoords;
use Core\Service\Application\Model\NotificationTypeConverter;
use Core\Service\Application\Model\YesNoDefaultConverter;
use Core\Service\Domain\Model\NewService;
class NewServiceFactory
{
/**
* @param int $inheritanceMode
* @param AddServiceRequest $request
* @param bool $isCloudPlatform
*
* @throws AssertionFailedException
*
* @return NewService
*/
public static function create(int $inheritanceMode, AddServiceRequest $request, bool $isCloudPlatform): NewService
{
$newService = new NewService($request->name, $request->hostId, $request->commandId);
foreach ($request->commandArguments as $argument) {
$newService->addCommandArgument($argument);
}
foreach ($request->eventHandlerArguments as $argument) {
$newService->addEventHandlerArgument($argument);
}
if ($request->notificationTypes !== null) {
foreach (NotificationTypeConverter::fromBits($request->notificationTypes) as $notificationType) {
$newService->addNotificationType($notificationType);
}
}
$newService->setContactAdditiveInheritance(
($inheritanceMode === 1) ? $request->isContactAdditiveInheritance : false
);
$newService->setContactGroupAdditiveInheritance(
($inheritanceMode === 1) ? $request->isContactGroupAdditiveInheritance : false
);
$newService->setActivated($request->isActivated);
$newService->setActiveChecks(YesNoDefaultConverter::fromInt($request->activeChecks));
$newService->setPassiveCheck(YesNoDefaultConverter::fromInt($request->passiveCheck));
$newService->setVolatility(YesNoDefaultConverter::fromInt($request->volatility));
$newService->setCheckFreshness(YesNoDefaultConverter::fromInt($request->checkFreshness));
$newService->setEventHandlerEnabled(YesNoDefaultConverter::fromInt($request->eventHandlerEnabled));
$newService->setFlapDetectionEnabled(YesNoDefaultConverter::fromInt($request->flapDetectionEnabled));
$newService->setNotificationsEnabled(YesNoDefaultConverter::fromInt($request->notificationsEnabled));
$newService->setComment($request->comment);
$newService->setNote($request->note);
$newService->setNoteUrl($request->noteUrl);
$newService->setActionUrl($request->actionUrl);
$newService->setIconAlternativeText($request->iconAlternativeText);
$newService->setGraphTemplateId($request->graphTemplateId);
$newService->setServiceTemplateParentId($request->serviceTemplateParentId);
$newService->setEventHandlerId($request->eventHandlerId);
$newService->setNotificationTimePeriodId($request->notificationTimePeriodId);
$newService->setCheckTimePeriodId($request->checkTimePeriodId);
$newService->setIconId($request->iconId);
$newService->setSeverityId($request->severityId);
$newService->setMaxCheckAttempts($request->maxCheckAttempts);
$newService->setNormalCheckInterval($request->normalCheckInterval);
$newService->setRetryCheckInterval($request->retryCheckInterval);
$newService->setFreshnessThreshold($request->freshnessThreshold);
$newService->setLowFlapThreshold($request->lowFlapThreshold);
$newService->setHighFlapThreshold($request->highFlapThreshold);
$newService->setNotificationInterval($request->notificationInterval);
$newService->setRecoveryNotificationDelay($request->recoveryNotificationDelay);
$newService->setFirstNotificationDelay($request->firstNotificationDelay);
$newService->setAcknowledgementTimeout($request->acknowledgementTimeout);
$newService->setGeoCoords(
$request->geoCoords === ''
? null
: GeoCoords::fromString($request->geoCoords)
);
return $newService;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Application/UseCase/AddService/MacroDto.php | centreon/src/Core/Service/Application/UseCase/AddService/MacroDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\UseCase\AddService;
class MacroDto
{
public function __construct(
public string $name,
public ?string $value,
public bool $isPassword,
public ?string $description,
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Application/UseCase/AddService/MacroFactory.php | centreon/src/Core/Service/Application/UseCase/AddService/MacroFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\UseCase\AddService;
use Assert\AssertionFailedException;
use Core\Macro\Domain\Model\Macro;
final class MacroFactory
{
/**
* Create macros object from the request data.
* Use direct and inherited macros to retrieve value of macro with isPassword when not provided in dto.
*
* @param MacroDto $dto
* @param int $serviceId
* @param array<string,Macro> $inheritedMacros
*
* @throws \Throwable
* @throws AssertionFailedException
*
* @return Macro
*/
public static function create(MacroDto $dto, int $serviceId, array $inheritedMacros): Macro
{
$macroName = mb_strtoupper($dto->name);
$macroValue = $dto->value ?? '';
$passwordHasNotChanged = ($dto->value === null) && $dto->isPassword;
// Note: do not handle vault storage at the moment
if ($passwordHasNotChanged) {
$macroValue = match (true) {
// retrieve actual password value
isset($inheritedMacros[$macroName]) => $inheritedMacros[$macroName]->getValue(),
default => $macroValue,
};
}
$macro = new Macro(
null,
$serviceId,
$dto->name,
$macroValue,
);
$macro->setIsPassword($dto->isPassword);
$macro->setDescription($dto->description ?? '');
return $macro;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Application/UseCase/AddService/AddServiceRequest.php | centreon/src/Core/Service/Application/UseCase/AddService/AddServiceRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\UseCase\AddService;
final class AddServiceRequest
{
public string $name = '';
public int $hostId = 0; // Only one host for SaaS platform
/** @var int|null */
public ?int $commandId = null;
/** @var list<string> */
public array $commandArguments = [];
/** @var list<string> */
public array $eventHandlerArguments = [];
/** @var list<int> */
public array $serviceCategories = [];
/** @var list<int> */
public array $serviceGroups = [];
public int|null $notificationTypes = null;
public bool $isContactAdditiveInheritance = false;
public bool $isContactGroupAdditiveInheritance = false;
public bool $isActivated = false;
public int $activeChecks = 0;
public int $passiveCheck = 0;
public int $volatility = 0;
public int $checkFreshness = 0;
public int $eventHandlerEnabled = 0;
public int $flapDetectionEnabled = 0;
public int $notificationsEnabled = 0;
public string|null $comment = null;
public string|null $note = null;
public string|null $noteUrl = null;
public string|null $actionUrl = null;
public string|null $iconAlternativeText = null;
public int|null $graphTemplateId = null;
public int|null $serviceTemplateParentId = null;
public int|null $eventHandlerId = null;
public int|null $notificationTimePeriodId = null;
public int|null $checkTimePeriodId = null;
public int|null $iconId = null;
public int|null $severityId = null;
public int|null $maxCheckAttempts = null;
public int|null $normalCheckInterval = null;
public int|null $retryCheckInterval = null;
public int|null $freshnessThreshold = null;
public int|null $lowFlapThreshold = null;
public int|null $highFlapThreshold = null;
public int|null $notificationInterval = null;
public int|null $recoveryNotificationDelay = null;
public int|null $firstNotificationDelay = null;
public int|null $acknowledgementTimeout = null;
/** @var MacroDto[] */
public array $macros = [];
public string $geoCoords = '';
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Application/UseCase/AddService/AddServiceValidation.php | centreon/src/Core/Service/Application/UseCase/AddService/AddServiceValidation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\UseCase\AddService;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Command\Application\Repository\ReadCommandRepositoryInterface;
use Core\Command\Domain\Model\CommandType;
use Core\Common\Domain\TrimmedString;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
use Core\PerformanceGraph\Application\Repository\ReadPerformanceGraphRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Core\Service\Application\Exception\ServiceException;
use Core\Service\Application\Repository\ReadServiceRepositoryInterface;
use Core\Service\Domain\Model\Service;
use Core\ServiceCategory\Application\Repository\ReadServiceCategoryRepositoryInterface;
use Core\ServiceGroup\Application\Repository\ReadServiceGroupRepositoryInterface;
use Core\ServiceSeverity\Application\Repository\ReadServiceSeverityRepositoryInterface;
use Core\ServiceTemplate\Application\Repository\ReadServiceTemplateRepositoryInterface;
use Core\TimePeriod\Application\Repository\ReadTimePeriodRepositoryInterface;
use Core\ViewImg\Application\Repository\ReadViewImgRepositoryInterface;
class AddServiceValidation
{
use LoggerTrait;
/** @var AccessGroup[] */
public array $accessGroups = [];
public function __construct(
private readonly ReadServiceTemplateRepositoryInterface $readServiceTemplateRepository,
private readonly ReadServiceRepositoryInterface $readServiceRepository,
private readonly ReadServiceSeverityRepositoryInterface $serviceSeverityRepository,
private readonly ReadPerformanceGraphRepositoryInterface $performanceGraphRepository,
private readonly ReadCommandRepositoryInterface $commandRepository,
private readonly ReadTimePeriodRepositoryInterface $timePeriodRepository,
private readonly ReadViewImgRepositoryInterface $imageRepository,
private readonly ReadHostRepositoryInterface $readHostRepository,
private readonly ReadServiceCategoryRepositoryInterface $readServiceCategoryRepository,
private readonly ReadServiceGroupRepositoryInterface $readServiceGroupRepository,
private readonly ContactInterface $user,
) {
}
/**
* @param int|null $severityId
*
* @throws ServiceException
* @throws \Throwable
*/
public function assertIsValidSeverity(?int $severityId): void
{
if ($severityId !== null) {
$exists = ($this->accessGroups === [])
? $this->serviceSeverityRepository->exists($severityId)
: $this->serviceSeverityRepository->existsByAccessGroups($severityId, $this->accessGroups);
if (! $exists) {
$this->error('Service severity does not exist', ['severity_id' => $severityId]);
throw ServiceException::idDoesNotExist('severity_id', $severityId);
}
}
}
/**
* @param int|null $graphTemplateId
*
* @throws ServiceException
* @throws \Throwable
*/
public function assertIsValidPerformanceGraph(?int $graphTemplateId): void
{
if ($graphTemplateId !== null && ! $this->performanceGraphRepository->exists($graphTemplateId)) {
$this->error('Performance graph does not exist', ['graph_template_id' => $graphTemplateId]);
throw ServiceException::idDoesNotExist('graph_template_id', $graphTemplateId);
}
}
/**
* @param int $hostId
*
* @throws ServiceException
*/
public function assertIsValidHost(int $hostId): void
{
$hostIdFound = $this->user->isAdmin()
? $this->readHostRepository->exists($hostId)
: $this->readHostRepository->existsByAccessGroups($hostId, $this->accessGroups);
if ($hostIdFound === false) {
throw ServiceException::idDoesNotExist('host_id', $hostId);
}
}
/**
* @param list<int> $serviceCategoriesIds
*
* @throws ServiceException
* @throws \Throwable
*/
public function assertIsValidServiceCategories(array $serviceCategoriesIds): void
{
if ($serviceCategoriesIds === []) {
return;
}
if ($this->user->isAdmin()) {
$serviceCategoriesIdsFound = $this->readServiceCategoryRepository->findAllExistingIds(
$serviceCategoriesIds
);
} else {
$serviceCategoriesIdsFound = $this->readServiceCategoryRepository->findAllExistingIdsByAccessGroups(
$serviceCategoriesIds,
$this->accessGroups
);
}
if ([] !== ($idsNotFound = array_diff($serviceCategoriesIds, $serviceCategoriesIdsFound))) {
throw ServiceException::idsDoNotExist('service_categories', $idsNotFound);
}
}
/**
* @param int|null $commandId
* @param int|null $serviceTemplateId
*
* @throws ServiceException
*/
public function assertIsValidCommandForOnPremPlatform(?int $commandId, ?int $serviceTemplateId): void
{
if ($commandId === null && $serviceTemplateId === null) {
throw ServiceException::checkCommandCannotBeNull();
}
if ($commandId !== null && ! $this->commandRepository->existsByIdAndCommandType($commandId, CommandType::Check)) {
$this->error('The check command does not exist', ['check_command_id' => $commandId]);
throw ServiceException::idDoesNotExist('check_command_id', $commandId);
}
}
/**
* @param int|null $eventHandlerId
*
* @throws ServiceException
*/
public function assertIsValidEventHandler(?int $eventHandlerId): void
{
if ($eventHandlerId !== null && ! $this->commandRepository->exists($eventHandlerId)) {
$this->error('Event handler command does not exist', ['event_handler_command_id' => $eventHandlerId]);
throw ServiceException::idDoesNotExist('event_handler_command_id', $eventHandlerId);
}
}
/**
* @param int|null $timePeriodId
*
* @throws ServiceException
* @throws \Throwable
*/
public function assertIsValidTimePeriod(?int $timePeriodId): void
{
if ($timePeriodId !== null && ! $this->timePeriodRepository->exists($timePeriodId)) {
$this->error('Time period does not exist', ['check_timeperiod_id' => $timePeriodId]);
throw ServiceException::idDoesNotExist('check_timeperiod_id', $timePeriodId);
}
}
/**
* @param int|null $iconId
*
* @throws ServiceException
* @throws \Throwable
*/
public function assertIsValidIcon(?int $iconId): void
{
if ($iconId !== null && ! $this->imageRepository->existsOne($iconId)) {
$this->error('Icon does not exist', ['icon_id' => $iconId]);
throw ServiceException::idDoesNotExist('icon_id', $iconId);
}
}
/**
* @param int|null $notificationTimePeriodId
*
* @throws ServiceException
* @throws \Throwable
*/
public function assertIsValidNotificationTimePeriod(?int $notificationTimePeriodId): void
{
if ($notificationTimePeriodId !== null && ! $this->timePeriodRepository->exists($notificationTimePeriodId)) {
$this->error(
'Notification time period does not exist',
['notification_timeperiod_id' => $notificationTimePeriodId]
);
throw ServiceException::idDoesNotExist('notification_timeperiod_id', $notificationTimePeriodId);
}
}
/**
* @param int|null $serviceTemplateId
*
* @throws ServiceException
* @throws \Throwable
*/
public function assertIsValidServiceTemplate(?int $serviceTemplateId): void
{
if ($serviceTemplateId !== null && ! $this->readServiceTemplateRepository->exists($serviceTemplateId)) {
$this->error('Service does not exist', ['service_template_id' => $serviceTemplateId]);
throw ServiceException::idDoesNotExist('service_template_id', $serviceTemplateId);
}
}
/**
* @param AddServiceRequest $request
*
* @throws \Throwable
*/
public function assertServiceName(AddServiceRequest $request): void
{
$nameToCheck = new TrimmedString(Service::formatName($request->name));
$serviceNamesByHost = $this->readServiceRepository->findServiceNamesByHost($request->hostId);
if ($serviceNamesByHost === null) {
// Should not be called if this assertion is called after assertion on host IDs
throw ServiceException::idDoesNotExist('host', $request->hostId);
}
if ($serviceNamesByHost->contains($nameToCheck)) {
throw ServiceException::nameAlreadyExists((string) $nameToCheck, $request->hostId);
}
}
/**
* @param int[] $serviceGroupIds
* @param int $hostId
*
* @throws ServiceException
* @throws \Throwable
*/
public function assertIsValidServiceGroups(array $serviceGroupIds, int $hostId): void
{
if ($serviceGroupIds === []) {
return;
}
if ($this->user->isAdmin()) {
$serviceGroupIdsFound = $this->readServiceGroupRepository->exist($serviceGroupIds);
} else {
$serviceGroupIdsFound = $this->readServiceGroupRepository->existByAccessGroups(
$serviceGroupIds,
$this->accessGroups
);
}
if ([] !== ($idsNotFound = array_diff($serviceGroupIds, $serviceGroupIdsFound))) {
throw ServiceException::idsDoNotExist('service_groups', $idsNotFound);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Application/UseCase/AddService/AddServicePresenterInterface.php | centreon/src/Core/Service/Application/UseCase/AddService/AddServicePresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\UseCase\AddService;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface AddServicePresenterInterface
{
public function presentResponse(AddServiceResponse|ResponseStatusInterface $response): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Application/Exception/ServiceException.php | centreon/src/Core/Service/Application/Exception/ServiceException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\Exception;
class ServiceException extends \Exception
{
public const CODE_CONFLICT = 1;
/**
* @return self
*/
public static function deleteNotAllowed(): self
{
return new self(_('You are not allowed to delete a service'));
}
/**
* @return self
*/
public static function addNotAllowed(): self
{
return new self(_('You are not allowed to add a service'));
}
/**
* @return self
*/
public static function editNotAllowed(): self
{
return new self(_('You are not allowed to edit a service'));
}
/**
* @return self
*/
public static function accessNotAllowed(): self
{
return new self(_('You are not allowed to access services'));
}
/**
* @return self
*/
public static function accessNotAllowedForRealTime(): self
{
return new self(_('You are not allowed to access services in the real time context'));
}
/**
* @return self
*/
public static function checkCommandCannotBeNull(): self
{
return new self(_('The check command cannot be null if the service template is null'));
}
/**
* @param \Throwable $ex
*
* @return self
*/
public static function errorWhileDeleting(\Throwable $ex): self
{
return new self(_('Error while deleting the service'), 0, $ex);
}
/**
* @param \Throwable $ex
*
* @return self
*/
public static function errorWhileAdding(\Throwable $ex): self
{
return new self(_('Error while adding the service'), 0, $ex);
}
/**
* @return self
*/
public static function errorWhileEditing(): self
{
return new self(_('Error while updating a service'));
}
/**
* @return self
*/
public static function errorWhileRetrieving(): self
{
return new self(_('Error while retrieving a service'));
}
/**
* @param \Throwable $ex
*
* @return self
*/
public static function errorWhileSearching(\Throwable $ex): self
{
return new self(_('Error while searching for services'), 0, $ex);
}
/**
* @param string $propertyName
* @param int $propertyValue
*
* @return self
*/
public static function idDoesNotExist(string $propertyName, int $propertyValue): self
{
return new self(
sprintf(
_("The %s with value '%d' does not exist"),
$propertyName,
$propertyValue
),
self::CODE_CONFLICT
);
}
/**
* @param string $propertyName
* @param list<int> $propertyValue
*
* @return self
*/
public static function idsDoNotExist(string $propertyName, array $propertyValue): self
{
return new self(
sprintf(
_("'%s' does not exist with ID(s) '%s'"),
$propertyName,
implode(',', $propertyValue)
),
self::CODE_CONFLICT
);
}
/**
* @param string $serviceName
* @param int $hostId
*
* @return self
*/
public static function nameAlreadyExists(string $serviceName, int $hostId): self
{
return new self(
sprintf(
_("'%s' service name already exists for host ID %d"),
$serviceName,
$hostId
),
self::CODE_CONFLICT
);
}
/**
* @return ServiceException
*/
public static function errorWhileRetrievingServiceStatusesCount(): self
{
return new self(_('Error while retrieving service statuses distribution'));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Application/Repository/WriteRealTimeServiceRepositoryInterface.php | centreon/src/Core/Service/Application/Repository/WriteRealTimeServiceRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\Repository;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
interface WriteRealTimeServiceRepositoryInterface
{
/**
* Link service to Resource ACLs.
*
* @param int $hostId
* @param int $serviceId
* @param AccessGroup[] $accessGroups
*
* @throws \Throwable
*/
public function addServiceToResourceAcls(int $hostId, int $serviceId, array $accessGroups): 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/Service/Application/Repository/ReadRealTimeServiceRepositoryInterface.php | centreon/src/Core/Service/Application/Repository/ReadRealTimeServiceRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\Repository;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Service\Domain\Model\ServiceStatusesCount;
interface ReadRealTimeServiceRepositoryInterface
{
/**
* @param RequestParametersInterface $requestParameters
*
* @return string[]
*/
public function findUniqueServiceNamesByRequestParameters(RequestParametersInterface $requestParameters): array;
/**
* @param RequestParametersInterface $requestParameters
* @param int[] $accessGroupIds
*
* @return string[]
*/
public function findUniqueServiceNamesByRequestParametersAndAccessGroupIds(
RequestParametersInterface $requestParameters,
array $accessGroupIds,
): array;
/**
* @param RequestParametersInterface $requestParameters
*
* @return ServiceStatusesCount
*/
public function findStatusesByRequestParameters(RequestParametersInterface $requestParameters): ServiceStatusesCount;
/**
* @param RequestParametersInterface $requestParameters
* @param int[] $accessGroupIds
*
* @return ServiceStatusesCount
*/
public function findStatusesByRequestParametersAndAccessGroupIds(
RequestParametersInterface $requestParameters,
array $accessGroupIds,
): ServiceStatusesCount;
/**
* Indicates whether the service already exists for the given service ID and host ID
*
* @param int $serviceId
* @param int $hostId
*
* @throws RepositoryException
*
* @return bool
*/
public function exists(int $serviceId, int $hostId): bool;
/**
* Indicates whether the service already exists for a meta service ID
*
* @param int $metaServiceId
*
* @throws RepositoryException
*
* @return array<int>|false
*/
public function existsByDescription(int $metaServiceId): array|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/Service/Application/Repository/WriteServiceRepositoryInterface.php | centreon/src/Core/Service/Application/Repository/WriteServiceRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Application\Repository;
use Core\Service\Domain\Model\NewService;
use Core\Service\Domain\Model\Service;
interface WriteServiceRepositoryInterface
{
/**
* Delete a service by ID.
*
* @param int $serviceId
*
* @throws \Throwable
*/
public function delete(int $serviceId): void;
/**
* Delete services by ID.
*
* @param int ...$serviceIds
*/
public function deleteByIds(int ...$serviceIds): void;
/**
* Add a new service.
*
* @param NewService $newService
*
* @throws \Throwable
*
* @return int
*/
public function add(NewService $newService): int;
/**
* Update a service.
*
* @param Service $service
*
* @throws \Throwable
*/
public function update(Service $service): 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/Service/Application/Repository/ReadServiceRepositoryInterface.php | centreon/src/Core/Service/Application/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\Service\Application\Repository;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Core\Service\Domain\Model\Service;
use Core\Service\Domain\Model\ServiceInheritance;
use Core\Service\Domain\Model\ServiceLight;
use Core\Service\Domain\Model\ServiceNamesByHost;
use Core\Service\Domain\Model\ServiceRelation;
use Core\Service\Domain\Model\TinyService;
interface ReadServiceRepositoryInterface
{
/**
* Indicates whether the service already exists.
*
* @param int $serviceId
*
* @throws \Throwable
*
* @return bool
*/
public function exists(int $serviceId): bool;
/**
* Indicates whether the services already exists.
*
* @param int[] $serviceIds
*
* @throws \Throwable
*
* @return int[]
*/
public function exist(array $serviceIds): array;
/**
* Indicates whether the service already exists by access groups.
*
* @param int $serviceId
* @param AccessGroup[] $accessGroups
*
* @throws \Throwable
*
* @return bool
*/
public function existsByAccessGroups(int $serviceId, array $accessGroups): bool;
/**
* Retrieve the monitoring server id related to the service.
*
* @param int $serviceId
*
* @throws \Throwable
*
* @return int
*/
public function findMonitoringServerId(int $serviceId): int;
/**
* Find all service IDs link to the host.
*
* @param int $hostId Host ID for which the services are linked
*
* @throws \Throwable
*
* @return list<int>
*/
public function findServiceIdsLinkedToHostId(int $hostId): array;
/**
* Find service IDs that are exclusively linked to the host.
* These are services that should be deleted when the host is deleted
* because they are not used by any other host.
*
* @param int $hostId Host ID for which to find exclusively linked services
*
* @throws \Throwable
*
* @return list<int>
*/
public function findServiceIdsExclusivelyLinkedToHostId(int $hostId): array;
/**
* Indicates whether the service name already exists.
*
* @param int $hostId
*
* @throws \Throwable
*
* @return ServiceNamesByHost|null
*/
public function findServiceNamesByHost(int $hostId): ?ServiceNamesByHost;
/**
* Find one service.
*
* @param int $serviceId
*
* @throws \Throwable
*
* @return Service|null
*/
public function findById(int $serviceId): ?Service;
/**
* Find services based on given IDs.
*
* @param int ...$serviceIds
*
* @throws \Throwable
*
* @return list<TinyService>
*/
public function findByIds(int ...$serviceIds): array;
/**
* Find all services.
*
* @throws \Throwable
*
* @return \Traversable<int, TinyService>&\Countable
*/
public function findAll(): \Traversable&\Countable;
/**
* Retrieves all service inheritances from a service.
*
* @param int $serviceId
*
* @throws \Throwable
*
* @return ServiceInheritance[]
*/
public function findParents(int $serviceId): array;
/**
* Find all services by request parameter.
*
* @param RequestParametersInterface $requestParameters
*
* @throws \Throwable
*
* @return ServiceLight[]
*/
public function findByRequestParameter(RequestParametersInterface $requestParameters): array;
/**
* Find all services by request parameters and access groups.
*
* @param RequestParametersInterface $requestParameters
* @param AccessGroup[] $accessGroups
*
* @throws \Throwable
*
* @return ServiceLight[]
*/
public function findByRequestParameterAndAccessGroup(
RequestParametersInterface $requestParameters,
array $accessGroups,
): array;
/**
* Find services relations with host group.
*
* param int $hostGroupId
*
* @param int $hostGroupId
*
* @throws \Throwable
*
* @return ServiceRelation[]
*/
public function findServiceRelationsByHostGroupId(int $hostGroupId): array;
/**
* Find a service name by its ID.
*
* @param int $serviceId
*
* @throws \Throwable
*
* @return string|null
*/
public function findNameById(int $serviceId): ?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/Service/Domain/Model/NewService.php | centreon/src/Core/Service/Domain/Model/NewService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Common\Domain\YesNoDefault;
use Core\Domain\Common\GeoCoords;
use Core\MonitoringServer\Model\MonitoringServer;
class NewService
{
public const MAX_NAME_LENGTH = 255;
public const MAX_COMMENT_LENGTH = 65535;
public const MAX_NOTES_LENGTH = 65535;
public const MAX_NOTES_URL_LENGTH = 65535;
public const MAX_ACTION_URL_LENGTH = 65535;
public const MAX_ICON_ALT_LENGTH = 200;
private string $name;
private int $hostId;
private string $className;
/** @var string[] */
private array $commandArguments = [];
/** @var string[] */
private array $eventHandlerArguments = [];
/** @var NotificationType[] */
private array $notificationTypes = [];
private bool $isContactAdditiveInheritance = false;
private bool $isContactGroupAdditiveInheritance = false;
private bool $isActivated = true;
private YesNoDefault $activeChecks = YesNoDefault::Default;
private YesNoDefault $passiveCheck = YesNoDefault::Default;
private YesNoDefault $volatility = YesNoDefault::Default;
private YesNoDefault $checkFreshness = YesNoDefault::Default;
private YesNoDefault $eventHandlerEnabled = YesNoDefault::Default;
private YesNoDefault $flapDetectionEnabled = YesNoDefault::Default;
private YesNoDefault $notificationsEnabled = YesNoDefault::Default;
private ?string $comment = null;
private ?string $note = null;
private ?string $noteUrl = null;
private ?string $actionUrl = null;
private ?string $iconAlternativeText = null;
private ?int $graphTemplateId = null;
private ?int $serviceTemplateParentId = null;
private ?int $commandId = null;
private ?int $eventHandlerId = null;
private ?int $notificationTimePeriodId = null;
private ?int $checkTimePeriodId = null;
private ?int $iconId = null;
private ?int $severityId = null;
private ?int $maxCheckAttempts = null;
private ?int $normalCheckInterval = null;
private ?int $retryCheckInterval = null;
private ?int $freshnessThreshold = null;
private ?int $lowFlapThreshold = null;
private ?int $highFlapThreshold = null;
private ?int $notificationInterval = null;
private ?int $recoveryNotificationDelay = null;
private ?int $firstNotificationDelay = null;
private ?int $acknowledgementTimeout = null;
private ?GeoCoords $geoCoords = null;
/**
* @param string $name
* @param int $hostId
* @param int|null $commandId
*
* @throws AssertionFailedException
*/
public function __construct(string $name, int $hostId, ?int $commandId)
{
$this->className = (new \ReflectionClass($this))->getShortName();
$this->setName($name);
$this->setHostId($hostId);
$this->setCommandId($commandId);
}
/**
* @param string $name
*
* @throws AssertionFailedException
*/
public function setName(string $name): void
{
$name = preg_replace('/\s{2,}/', ' ', $name);
if ($name === null) {
throw AssertionException::notNull($this->className . '::name');
}
$name = trim($name);
Assertion::notEmptyString($name, $this->className . '::name');
Assertion::maxLength($name, self::MAX_NAME_LENGTH, $this->className . '::name');
Assertion::unauthorizedCharacters(
$name,
MonitoringServer::ILLEGAL_CHARACTERS,
$this->className . '::name'
);
$this->name = $name;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @param string $commandArgument
*/
public function addCommandArgument(string $commandArgument): void
{
$this->commandArguments[] = $commandArgument;
}
/**
* @return list<string>
*/
public function getCommandArguments(): array
{
return $this->commandArguments;
}
/**
* @param string $eventHandlerArgument
*/
public function addEventHandlerArgument(string $eventHandlerArgument): void
{
$this->eventHandlerArguments[] = $eventHandlerArgument;
}
/**
* @return list<string>
*/
public function getEventHandlerArguments(): array
{
return $this->eventHandlerArguments;
}
/**
* @param NotificationType $notificationType
*/
public function addNotificationType(NotificationType $notificationType): void
{
$this->notificationTypes[] = $notificationType;
}
/**
* @return NotificationType[]
*/
public function getNotificationTypes(): array
{
return $this->notificationTypes;
}
/**
* @param bool $isContactAdditiveInheritance
*/
public function setContactAdditiveInheritance(bool $isContactAdditiveInheritance): void
{
$this->isContactAdditiveInheritance = $isContactAdditiveInheritance;
}
/**
* @return bool
*/
public function isContactAdditiveInheritance(): bool
{
return $this->isContactAdditiveInheritance;
}
/**
* @param bool $isContactGroupAdditiveInheritance
*/
public function setContactGroupAdditiveInheritance(bool $isContactGroupAdditiveInheritance): void
{
$this->isContactGroupAdditiveInheritance = $isContactGroupAdditiveInheritance;
}
/**
* @return bool
*/
public function isContactGroupAdditiveInheritance(): bool
{
return $this->isContactGroupAdditiveInheritance;
}
/**
* @param bool $isActivated
*/
public function setActivated(bool $isActivated): void
{
$this->isActivated = $isActivated;
}
/**
* @return bool
*/
public function isActivated(): bool
{
return $this->isActivated;
}
/**
* @param YesNoDefault $activeChecks
*/
public function setActiveChecks(YesNoDefault $activeChecks): void
{
$this->activeChecks = $activeChecks;
}
/**
* @return YesNoDefault
*/
public function getActiveChecks(): YesNoDefault
{
return $this->activeChecks;
}
/**
* @param YesNoDefault $passiveCheck
*/
public function setPassiveCheck(YesNoDefault $passiveCheck): void
{
$this->passiveCheck = $passiveCheck;
}
/**
* @return YesNoDefault
*/
public function getPassiveCheck(): YesNoDefault
{
return $this->passiveCheck;
}
/**
* @param YesNoDefault $volatility
*/
public function setVolatility(YesNoDefault $volatility): void
{
$this->volatility = $volatility;
}
/**
* @return YesNoDefault
*/
public function getVolatility(): YesNoDefault
{
return $this->volatility;
}
/**
* @param YesNoDefault $checkFreshness
*/
public function setCheckFreshness(YesNoDefault $checkFreshness): void
{
$this->checkFreshness = $checkFreshness;
}
/**
* @return YesNoDefault
*/
public function getCheckFreshness(): YesNoDefault
{
return $this->checkFreshness;
}
/**
* @param YesNoDefault $eventHandlerEnabled
*/
public function setEventHandlerEnabled(YesNoDefault $eventHandlerEnabled): void
{
$this->eventHandlerEnabled = $eventHandlerEnabled;
}
/**
* @return YesNoDefault
*/
public function getEventHandlerEnabled(): YesNoDefault
{
return $this->eventHandlerEnabled;
}
/**
* @param YesNoDefault $flapDetectionEnabled
*/
public function setFlapDetectionEnabled(YesNoDefault $flapDetectionEnabled): void
{
$this->flapDetectionEnabled = $flapDetectionEnabled;
}
/**
* @return YesNoDefault
*/
public function getFlapDetectionEnabled(): YesNoDefault
{
return $this->flapDetectionEnabled;
}
/**
* @param YesNoDefault $notificationsEnabled
*/
public function setNotificationsEnabled(YesNoDefault $notificationsEnabled): void
{
$this->notificationsEnabled = $notificationsEnabled;
}
/**
* @return YesNoDefault
*/
public function getNotificationsEnabled(): YesNoDefault
{
return $this->notificationsEnabled;
}
/**
* @param string|null $comment
*
* @throws AssertionFailedException
*/
public function setComment(?string $comment): void
{
if ($comment !== null) {
$comment = trim($comment);
Assertion::notEmptyString($comment, $this->className . '::comment');
Assertion::maxLength($comment, self::MAX_COMMENT_LENGTH, $this->className . '::comment');
}
$this->comment = $comment;
}
/**
* @return string|null
*/
public function getComment(): ?string
{
return $this->comment;
}
/**
* @param string|null $note
*
* @throws AssertionFailedException
*/
public function setNote(?string $note): void
{
if ($note !== null) {
$note = trim($note);
Assertion::notEmptyString($note, $this->className . '::note');
Assertion::maxLength($note, self::MAX_NOTES_LENGTH, $this->className . '::note');
}
$this->note = $note;
}
/**
* @return string|null
*/
public function getNote(): ?string
{
return $this->note;
}
/**
* @param string|null $noteUrl
*
* @throws AssertionFailedException
*/
public function setNoteUrl(?string $noteUrl): void
{
if ($noteUrl !== null) {
$noteUrl = trim($noteUrl);
Assertion::notEmptyString($noteUrl, $this->className . '::noteUrl');
Assertion::maxLength($noteUrl, self::MAX_NOTES_URL_LENGTH, $this->className . '::noteUrl');
}
$this->noteUrl = $noteUrl;
}
/**
* @return string|null
*/
public function getNoteUrl(): ?string
{
return $this->noteUrl;
}
/**
* @param string|null $actionUrl
*
* @throws AssertionFailedException
*/
public function setActionUrl(?string $actionUrl): void
{
if ($actionUrl !== null) {
$actionUrl = trim($actionUrl);
Assertion::notEmptyString($actionUrl, $this->className . '::actionUrl');
Assertion::maxLength($actionUrl, self::MAX_ACTION_URL_LENGTH, $this->className . '::actionUrl');
}
$this->actionUrl = $actionUrl;
}
/**
* @return string|null
*/
public function getActionUrl(): ?string
{
return $this->actionUrl;
}
/**
* @param string|null $iconAlternativeText
*
* @throws AssertionFailedException
*/
public function setIconAlternativeText(?string $iconAlternativeText): void
{
if ($iconAlternativeText !== null) {
$iconAlternativeText = trim($iconAlternativeText);
Assertion::notEmptyString($iconAlternativeText, $this->className . '::iconAlternativeText');
Assertion::maxLength(
$iconAlternativeText,
self::MAX_ICON_ALT_LENGTH,
$this->className . '::iconAlternativeText'
);
}
$this->iconAlternativeText = $iconAlternativeText;
}
/**
* @return string|null
*/
public function getIconAlternativeText(): ?string
{
return $this->iconAlternativeText;
}
/**
* @param int|null $graphTemplateId
*
* @throws AssertionFailedException
*/
public function setGraphTemplateId(?int $graphTemplateId): void
{
if ($graphTemplateId !== null) {
Assertion::positiveInt($graphTemplateId, $this->className . '::graphTemplateId');
}
$this->graphTemplateId = $graphTemplateId;
}
/**
* @return int|null
*/
public function getGraphTemplateId(): ?int
{
return $this->graphTemplateId;
}
/**
* @param int|null $serviceTemplateParentId
*
* @throws AssertionFailedException
*/
public function setServiceTemplateParentId(?int $serviceTemplateParentId): void
{
if ($serviceTemplateParentId !== null) {
Assertion::positiveInt($serviceTemplateParentId, $this->className . '::serviceTemplateParentId');
}
$this->serviceTemplateParentId = $serviceTemplateParentId;
}
/**
* @return int|null
*/
public function getServiceTemplateParentId(): ?int
{
return $this->serviceTemplateParentId;
}
/**
* @param int|null $commandId
*
* @throws AssertionFailedException
*/
public function setCommandId(?int $commandId): void
{
if ($commandId !== null) {
Assertion::positiveInt($commandId, $this->className . '::commandId');
}
$this->commandId = $commandId;
}
/**
* @return int|null
*/
public function getCommandId(): ?int
{
return $this->commandId;
}
/**
* @param int|null $eventHandlerId
*
* @throws AssertionFailedException
*/
public function setEventHandlerId(?int $eventHandlerId): void
{
if ($eventHandlerId !== null) {
Assertion::positiveInt($eventHandlerId, $this->className . '::eventHandlerId');
}
$this->eventHandlerId = $eventHandlerId;
}
/**
* @return int|null
*/
public function getEventHandlerId(): ?int
{
return $this->eventHandlerId;
}
/**
* @param int|null $notificationTimePeriodId
*
* @throws AssertionFailedException
*/
public function setNotificationTimePeriodId(?int $notificationTimePeriodId): void
{
if ($notificationTimePeriodId !== null) {
Assertion::positiveInt($notificationTimePeriodId, $this->className . '::notificationTimePeriodId');
}
$this->notificationTimePeriodId = $notificationTimePeriodId;
}
/**
* @return int|null
*/
public function getNotificationTimePeriodId(): ?int
{
return $this->notificationTimePeriodId;
}
/**
* @param int|null $checkTimePeriodId
*
* @throws AssertionFailedException
*/
public function setCheckTimePeriodId(?int $checkTimePeriodId): void
{
if ($checkTimePeriodId !== null) {
Assertion::positiveInt($checkTimePeriodId, $this->className . '::checkTimePeriodId');
}
$this->checkTimePeriodId = $checkTimePeriodId;
}
/**
* @return int|null
*/
public function getCheckTimePeriodId(): ?int
{
return $this->checkTimePeriodId;
}
/**
* @param int|null $iconId
*
* @throws AssertionFailedException
*/
public function setIconId(?int $iconId): void
{
if ($iconId !== null) {
Assertion::positiveInt($iconId, $this->className . '::iconId');
}
$this->iconId = $iconId;
}
/**
* @return int|null
*/
public function getIconId(): ?int
{
return $this->iconId;
}
/**
* @param int|null $severityId
*
* @throws AssertionFailedException
*/
public function setSeverityId(?int $severityId): void
{
if ($severityId !== null) {
Assertion::positiveInt($severityId, $this->className . '::severityId');
}
$this->severityId = $severityId;
}
/**
* @return int|null
*/
public function getSeverityId(): ?int
{
return $this->severityId;
}
/**
* @param int|null $maxCheckAttempts
*
* @throws AssertionFailedException
*/
public function setMaxCheckAttempts(?int $maxCheckAttempts): void
{
if ($maxCheckAttempts !== null) {
Assertion::min($maxCheckAttempts, 0, $this->className . '::maxCheckAttempts');
}
$this->maxCheckAttempts = $maxCheckAttempts;
}
/**
* @return int|null
*/
public function getMaxCheckAttempts(): ?int
{
return $this->maxCheckAttempts;
}
/**
* @param int|null $normalCheckInterval
*
* @throws AssertionFailedException
*/
public function setNormalCheckInterval(?int $normalCheckInterval): void
{
if ($normalCheckInterval !== null) {
Assertion::min($normalCheckInterval, 0, $this->className . '::normalCheckInterval');
}
$this->normalCheckInterval = $normalCheckInterval;
}
/**
* @return int|null
*/
public function getNormalCheckInterval(): ?int
{
return $this->normalCheckInterval;
}
/**
* @param int|null $retryCheckInterval
*
* @throws AssertionFailedException
*/
public function setRetryCheckInterval(?int $retryCheckInterval): void
{
if ($retryCheckInterval !== null) {
Assertion::min($retryCheckInterval, 0, $this->className . '::retryCheckInterval');
}
$this->retryCheckInterval = $retryCheckInterval;
}
/**
* @return int|null
*/
public function getRetryCheckInterval(): ?int
{
return $this->retryCheckInterval;
}
/**
* @param int|null $freshnessThreshold
*
* @throws AssertionFailedException
*/
public function setFreshnessThreshold(?int $freshnessThreshold): void
{
if ($freshnessThreshold !== null) {
Assertion::min($freshnessThreshold, 0, $this->className . '::freshnessThreshold');
}
$this->freshnessThreshold = $freshnessThreshold;
}
/**
* @return int|null
*/
public function getFreshnessThreshold(): ?int
{
return $this->freshnessThreshold;
}
/**
* @param int|null $lowFlapThreshold
*
* @throws AssertionFailedException
*/
public function setLowFlapThreshold(?int $lowFlapThreshold): void
{
if ($lowFlapThreshold !== null) {
Assertion::min($lowFlapThreshold, 0, $this->className . '::lowFlapThreshold');
}
$this->lowFlapThreshold = $lowFlapThreshold;
}
/**
* @return int|null
*/
public function getLowFlapThreshold(): ?int
{
return $this->lowFlapThreshold;
}
/**
* @param int|null $highFlapThreshold
*
* @throws AssertionFailedException
*/
public function setHighFlapThreshold(?int $highFlapThreshold): void
{
if ($highFlapThreshold !== null) {
Assertion::min($highFlapThreshold, 0, $this->className . '::highFlapThreshold');
}
$this->highFlapThreshold = $highFlapThreshold;
}
/**
* @return int|null
*/
public function getHighFlapThreshold(): ?int
{
return $this->highFlapThreshold;
}
/**
* @param int|null $notificationInterval
*
* @throws AssertionFailedException
*/
public function setNotificationInterval(?int $notificationInterval): void
{
if ($notificationInterval !== null) {
Assertion::min($notificationInterval, 0, $this->className . '::notificationInterval');
}
$this->notificationInterval = $notificationInterval;
}
/**
* @return int|null
*/
public function getNotificationInterval(): ?int
{
return $this->notificationInterval;
}
/**
* @param int|null $recoveryNotificationDelay
*
* @throws AssertionFailedException
*/
public function setRecoveryNotificationDelay(?int $recoveryNotificationDelay): void
{
if ($recoveryNotificationDelay !== null) {
Assertion::min($recoveryNotificationDelay, 0, $this->className . '::recoveryNotificationDelay');
}
$this->recoveryNotificationDelay = $recoveryNotificationDelay;
}
/**
* @return int|null
*/
public function getRecoveryNotificationDelay(): ?int
{
return $this->recoveryNotificationDelay;
}
/**
* @param int|null $firstNotificationDelay
*
* @throws AssertionFailedException
*/
public function setFirstNotificationDelay(?int $firstNotificationDelay): void
{
if ($firstNotificationDelay !== null) {
Assertion::min($firstNotificationDelay, 0, $this->className . '::firstNotificationDelay');
}
$this->firstNotificationDelay = $firstNotificationDelay;
}
/**
* @return int|null
*/
public function getFirstNotificationDelay(): ?int
{
return $this->firstNotificationDelay;
}
/**
* @param int|null $acknowledgementTimeout
*
* @throws AssertionFailedException
*/
public function setAcknowledgementTimeout(?int $acknowledgementTimeout): void
{
if ($acknowledgementTimeout !== null) {
Assertion::min($acknowledgementTimeout, 0, $this->className . '::acknowledgementTimeout');
}
$this->acknowledgementTimeout = $acknowledgementTimeout;
}
/**
* @return int|null
*/
public function getAcknowledgementTimeout(): ?int
{
return $this->acknowledgementTimeout;
}
/**
* @return int
*/
public function getHostId(): int
{
return $this->hostId;
}
/**
* @param int $hostId
*
* @throws AssertionFailedException
*/
public function setHostId(int $hostId): void
{
Assertion::positiveInt($hostId, $this->className . '::hostId');
$this->hostId = $hostId;
}
/**
* @param GeoCoords|null $geoCoords
*/
public function setGeoCoords(?GeoCoords $geoCoords): void
{
$this->geoCoords = $geoCoords;
}
/**
* @return GeoCoords|null
*/
public function getGeoCoords(): ?GeoCoords
{
return $this->geoCoords;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Domain/Model/ServiceInheritance.php | centreon/src/Core/Service/Domain/Model/ServiceInheritance.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
class ServiceInheritance
{
/**
* @param int $parentId
* @param int $childId
*
* @throws AssertionFailedException
*/
public function __construct(
private readonly int $parentId,
private readonly int $childId,
) {
Assertion::positiveInt($parentId, 'ParentServiceTemplate::parentID');
Assertion::positiveInt($childId, 'ParentServiceTemplate::childId');
}
/**
* @return int
*/
public function getParentId(): int
{
return $this->parentId;
}
/**
* @return int
*/
public function getChildId(): int
{
return $this->childId;
}
/**
* Return an ordered line of inheritance for a service.
* (This is a recursive method).
*
* @param int $serviceId
* @param ServiceInheritance[] $parents
*
* @return int[]
*/
public static function createInheritanceLine(int $serviceId, array $parents): array
{
foreach ($parents as $index => $parent) {
if ($parent->getChildId() === $serviceId) {
unset($parents[$index]);
return array_merge(
[$parent->getParentId()],
self::createInheritanceLine($parent->getParentId(), $parents)
);
}
}
return [];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Domain/Model/ServiceLight.php | centreon/src/Core/Service/Domain/Model/ServiceLight.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Core\Common\Domain\SimpleEntity;
use Core\Common\Domain\TrimmedString;
use Core\ServiceGroup\Domain\Model\ServiceGroupRelation;
class ServiceLight
{
public const MAX_NAME_LENGTH = NewService::MAX_NAME_LENGTH;
/**
* @param int $id
* @param TrimmedString $name
* @param int[] $hostIds
* @param int[] $categoryIds
* @param ServiceGroupRelation[] $groups
* @param null|SimpleEntity $serviceTemplate
* @param null|SimpleEntity $notificationTimePeriod
* @param null|SimpleEntity $checkTimePeriod
* @param null|SimpleEntity $severity
* @param null|int $normalCheckInterval
* @param null|int $retryCheckInterval
* @param bool $isActivated
*
* @throws AssertionFailedException
*/
public function __construct(
private readonly int $id,
private readonly TrimmedString $name,
private readonly array $hostIds,
private readonly array $categoryIds = [],
private readonly array $groups = [],
private readonly ?SimpleEntity $serviceTemplate = null,
private readonly ?SimpleEntity $notificationTimePeriod = null,
private readonly ?SimpleEntity $checkTimePeriod = null,
private readonly ?SimpleEntity $severity = null,
private readonly ?int $normalCheckInterval = null,
private readonly ?int $retryCheckInterval = null,
private readonly bool $isActivated = true,
) {
$className = (new \ReflectionClass($this))->getShortName();
Assertion::positiveInt($id, "{$className}::id");
Assertion::notEmptyString($this->name->value, "{$className}::name");
Assertion::maxLength($this->name->value, self::MAX_NAME_LENGTH, "{$className}::name");
Assertion::notEmpty($hostIds, "{$className}::hostIds");
Assertion::arrayOfTypeOrNull('int', $hostIds, "{$className}::hostIds");
Assertion::arrayOfTypeOrNull('int', $hostIds, "{$className}::categoryIds");
if ($normalCheckInterval !== null) {
Assertion::min($normalCheckInterval, 0, "{$className}::normalCheckInterval");
}
if ($retryCheckInterval !== null) {
Assertion::min($retryCheckInterval, 0, "{$className}::retryCheckInterval");
}
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name->value;
}
/**
* @return bool
*/
public function isActivated(): bool
{
return $this->isActivated;
}
/**
* @return null|SimpleEntity
*/
public function getServiceTemplate(): ?SimpleEntity
{
return $this->serviceTemplate;
}
/**
* @return null|SimpleEntity
*/
public function getNotificationTimePeriod(): ?SimpleEntity
{
return $this->notificationTimePeriod;
}
/**
* @return null|SimpleEntity
*/
public function getCheckTimePeriod(): ?SimpleEntity
{
return $this->checkTimePeriod;
}
/**
* @return null|SimpleEntity
*/
public function getSeverity(): ?SimpleEntity
{
return $this->severity;
}
/**
* @return null|int
*/
public function getNormalCheckInterval(): ?int
{
return $this->normalCheckInterval;
}
/**
* @return null|int
*/
public function getRetryCheckInterval(): ?int
{
return $this->retryCheckInterval;
}
/**
* @return int[]
*/
public function getHostIds(): array
{
return $this->hostIds;
}
/**
* @return int[]
*/
public function getCategoryIds(): array
{
return $this->categoryIds;
}
/**
* @return ServiceGroupRelation[]
*/
public function getGroups(): array
{
return $this->groups;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Domain/Model/ServiceStatusesCount.php | centreon/src/Core/Service/Domain/Model/ServiceStatusesCount.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Domain\Model;
class ServiceStatusesCount
{
public const STATUS_OK = 0;
public const STATUS_WARNING = 1;
public const STATUS_CRITICAL = 2;
public const STATUS_UNKNOWN = 3;
public const STATUS_PENDING = 4;
public function __construct(
private readonly int $totalOk,
private readonly int $totalWarning,
private readonly int $totalUnknown,
private readonly int $totalCritical,
private readonly int $totalPending,
) {
}
public function getTotalPending(): int
{
return $this->totalPending;
}
public function getTotalCritical(): int
{
return $this->totalCritical;
}
public function getTotalOk(): int
{
return $this->totalOk;
}
public function getTotalWarning(): int
{
return $this->totalWarning;
}
public function getTotalUnknown(): int
{
return $this->totalUnknown;
}
public function getTotal(): int
{
return array_sum([
$this->totalOk,
$this->totalWarning,
$this->totalCritical,
$this->totalUnknown,
$this->totalPending,
]);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Domain/Model/NotificationType.php | centreon/src/Core/Service/Domain/Model/NotificationType.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Domain\Model;
enum NotificationType
{
case Warning;
case Unknown;
case Critical;
case Recovery;
case Flapping;
case DowntimeScheduled;
case None;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Domain/Model/ServiceRelation.php | centreon/src/Core/Service/Domain/Model/ServiceRelation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Domain\Model;
final readonly class ServiceRelation
{
/**
* @param int $serviceId
* @param int[] $hostGroupIds
* @param int[] $hostIds
* @param int[] $serviceGroupIds
*/
public function __construct(
private int $serviceId,
private array $hostGroupIds = [],
private array $hostIds = [],
private array $serviceGroupIds = [],
) {
}
public function getServiceId(): int
{
return $this->serviceId;
}
/**
* @return int[]
*/
public function getHostGroupIds(): array
{
return $this->hostGroupIds;
}
/**
* @return int[]
*/
public function getHostIds(): array
{
return $this->hostIds;
}
/**
* @return int[]
*/
public function getServiceGroupIds(): array
{
return $this->serviceGroupIds;
}
public function hasOnlyOneHostGroup(): bool
{
return count($this->hostGroupIds) === 1;
}
public function hasOnlyOneHost(): bool
{
return count($this->hostIds) === 1;
}
public function hasOnlyOneServiceGroup(): bool
{
return count($this->serviceGroupIds) === 1;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Domain/Model/ServiceNamesByHost.php | centreon/src/Core/Service/Domain/Model/ServiceNamesByHost.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Domain\Model;
use Core\Common\Domain\TrimmedString;
class ServiceNamesByHost
{
/** @var list<string> */
private array $names = [];
/**
* @param int $hostId
* @param list<string> $servicesName
*/
public function __construct(private readonly int $hostId, array $servicesName)
{
$this->setServicesName($servicesName);
}
/**
* @param TrimmedString $serviceName
*
* @return bool
*/
public function contains(TrimmedString $serviceName): bool
{
return in_array($serviceName->value, $this->names, true);
}
/**
* @return int
*/
public function getHostId(): int
{
return $this->hostId;
}
/**
* @template T
*
* @param list<T> $servicesName
*/
private function setServicesName(array $servicesName): void
{
$this->names = [];
foreach ($servicesName as $serviceName) {
$this->names[] = (string) $serviceName;
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Domain/Model/Service.php | centreon/src/Core/Service/Domain/Model/Service.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Common\Domain\YesNoDefault;
use Core\Domain\Common\GeoCoords;
use Core\MonitoringServer\Model\MonitoringServer;
class Service
{
public const MAX_NAME_LENGTH = NewService::MAX_NAME_LENGTH;
public const MAX_COMMENT_LENGTH = NewService::MAX_COMMENT_LENGTH;
public const MAX_NOTES_LENGTH = NewService::MAX_NOTES_LENGTH;
public const MAX_NOTES_URL_LENGTH = NewService::MAX_NOTES_URL_LENGTH;
public const MAX_ACTION_URL_LENGTH = NewService::MAX_ACTION_URL_LENGTH;
public const MAX_ICON_ALT_LENGTH = NewService::MAX_ICON_ALT_LENGTH;
/** @var list<string> */
private array $commandArguments = [];
/** @var list<string> */
private array $eventHandlerArguments = [];
/**
* @param int $id
* @param string $name
* @param int $hostId
* @param list<mixed> $commandArguments
* @param list<mixed> $eventHandlerArguments
* @param NotificationType[] $notificationTypes
* @param bool $contactAdditiveInheritance
* @param bool $contactGroupAdditiveInheritance
* @param bool $isActivated
* @param YesNoDefault $activeChecks
* @param YesNoDefault $passiveCheck
* @param YesNoDefault $volatility
* @param YesNoDefault $checkFreshness
* @param YesNoDefault $eventHandlerEnabled
* @param YesNoDefault $flapDetectionEnabled
* @param YesNoDefault $notificationsEnabled
* @param string|null $comment
* @param string|null $note
* @param string|null $noteUrl
* @param string|null $actionUrl
* @param string|null $iconAlternativeText
* @param int|null $graphTemplateId
* @param int|null $serviceTemplateParentId
* @param int|null $commandId
* @param int|null $eventHandlerId
* @param int|null $notificationTimePeriodId
* @param int|null $checkTimePeriodId
* @param int|null $iconId
* @param int|null $severityId
* @param int|null $maxCheckAttempts
* @param int|null $normalCheckInterval
* @param int|null $retryCheckInterval
* @param int|null $freshnessThreshold
* @param int|null $lowFlapThreshold
* @param int|null $highFlapThreshold
* @param int|null $notificationInterval
* @param int|null $recoveryNotificationDelay
* @param int|null $firstNotificationDelay
* @param int|null $acknowledgementTimeout
* @param GeoCoords|null $geoCoords
*
* @throws AssertionFailedException
*/
public function __construct(
private readonly int $id,
private string $name,
private int $hostId,
array $commandArguments = [],
array $eventHandlerArguments = [],
private array $notificationTypes = [],
private bool $contactAdditiveInheritance = false,
private bool $contactGroupAdditiveInheritance = false,
private bool $isActivated = true,
private YesNoDefault $activeChecks = YesNoDefault::Default,
private YesNoDefault $passiveCheck = YesNoDefault::Default,
private YesNoDefault $volatility = YesNoDefault::Default,
private YesNoDefault $checkFreshness = YesNoDefault::Default,
private YesNoDefault $eventHandlerEnabled = YesNoDefault::Default,
private YesNoDefault $flapDetectionEnabled = YesNoDefault::Default,
private YesNoDefault $notificationsEnabled = YesNoDefault::Default,
private ?string $comment = null,
private ?string $note = null,
private ?string $noteUrl = null,
private ?string $actionUrl = null,
private ?string $iconAlternativeText = null,
private ?int $graphTemplateId = null,
private ?int $serviceTemplateParentId = null,
private ?int $commandId = null,
private ?int $eventHandlerId = null,
private ?int $notificationTimePeriodId = null,
private ?int $checkTimePeriodId = null,
private ?int $iconId = null,
private ?int $severityId = null,
private ?int $maxCheckAttempts = null,
private ?int $normalCheckInterval = null,
private ?int $retryCheckInterval = null,
private ?int $freshnessThreshold = null,
private ?int $lowFlapThreshold = null,
private ?int $highFlapThreshold = null,
private ?int $notificationInterval = null,
private ?int $recoveryNotificationDelay = null,
private ?int $firstNotificationDelay = null,
private ?int $acknowledgementTimeout = null,
private ?GeoCoords $geoCoords = null,
) {
$className = (new \ReflectionClass($this))->getShortName();
Assertion::positiveInt($id, "{$className}::id");
Assertion::positiveInt($hostId, $className . '::hostId');
foreach (
[
'name' => self::MAX_NAME_LENGTH,
'comment' => self::MAX_COMMENT_LENGTH,
'note' => self::MAX_NOTES_LENGTH,
'noteUrl' => self::MAX_NOTES_URL_LENGTH,
'actionUrl' => self::MAX_ACTION_URL_LENGTH,
'iconAlternativeText' => self::MAX_ICON_ALT_LENGTH,
] as $field => $limitation
) {
$propertyValue = $this->{$field};
if (in_array($field, ['name'], true)) {
$propertyValue = preg_replace('/\s{2,}/', ' ', $propertyValue);
if ($propertyValue === null) {
throw AssertionException::notNull($className . '::' . $field);
}
Assertion::unauthorizedCharacters(
$propertyValue,
MonitoringServer::ILLEGAL_CHARACTERS,
$className . '::' . $field
);
}
if ($propertyValue !== null) {
$this->{$field} = trim($propertyValue);
Assertion::notEmptyString($this->{$field}, "{$className}::{$field}");
Assertion::maxLength($this->{$field}, $limitation, "{$className}::{$field}");
}
}
// Assertions on ForeignKeys
$foreignKeys = [
'serviceTemplateParentId',
'commandId',
'eventHandlerId',
'notificationTimePeriodId',
'checkTimePeriodId',
'iconId',
'graphTemplateId',
'severityId',
];
foreach ($foreignKeys as $propertyName) {
$propertyValue = $this->{$propertyName};
if ($propertyValue !== null) {
Assertion::positiveInt($propertyValue, "{$className}::{$propertyName}");
}
}
$properties = [
'maxCheckAttempts',
'normalCheckInterval',
'retryCheckInterval',
'freshnessThreshold',
'notificationInterval',
'recoveryNotificationDelay',
'firstNotificationDelay',
'acknowledgementTimeout',
'lowFlapThreshold',
'highFlapThreshold',
];
foreach ($properties as $propertyName) {
$propertyValue = $this->{$propertyName};
if ($propertyValue !== null) {
Assertion::min($propertyValue, 0, "{$className}::{$propertyName}");
}
}
foreach ($commandArguments as $argument) {
if (is_scalar($argument)) {
$this->commandArguments[] = (string) $argument;
}
}
foreach ($eventHandlerArguments as $argument) {
if (is_scalar($argument)) {
$this->eventHandlerArguments[] = (string) $argument;
}
}
foreach ($this->notificationTypes as $type) {
Assertion::isInstanceOf($type, NotificationType::class, "{$className}::notificationTypes");
}
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @return list<string>
*/
public function getCommandArguments(): array
{
return $this->commandArguments;
}
/**
* @return list<string>
*/
public function getEventHandlerArguments(): array
{
return $this->eventHandlerArguments;
}
/**
* @return NotificationType[]
*/
public function getNotificationTypes(): array
{
return $this->notificationTypes;
}
/**
* @return bool
*/
public function isContactAdditiveInheritance(): bool
{
return $this->contactAdditiveInheritance;
}
/**
* @return bool
*/
public function isContactGroupAdditiveInheritance(): bool
{
return $this->contactGroupAdditiveInheritance;
}
/**
* @return bool
*/
public function isActivated(): bool
{
return $this->isActivated;
}
/**
* @return YesNoDefault
*/
public function getActiveChecks(): YesNoDefault
{
return $this->activeChecks;
}
/**
* @return YesNoDefault
*/
public function getPassiveCheck(): YesNoDefault
{
return $this->passiveCheck;
}
/**
* @return YesNoDefault
*/
public function getVolatility(): YesNoDefault
{
return $this->volatility;
}
/**
* @return YesNoDefault
*/
public function getCheckFreshness(): YesNoDefault
{
return $this->checkFreshness;
}
/**
* @return YesNoDefault
*/
public function getEventHandlerEnabled(): YesNoDefault
{
return $this->eventHandlerEnabled;
}
/**
* @return YesNoDefault
*/
public function getFlapDetectionEnabled(): YesNoDefault
{
return $this->flapDetectionEnabled;
}
/**
* @return YesNoDefault
*/
public function getNotificationsEnabled(): YesNoDefault
{
return $this->notificationsEnabled;
}
/**
* @return string|null
*/
public function getComment(): ?string
{
return $this->comment;
}
/**
* @return string|null
*/
public function getNote(): ?string
{
return $this->note;
}
/**
* @return string|null
*/
public function getNoteUrl(): ?string
{
return $this->noteUrl;
}
/**
* @return string|null
*/
public function getActionUrl(): ?string
{
return $this->actionUrl;
}
/**
* @return string|null
*/
public function getIconAlternativeText(): ?string
{
return $this->iconAlternativeText;
}
/**
* @return int|null
*/
public function getGraphTemplateId(): ?int
{
return $this->graphTemplateId;
}
/**
* @return int|null
*/
public function getServiceTemplateParentId(): ?int
{
return $this->serviceTemplateParentId;
}
/**
* @return int|null
*/
public function getCommandId(): ?int
{
return $this->commandId;
}
/**
* @return int|null
*/
public function getEventHandlerId(): ?int
{
return $this->eventHandlerId;
}
/**
* @return int|null
*/
public function getNotificationTimePeriodId(): ?int
{
return $this->notificationTimePeriodId;
}
/**
* @return int|null
*/
public function getCheckTimePeriodId(): ?int
{
return $this->checkTimePeriodId;
}
/**
* @return int|null
*/
public function getIconId(): ?int
{
return $this->iconId;
}
/**
* @return int|null
*/
public function getSeverityId(): ?int
{
return $this->severityId;
}
/**
* @return int|null
*/
public function getMaxCheckAttempts(): ?int
{
return $this->maxCheckAttempts;
}
/**
* @return int|null
*/
public function getNormalCheckInterval(): ?int
{
return $this->normalCheckInterval;
}
/**
* @return int|null
*/
public function getRetryCheckInterval(): ?int
{
return $this->retryCheckInterval;
}
/**
* @return int|null
*/
public function getFreshnessThreshold(): ?int
{
return $this->freshnessThreshold;
}
/**
* @return int|null
*/
public function getLowFlapThreshold(): ?int
{
return $this->lowFlapThreshold;
}
/**
* @return int|null
*/
public function getHighFlapThreshold(): ?int
{
return $this->highFlapThreshold;
}
/**
* @return int|null
*/
public function getNotificationInterval(): ?int
{
return $this->notificationInterval;
}
/**
* @return int|null
*/
public function getRecoveryNotificationDelay(): ?int
{
return $this->recoveryNotificationDelay;
}
/**
* @return int|null
*/
public function getFirstNotificationDelay(): ?int
{
return $this->firstNotificationDelay;
}
/**
* @return int|null
*/
public function getAcknowledgementTimeout(): ?int
{
return $this->acknowledgementTimeout;
}
public static function formatName(string $name): string
{
return (string) preg_replace('/\s{2,}/', ' ', $name);
}
/**
* @return int
*/
public function getHostId(): int
{
return $this->hostId;
}
/**
* @return GeoCoords|null
*/
public function getGeoCoords(): ?GeoCoords
{
return $this->geoCoords;
}
public function isNameIdentical(string $testName): bool
{
return $this->name === self::formatName($testName);
}
/**
* @param string $name
*
* @throws AssertionException
*/
public function setName(string $name): void
{
$name = preg_replace('/\s{2,}/', ' ', trim($name));
if ($name === null) {
throw AssertionException::notNull('Service::name');
}
Assertion::notEmptyString($name, 'Service::name');
Assertion::maxLength($name, self::MAX_NAME_LENGTH, 'Service::name');
Assertion::unauthorizedCharacters(
$name,
MonitoringServer::ILLEGAL_CHARACTERS,
'Service::name'
);
$this->name = $name;
}
/**
* @param int $hostId
*
* @throws AssertionException
*/
public function setHostId(int $hostId): void
{
Assertion::positiveInt($hostId, 'Service::hostId');
$this->hostId = $hostId;
}
public function setContactAdditiveInheritance(bool $contactAdditiveInheritance): void
{
$this->contactAdditiveInheritance = $contactAdditiveInheritance;
}
public function setContactGroupAdditiveInheritance(bool $contactGroupAdditiveInheritance): void
{
$this->contactGroupAdditiveInheritance = $contactGroupAdditiveInheritance;
}
public function setActivated(bool $isActivated): void
{
$this->isActivated = $isActivated;
}
public function setActiveChecks(YesNoDefault $activeChecks): void
{
$this->activeChecks = $activeChecks;
}
public function setPassiveCheck(YesNoDefault $passiveCheck): void
{
$this->passiveCheck = $passiveCheck;
}
public function setVolatility(YesNoDefault $volatility): void
{
$this->volatility = $volatility;
}
public function setCheckFreshness(YesNoDefault $checkFreshness): void
{
$this->checkFreshness = $checkFreshness;
}
public function setEventHandlerEnabled(YesNoDefault $eventHandlerEnabled): void
{
$this->eventHandlerEnabled = $eventHandlerEnabled;
}
public function setFlapDetectionEnabled(YesNoDefault $flapDetectionEnabled): void
{
$this->flapDetectionEnabled = $flapDetectionEnabled;
}
public function setNotificationsEnabled(YesNoDefault $notificationsEnabled): void
{
$this->notificationsEnabled = $notificationsEnabled;
}
/**
* @param string|null $comment
*
* @throws AssertionException
*/
public function setComment(?string $comment): void
{
if ($comment !== null) {
Assertion::notEmptyString($comment, 'Service::comment');
Assertion::maxLength($comment, self::MAX_COMMENT_LENGTH, 'Service::comment');
}
$this->comment = $comment;
}
/**
* @param string|null $note
*
* @throws AssertionException
*/
public function setNote(?string $note): void
{
if ($note !== null) {
Assertion::notEmptyString($note, 'Service::note');
Assertion::maxLength($note, self::MAX_NOTES_LENGTH, 'Service::note');
}
$this->note = $note;
}
/**
* @param string|null $noteUrl
*
* @throws AssertionException
*/
public function setNoteUrl(?string $noteUrl): void
{
if ($noteUrl !== null) {
Assertion::notEmptyString($noteUrl, 'Service::noteUrl');
Assertion::maxLength($noteUrl, self::MAX_NOTES_URL_LENGTH, 'Service::noteUrl');
}
$this->noteUrl = $noteUrl;
}
/**
* @param string|null $actionUrl
*
* @throws AssertionException
*/
public function setActionUrl(?string $actionUrl): void
{
if ($actionUrl !== null) {
Assertion::notEmptyString($actionUrl, 'Service::actionUrl');
Assertion::maxLength($actionUrl, self::MAX_ACTION_URL_LENGTH, 'Service::actionUrl');
}
$this->actionUrl = $actionUrl;
}
/**
* @param string|null $iconAlternativeText
*
* @throws AssertionException
*/
public function setIconAlternativeText(?string $iconAlternativeText): void
{
if ($iconAlternativeText !== null) {
Assertion::notEmptyString($iconAlternativeText, 'Service::iconAlternativeText');
Assertion::maxLength($iconAlternativeText, self::MAX_ICON_ALT_LENGTH, 'Service::iconAlternativeText');
}
$this->iconAlternativeText = $iconAlternativeText;
}
/**
* @param int|null $graphTemplateId
*
* @throws AssertionException
*/
public function setGraphTemplateId(?int $graphTemplateId): void
{
if ($graphTemplateId !== null) {
Assertion::positiveInt($graphTemplateId, 'Service::graphTemplateId');
}
$this->graphTemplateId = $graphTemplateId;
}
/**
* @param int|null $serviceTemplateParentId
*
* @throws AssertionException
*/
public function setServiceTemplateParentId(?int $serviceTemplateParentId): void
{
if ($serviceTemplateParentId !== null) {
Assertion::positiveInt($serviceTemplateParentId, 'Service::serviceTemplateParentId');
}
$this->serviceTemplateParentId = $serviceTemplateParentId;
}
/**
* @param int|null $commandId
*
* @throws AssertionException
*/
public function setCommandId(?int $commandId): void
{
if ($commandId !== null) {
Assertion::positiveInt($commandId, 'Service::commandId');
}
$this->commandId = $commandId;
}
/**
* @param int|null $eventHandlerId
*
* @throws AssertionException
*/
public function setEventHandlerId(?int $eventHandlerId): void
{
if ($eventHandlerId !== null) {
Assertion::positiveInt($eventHandlerId, 'Service::eventHandlerId');
}
$this->eventHandlerId = $eventHandlerId;
}
/**
* @param int|null $notificationTimePeriodId
*
* @throws AssertionException
*/
public function setNotificationTimePeriodId(?int $notificationTimePeriodId): void
{
if ($notificationTimePeriodId !== null) {
Assertion::positiveInt($notificationTimePeriodId, 'Service::notificationTimePeriodId');
}
$this->notificationTimePeriodId = $notificationTimePeriodId;
}
/**
* @param int|null $checkTimePeriodId
*
* @throws AssertionException
*/
public function setCheckTimePeriodId(?int $checkTimePeriodId): void
{
if ($checkTimePeriodId !== null) {
Assertion::positiveInt($checkTimePeriodId, 'Service::checkTimePeriodId');
}
$this->checkTimePeriodId = $checkTimePeriodId;
}
/**
* @param int|null $iconId
*
* @throws AssertionException
*/
public function setIconId(?int $iconId): void
{
if ($iconId !== null) {
Assertion::positiveInt($iconId, 'Service::iconId');
}
$this->iconId = $iconId;
}
/**
* @param int|null $severityId
*
* @throws AssertionException
*/
public function setSeverityId(?int $severityId): void
{
if ($severityId !== null) {
Assertion::positiveInt($severityId, 'Service::severityId');
}
$this->severityId = $severityId;
}
/**
* @param int|null $maxCheckAttempts
*
* @throws AssertionException
*/
public function setMaxCheckAttempts(?int $maxCheckAttempts): void
{
if ($maxCheckAttempts !== null) {
Assertion::min($maxCheckAttempts, 0, 'Service::maxCheckAttempts');
}
$this->maxCheckAttempts = $maxCheckAttempts;
}
/**
* @param int|null $normalCheckInterval
*
* @throws AssertionException
*/
public function setNormalCheckInterval(?int $normalCheckInterval): void
{
if ($normalCheckInterval !== null) {
Assertion::min($normalCheckInterval, 0, 'Service::normalCheckInterval');
}
$this->normalCheckInterval = $normalCheckInterval;
}
/**
* @param int|null $retryCheckInterval
*
* @throws AssertionException
*/
public function setRetryCheckInterval(?int $retryCheckInterval): void
{
if ($retryCheckInterval !== null) {
Assertion::min($retryCheckInterval, 0, 'Service::retryCheckInterval');
}
$this->retryCheckInterval = $retryCheckInterval;
}
/**
* @param int|null $freshnessThreshold
*
* @throws AssertionException
*/
public function setFreshnessThreshold(?int $freshnessThreshold): void
{
if ($freshnessThreshold !== null) {
Assertion::min($freshnessThreshold, 0, 'Service::freshnessThreshold');
}
$this->freshnessThreshold = $freshnessThreshold;
}
/**
* @param int|null $lowFlapThreshold
*
* @throws AssertionException
*/
public function setLowFlapThreshold(?int $lowFlapThreshold): void
{
if ($lowFlapThreshold !== null) {
Assertion::min($lowFlapThreshold, 0, 'Service::lowFlapThreshold');
}
$this->lowFlapThreshold = $lowFlapThreshold;
}
/**
* @param int|null $highFlapThreshold
*
* @throws AssertionException
*/
public function setHighFlapThreshold(?int $highFlapThreshold): void
{
if ($highFlapThreshold !== null) {
Assertion::min($highFlapThreshold, 0, 'Service::highFlapThreshold');
}
$this->highFlapThreshold = $highFlapThreshold;
}
/**
* @param int|null $notificationInterval
*
* @throws AssertionException
*/
public function setNotificationInterval(?int $notificationInterval): void
{
if ($notificationInterval !== null) {
Assertion::min($notificationInterval, 0, 'Service::notificationInterval');
}
$this->notificationInterval = $notificationInterval;
}
/**
* @param int|null $recoveryNotificationDelay
*
* @throws AssertionException
*/
public function setRecoveryNotificationDelay(?int $recoveryNotificationDelay): void
{
if ($recoveryNotificationDelay !== null) {
Assertion::min($recoveryNotificationDelay, 0, 'Service::recoveryNotificationDelay');
}
$this->recoveryNotificationDelay = $recoveryNotificationDelay;
}
/**
* @param int|null $firstNotificationDelay
*
* @throws AssertionException
*/
public function setFirstNotificationDelay(?int $firstNotificationDelay): void
{
if ($firstNotificationDelay !== null) {
Assertion::min($firstNotificationDelay, 0, 'Service::firstNotificationDelay');
}
$this->firstNotificationDelay = $firstNotificationDelay;
}
/**
* @param int|null $acknowledgementTimeout
*
* @throws AssertionException
*/
public function setAcknowledgementTimeout(?int $acknowledgementTimeout): void
{
if ($acknowledgementTimeout !== null) {
Assertion::min($acknowledgementTimeout, 0, 'Service::acknowledgementTimeout');
}
$this->acknowledgementTimeout = $acknowledgementTimeout;
}
public function setGeoCoords(?GeoCoords $geoCoords): void
{
$this->geoCoords = $geoCoords;
}
/**
* @param string[] $commandArguments
*/
public function setCommandArguments(array $commandArguments): void
{
$this->commandArguments = [];
foreach ($commandArguments as $commandArgument) {
if (\is_scalar($commandArgument)) {
$this->commandArguments[] = (string) $commandArgument;
}
}
}
/**
* @param string[] $eventHandlerArguments
*/
public function setEventHandlerArguments(array $eventHandlerArguments): void
{
$this->eventHandlerArguments = [];
foreach ($eventHandlerArguments as $eventHandlerArgument) {
if (\is_scalar($eventHandlerArgument)) {
$this->eventHandlerArguments[] = (string) $eventHandlerArgument;
}
}
}
/**
* @param NotificationType[] $notificationTypes
*
* @throws AssertionException
*/
public function setNotificationTypes(array $notificationTypes): void
{
$this->notificationTypes = [];
foreach ($notificationTypes as $notificationType) {
Assertion::isInstanceOf($notificationType, NotificationType::class, 'Service::notificationTypes');
$this->notificationTypes[] = $notificationType;
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Domain/Model/TinyService.php | centreon/src/Core/Service/Domain/Model/TinyService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Domain\Model;
use Core\Common\Domain\Comparable;
use Core\Common\Domain\Identifiable;
class TinyService implements Comparable, Identifiable
{
public function __construct(
readonly private int $id,
readonly private string $name,
readonly private string $hostName,
) {
}
public function getId(): int
{
return $this->id;
}
public function getName(): string
{
return $this->name;
}
public function getHostName(): string
{
return $this->hostName;
}
public function isEqual(object $object): bool
{
return $object instanceof self && $object->getEqualityHash() === $this->getEqualityHash();
}
public function getEqualityHash(): string
{
return md5($this->getHostName() . '/' . $this->getName());
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Infrastructure/Model/NotificationTypeConverter.php | centreon/src/Core/Service/Infrastructure/Model/NotificationTypeConverter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Infrastructure\Model;
use Core\Service\Domain\Model\NotificationType;
final class NotificationTypeConverter
{
public const NONE_AS_BIT = 0b000000;
public const NONE_AS_CHAR = 'n';
public const WARNING_AS_BIT = 0b000001;
public const WARNING_AS_CHAR = 'w';
public const UNKNOWN_AS_BIT = 0b000010;
public const UNKNOWN_AS_CHAR = 'u';
public const CRITICAL_AS_BIT = 0b000100;
public const CRITICAL_AS_CHAR = 'c';
public const RECOVERY_AS_BIT = 0b001000;
public const RECOVERY_AS_CHAR = 'r';
public const FLAPPING_AS_BIT = 0b010000;
public const FLAPPING_AS_CHAR = 'f';
public const DOWNTIME_SCHEDULED_AS_BIT = 0b100000;
public const DOWNTIME_SCHEDULED__AS_CHAR = 's';
/**
* @param NotificationType[] $notificationTypes
*
* @return int|null
*/
public static function toBits(array $notificationTypes): ?int
{
if ($notificationTypes === []) {
return null;
}
$bits = 0;
foreach ($notificationTypes as $type) {
// The 0 is considered a "None" type and therefore we do not expect any other values.
if (self::toBit($type) === 0) {
return 0;
}
$bits |= self::toBit($type);
}
return $bits;
}
/**
* @param NotificationType[] $notificationTypes
*
* @return string|null
*/
public static function toString(array $notificationTypes): ?string
{
$notificationChars = [];
if ($notificationTypes === []) {
return null;
}
foreach ($notificationTypes as $notification) {
$notificationChars[] = match ($notification) {
NotificationType::None => self::NONE_AS_CHAR,
NotificationType::Warning => self::WARNING_AS_CHAR,
NotificationType::Unknown => self::UNKNOWN_AS_CHAR,
NotificationType::Critical => self::CRITICAL_AS_CHAR,
NotificationType::Recovery => self::RECOVERY_AS_CHAR,
NotificationType::Flapping => self::FLAPPING_AS_CHAR,
NotificationType::DowntimeScheduled => self::DOWNTIME_SCHEDULED__AS_CHAR,
};
}
return implode(',', $notificationChars);
}
/**
* @param NotificationType $notificationType
*
* @return int
*/
private static function toBit(NotificationType $notificationType): int
{
return match ($notificationType) {
NotificationType::None => self::NONE_AS_BIT,
NotificationType::Warning => self::WARNING_AS_BIT,
NotificationType::Unknown => self::UNKNOWN_AS_BIT,
NotificationType::Critical => self::CRITICAL_AS_BIT,
NotificationType::Recovery => self::RECOVERY_AS_BIT,
NotificationType::Flapping => self::FLAPPING_AS_BIT,
NotificationType::DowntimeScheduled => self::DOWNTIME_SCHEDULED_AS_BIT,
};
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Infrastructure/Model/YesNoDefaultConverter.php | centreon/src/Core/Service/Infrastructure/Model/YesNoDefaultConverter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Infrastructure\Model;
use Core\Common\Domain\YesNoDefault;
final class YesNoDefaultConverter
{
public static function toInt(YesNoDefault $yesNoDefault): int
{
return match ($yesNoDefault) {
YesNoDefault::No => 0,
YesNoDefault::Yes => 1,
default => 2,
};
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Infrastructure/Voters/ServiceVoters.php | centreon/src/Core/Service/Infrastructure/Voters/ServiceVoters.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Infrastructure\Voters;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
/**
* @extends Voter<string, mixed>
*/
final class ServiceVoters extends Voter
{
public const SERVICE_DELETE = 'service_delete';
/**
* @inheritDoc
*/
protected function supports(string $attribute, mixed $subject): bool
{
return $attribute === self::SERVICE_DELETE;
}
/**
* @inheritDoc
*/
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (! $user instanceof ContactInterface) {
return false;
}
return match ($attribute) {
self::SERVICE_DELETE => $this->checkUserRights($user),
default => false,
};
}
/**
* Check that user has rights to perform write operations on services.
*
* @param ContactInterface $user
*
* @return bool
*/
private function checkUserRights(ContactInterface $user): bool
{
return $user->hasTopologyRole(Contact::ROLE_CONFIGURATION_SERVICES_WRITE);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Infrastructure/Serializer/DeleteServicesStatusResponseNormalizer.php | centreon/src/Core/Service/Infrastructure/Serializer/DeleteServicesStatusResponseNormalizer.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Infrastructure\Serializer;
use Centreon\Domain\Log\LoggerTrait;
use Core\Common\Domain\ResponseCodeEnum;
use Core\Infrastructure\Common\Api\Router;
use Core\Service\Application\UseCase\DeleteServices\DeleteServicesStatusResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
class DeleteServicesStatusResponseNormalizer implements NormalizerInterface
{
use LoggerTrait;
private const SERVICE_TOPOLOGY_PAGE = 60201;
/**
* @param Router $router
*/
public function __construct(
private readonly Router $router,
) {
}
/**
* @param DeleteServicesStatusResponse $object
* @param string|null $format
* @param array<string, mixed> $context
*
* @throws \Throwable
*
* @return array<string, mixed>
*/
public function normalize(
mixed $object,
?string $format = null,
array $context = [],
): array {
return [
'href' => $this->router->generateLegacyHref(self::SERVICE_TOPOLOGY_PAGE, ['o' => 'w', 'service_id' => $object->id]),
'status' => $this->enumToHttpStatusCodeConverter($object->status),
'message' => $object->message,
];
}
/**
* @param array<string, mixed> $context
* @param mixed $data
* @param ?string $format
*/
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof DeleteServicesStatusResponse;
}
/**
* @param ?string $format
* @return array<class-string|'*'|'object'|string, bool|null>
*/
public function getSupportedTypes(?string $format): array
{
return [
DeleteServicesStatusResponse::class => true,
];
}
/**
* Convert ResponseCodeEnum to HTTP Status Code
*
* @param ResponseCodeEnum $code
*
* @return int
*/
private function enumToHttpStatusCodeConverter(ResponseCodeEnum $code): int
{
return match ($code) {
ResponseCodeEnum::OK => Response::HTTP_NO_CONTENT,
ResponseCodeEnum::NotFound => Response::HTTP_NOT_FOUND,
ResponseCodeEnum::Error => Response::HTTP_INTERNAL_SERVER_ERROR,
};
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Infrastructure/Repository/ApiReadServiceRepository.php | centreon/src/Core/Service/Infrastructure/Repository/ApiReadServiceRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Infrastructure\Repository;
use Centreon\Domain\Repository\RepositoryException;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Common\Infrastructure\Repository\ApiCallIterator;
use Core\Common\Infrastructure\Repository\ApiRepositoryTrait;
use Core\Common\Infrastructure\Repository\ApiResponseTrait;
use Core\Service\Application\Repository\ReadServiceRepositoryInterface;
use Core\Service\Domain\Model\Service;
use Core\Service\Domain\Model\ServiceNamesByHost;
use Core\Service\Domain\Model\TinyService;
use Psr\Log\LoggerInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class ApiReadServiceRepository implements ReadServiceRepositoryInterface
{
use ApiResponseTrait;
use ApiRepositoryTrait;
public function __construct(
private readonly HttpClientInterface $httpClient,
private readonly RouterInterface $router,
private readonly LoggerInterface $logger,
) {
}
/**
* @inheritDoc
*/
public function exists(int $serviceId): bool
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function existsByAccessGroups(int $serviceId, array $accessGroups): bool
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function findMonitoringServerId(int $serviceId): int
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function findServiceIdsLinkedToHostId(int $hostId): array
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function findServiceIdsExclusivelyLinkedToHostId(int $hostId): array
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function findServiceNamesByHost(int $hostId): ?ServiceNamesByHost
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function findById(int $serviceId): ?Service
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function findByIds(int ...$serviceIds): array
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function findAll(): \Traversable&\Countable
{
$apiEndpoint = $this->router->generate('FindServices');
$options = [
'verify_peer' => true,
'verify_host' => true,
'timeout' => $this->timeout,
'headers' => ['X-AUTH-TOKEN: ' . $this->authenticationToken],
];
if ($this->proxy !== null) {
$options['proxy'] = $this->proxy;
$this->logger->info('Getting services using proxy');
}
$debugOptions = $options;
unset($debugOptions['headers'][0]);
$this->logger->debug('Connexion configuration', [
'url' => $apiEndpoint,
'options' => $debugOptions,
]);
/**
* @param array{id: int, name: string, hosts: array<array{name: string}>} $data
*
* @return \Generator<TinyService>
*/
$serviceFactory = function (array $data): \Generator {
$propertyName = isset($data['hosts']) ? 'hosts' : 'host';
foreach ($data[$propertyName] as $host) {
yield TinyServiceFactory::createFromApi([
'id' => $data['id'],
'name' => $data['name'],
'host_name' => $host['name'],
]);
}
};
return new ApiCallIterator(
$this->httpClient,
$this->url . $apiEndpoint,
$options,
$this->maxItemsByRequest,
$serviceFactory,
$this->logger
);
}
/**
* @inheritDoc
*/
public function findParents(int $serviceId): array
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function findByRequestParameter(RequestParametersInterface $requestParameters): array
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function findByRequestParameterAndAccessGroup(
RequestParametersInterface $requestParameters,
array $accessGroups,
): array {
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function exist(array $serviceIds): array
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function findServiceRelationsByHostGroupId(int $hostGroupId): array
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function findNameById(int $serviceId): ?string
{
throw RepositoryException::notYetImplemented();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Infrastructure/Repository/DbReadRealTimeServiceRepository.php | centreon/src/Core/Service/Infrastructure/Repository/DbReadRealTimeServiceRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Infrastructure\Repository;
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\RequestParameters\Interfaces\NormalizerInterface;
use Centreon\Infrastructure\RequestParameters\RequestParametersTranslatorException;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use Core\Common\Domain\Exception\CollectionException;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Common\Domain\Exception\ValueObjectException;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait;
use Core\Service\Application\Repository\ReadRealTimeServiceRepositoryInterface;
use Core\Service\Domain\Model\ServiceStatusesCount;
/**
* @phpstan-type _ServiceStatuses array{
* array{
* id: int,
* name: string,
* status: int
* }
* }|array{}
*/
class DbReadRealTimeServiceRepository extends AbstractRepositoryRDB implements ReadRealTimeServiceRepositoryInterface
{
use SqlMultipleBindTrait;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function findStatusesByRequestParameters(RequestParametersInterface $requestParameters): ServiceStatusesCount
{
$sqlTranslator = $this->prepareSqlRequestParametersTranslator($requestParameters);
$request = $this->returnBaseQuery();
$request .= $search = $sqlTranslator->translateSearchParameterToSql();
$request .= $search !== null ? ' AND ' : ' WHERE ';
$request .= 'services.type = 0 AND services.enabled = 1';
$request .= ' GROUP BY services.id, services.name, services.status ';
$sort = $sqlTranslator->translateSortParameterToSql();
$request .= $sort ?? ' ORDER BY services.name ASC';
$statement = $this->db->prepare($this->translateDbName($request));
$sqlTranslator->bindSearchValues($statement);
$statement->execute();
/** @var _ServiceStatuses $services */
$services = $statement->fetchAll(\PDO::FETCH_ASSOC);
return $this->createServiceStatusesCountFromRecord($services);
}
/**
* @inheritDoc
*/
public function findStatusesByRequestParametersAndAccessGroupIds(
RequestParametersInterface $requestParameters,
array $accessGroupIds,
): ServiceStatusesCount {
if ($accessGroupIds === []) {
$this->createServiceStatusesCountFromRecord([]);
}
[$bindValues, $bindQuery] = $this->createMultipleBindQuery($accessGroupIds, ':access_group');
$sqlTranslator = $this->prepareSqlRequestParametersTranslator($requestParameters);
$request = $this->returnBaseQuery();
// handle ACLs
$request .= <<<'SQL'
INNER JOIN `:dbstg`.centreon_acl acls
ON acls.service_id = services.id
AND acls.host_id = services.parent_id
SQL;
$request .= $search = $sqlTranslator->translateSearchParameterToSql();
$request .= $search !== null ? ' AND ' : ' WHERE ';
$request .= "services.type = 0 AND services.enabled = 1 AND acls.group_id IN ({$bindQuery})";
$request .= ' GROUP BY services.id, services.name, services.status ';
$sort = $sqlTranslator->translateSortParameterToSql();
$request .= $sort ?? ' ORDER BY services.name ASC';
$statement = $this->db->prepare($this->translateDbName($request));
$sqlTranslator->bindSearchValues($statement);
foreach ($bindValues as $token => $value) {
$statement->bindValue($token, $value, \PDO::PARAM_INT);
}
$statement->execute();
/** @var _ServiceStatuses $services */
$services = $statement->fetchAll(\PDO::FETCH_ASSOC);
return $this->createServiceStatusesCountFromRecord($services);
}
/**
* @inheritDoc
*/
public function findUniqueServiceNamesByRequestParameters(RequestParametersInterface $requestParameters): array
{
$selectSqlTranslator = $this->prepareSqlRequestParametersTranslator($requestParameters);
$countSqlTranslator = $this->prepareSqlRequestParametersTranslator($requestParameters);
$selectRequest = $this->findServiceNamesQuery($selectSqlTranslator, false);
$countRequest = $this->findServiceNamesQuery($countSqlTranslator, true);
$selectStatement = $this->db->prepare($this->translateDbName($selectRequest));
$selectSqlTranslator->bindSearchValues($selectStatement);
$selectStatement->execute();
$countStatement = $this->db->prepare($this->translateDbName($countRequest));
$countSqlTranslator->bindSearchValues($countStatement);
$countStatement->execute();
$serviceNames = $selectStatement->fetchAll(\PDO::FETCH_COLUMN, 0);
$countResult = $countStatement->fetchAll(\PDO::FETCH_COLUMN, 0);
$numberOfRows = $countResult ? current($countResult) : 0;
$countSqlTranslator->setNumberOfRows($numberOfRows);
return $serviceNames;
}
/**
* @inheritDoc
*/
public function findUniqueServiceNamesByRequestParametersAndAccessGroupIds(
RequestParametersInterface $requestParameters,
array $accessGroupIds,
): array {
if ($accessGroupIds === []) {
return [];
}
[$bindValues, $bindQuery] = $this->createMultipleBindQuery($accessGroupIds, ':acl_group');
$selectSqlTranslator = $this->prepareSqlRequestParametersTranslator($requestParameters);
$countSqlTranslator = $this->prepareSqlRequestParametersTranslator($requestParameters);
$selectRequest = $this->findServiceNamesQuery($selectSqlTranslator, false, $accessGroupIds, $bindQuery);
$countRequest = $this->findServiceNamesQuery($countSqlTranslator, true, $accessGroupIds, $bindQuery);
$selectStatement = $this->db->prepare($this->translateDbName($selectRequest));
$selectSqlTranslator->bindSearchValues($selectStatement);
foreach ($bindValues as $token => $value) {
$selectStatement->bindValue($token, $value, \PDO::PARAM_INT);
}
$selectStatement->execute();
$countStatement = $this->db->prepare($this->translateDbName($countRequest));
$countSqlTranslator->bindSearchValues($countStatement);
foreach ($bindValues as $token => $value) {
$countStatement->bindValue($token, $value, \PDO::PARAM_INT);
}
$countStatement->execute();
$serviceNames = $selectStatement->fetchAll(\PDO::FETCH_COLUMN, 0);
$countResult = $countStatement->fetchAll(\PDO::FETCH_COLUMN, 0);
$numberOfRows = $countResult ? current($countResult) : 0;
$countSqlTranslator->setNumberOfRows($numberOfRows);
return $serviceNames;
}
/**
* @inheritDoc
*/
public function exists(int $serviceId, int $hostId): bool
{
$query = <<<'SQL'
SELECT 1
FROM `:dbstg`.services
WHERE service_id = :serviceId
AND host_id = :hostId
SQL;
try {
$raw = $this->db->fetchOne(
$this->translateDbName($query),
QueryParameters::create([
QueryParameter::int('serviceId', $serviceId),
QueryParameter::int('hostId', $hostId),
])
);
return (bool) $raw;
} catch (ValueObjectException|CollectionException|ConnectionException $e) {
throw new RepositoryException(
sprintf(
'Error checking existence of service %d on host %d',
$serviceId,
$hostId
),
[
'serviceId' => $serviceId,
'hostId' => $hostId,
],
$e
);
}
}
/**
* @inheritDoc
*/
public function existsByDescription(int $metaServiceId): array|false
{
$query = <<<'SQL'
SELECT service_id, host_id
FROM `:dbstg`.services s
WHERE s.description = :metaId
SQL;
try {
return $this->db->fetchAssociative(
$this->translateDbName($query),
QueryParameters::create([
QueryParameter::string('metaId', "meta_{$metaServiceId}"),
])
);
} catch (ValueObjectException|CollectionException|ConnectionException $e) {
throw new RepositoryException(
sprintf(
'Error checking existence of meta service as service with description: meta_%d',
$metaServiceId
),
[
'metaServiceId' => $metaServiceId,
],
$e
);
}
}
/**
* @param SqlRequestParametersTranslator $sqlTranslator
* @param bool $calculateNumberOfRows
* @param int[] $accessGroupIds
* @param string $aclBindQuery
*
* @return string
*/
private function findServiceNamesQuery(
SqlRequestParametersTranslator $sqlTranslator,
bool $calculateNumberOfRows,
array $accessGroupIds = [],
string $aclBindQuery = '',
): string {
$search = $sqlTranslator->translateSearchParameterToSql();
$typeSearch = $search !== null ? ' AND services.type = 0 ' : ' WHERE services.type = 0 ';
$sort = $sqlTranslator->translateSortParameterToSql() ?? ' ORDER BY services.name ASC';
$aclJoin = '';
$aclSearch = '';
if ($calculateNumberOfRows) {
$select = ' COUNT(*) OVER(), services.name AS `name`';
$limit = '';
} else {
$select = ' services.name AS `name`';
$limit = $sqlTranslator->translatePaginationToSql();
}
if ($accessGroupIds !== []) {
$aclJoin = <<<'SQL'
INNER JOIN `:dbstg`.centreon_acl acls
ON acls.host_id = services.parent_id
AND acls.service_id = services.id
SQL;
$aclSearch = <<<SQL
AND acls.group_id IN ({$aclBindQuery})
SQL;
}
return <<<SQL
SELECT {$select}
FROM `:dbstg`.resources AS services
INNER JOIN `:dbstg`.resources AS hosts
ON hosts.id = services.parent_id
LEFT JOIN `:dbstg`.resources_tags AS rtags_host_groups
ON hosts.resource_id = rtags_host_groups.resource_id
LEFT JOIN `:dbstg`.tags host_groups
ON rtags_host_groups.tag_id = host_groups.tag_id
AND host_groups.type = 1
LEFT JOIN `:dbstg`.resources_tags AS rtags_host_categories
ON hosts.resource_id = rtags_host_categories.resource_id
LEFT JOIN `:dbstg`.tags host_categories
ON rtags_host_categories.tag_id = host_categories.tag_id
AND host_categories.type = 3
LEFT JOIN `:dbstg`.resources_tags AS rtags_service_groups
ON services.resource_id = rtags_service_groups.resource_id
LEFT JOIN `:dbstg`.tags service_groups
ON rtags_service_groups.tag_id = service_groups.tag_id
AND service_groups.type = 0
LEFT JOIN `:dbstg`.resources_tags AS rtags_service_categories
ON services.resource_id = rtags_service_categories.resource_id
LEFT JOIN `:dbstg`.tags service_categories
ON rtags_service_categories.tag_id = service_categories.tag_id
AND service_categories.type = 2
{$aclJoin}
{$search}
{$typeSearch}
{$aclSearch}
AND services.enabled = 1
GROUP BY services.name
{$sort}
{$limit}
SQL;
}
/**
* @return string
*/
private function returnBaseQuery(): string
{
// tags 0=servicegroup, 1=hostgroup, 2=servicecategory, 3=hostcategory
return <<<'SQL_WRAP'
SELECT SQL_CALC_FOUND_ROWS
services.id AS `id`,
services.name AS `name`,
services.status AS `status`
FROM `:dbstg`.resources AS services
INNER JOIN `:dbstg`.resources AS hosts
ON hosts.id = services.parent_id
LEFT JOIN `:dbstg`.resources_tags AS rtags_host_groups
ON hosts.resource_id = rtags_host_groups.resource_id
LEFT JOIN `:dbstg`.tags host_groups
ON rtags_host_groups.tag_id = host_groups.tag_id
AND host_groups.type = 1
LEFT JOIN `:dbstg`.resources_tags AS rtags_host_categories
ON hosts.resource_id = rtags_host_categories.resource_id
LEFT JOIN `:dbstg`.tags host_categories
ON rtags_host_categories.tag_id = host_categories.tag_id
AND host_categories.type = 3
LEFT JOIN `:dbstg`.resources_tags AS rtags_service_groups
ON services.resource_id = rtags_service_groups.resource_id
LEFT JOIN `:dbstg`.tags service_groups
ON rtags_service_groups.tag_id = service_groups.tag_id
AND service_groups.type = 0
LEFT JOIN `:dbstg`.resources_tags AS rtags_service_categories
ON services.resource_id = rtags_service_categories.resource_id
LEFT JOIN `:dbstg`.tags service_categories
ON rtags_service_categories.tag_id = service_categories.tag_id
AND service_categories.type = 2
SQL_WRAP;
}
/**
* @param RequestParametersInterface $requestParameters
*
* @return SqlRequestParametersTranslator
*/
private function prepareSqlRequestParametersTranslator(
RequestParametersInterface $requestParameters,
): SqlRequestParametersTranslator {
$sqlTranslator = new SqlRequestParametersTranslator($requestParameters);
$sqlTranslator->setConcordanceArray([
'name' => 'services.name',
'status' => 'services.status',
'host.name' => 'hosts.name',
'host.id' => 'hosts.id',
'host_category.name' => 'host_categories.name',
'host_category.id' => 'host_categories.id',
'host_group.name' => 'host_groups.name',
'host_group.id' => 'host_groups.id',
'service_group.name' => 'service_groups.name',
'service_group.id' => 'service_groups.id',
'service_category.name' => 'service_categories.name',
'service_category.id' => 'service_categories.id',
]);
$sqlTranslator->addNormalizer(
'status',
new class () implements NormalizerInterface {
/**
* @inheritDoc
*/
public function normalize($valueToNormalize)
{
switch (mb_strtoupper((string) $valueToNormalize)) {
case 'OK':
$code = ServiceStatusesCount::STATUS_OK;
break;
case 'WARNING':
$code = ServiceStatusesCount::STATUS_WARNING;
break;
case 'CRITICAL':
$code = ServiceStatusesCount::STATUS_CRITICAL;
break;
case 'UNKNOWN':
$code = ServiceStatusesCount::STATUS_UNKNOWN;
break;
case 'PENDING':
$code = ServiceStatusesCount::STATUS_PENDING;
break;
default:
throw new RequestParametersTranslatorException('Status provided not handled');
}
return $code;
}
}
);
return $sqlTranslator;
}
/**
* @param _ServiceStatuses $record
*
* @return ServiceStatusesCount
*/
private function createServiceStatusesCountFromRecord(array $record): ServiceStatusesCount
{
return new ServiceStatusesCount(
$this->countStatuses($record, ServiceStatusesCount::STATUS_OK),
$this->countStatuses($record, ServiceStatusesCount::STATUS_WARNING),
$this->countStatuses($record, ServiceStatusesCount::STATUS_UNKNOWN),
$this->countStatuses($record, ServiceStatusesCount::STATUS_CRITICAL),
$this->countStatuses($record, ServiceStatusesCount::STATUS_PENDING)
);
}
/**
* @param _ServiceStatuses $record
* @param int $statusCode
*
* @return int
*/
private function countStatuses(array $record, int $statusCode): int
{
return count(
array_filter(
$record,
(fn (array $service) => $service['status'] === $statusCode)
)
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Infrastructure/Repository/DbWriteServiceRepository.php | centreon/src/Core/Service/Infrastructure/Repository/DbWriteServiceRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Infrastructure\Repository;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Common\Infrastructure\RequestParameters\Normalizer\BoolToEnumNormalizer;
use Core\Service\Application\Repository\WriteServiceRepositoryInterface;
use Core\Service\Domain\Model\NewService;
use Core\Service\Domain\Model\Service;
use Core\Service\Infrastructure\Model\NotificationTypeConverter;
use Core\Service\Infrastructure\Model\YesNoDefaultConverter;
class DbWriteServiceRepository extends AbstractRepositoryRDB implements WriteServiceRepositoryInterface
{
use LoggerTrait;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function delete(int $serviceId): void
{
$request = $this->translateDbName(
<<<'SQL'
DELETE FROM `:db`.service
WHERE service_id = :id
AND service_register = '1'
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':id', $serviceId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @inheritDoc
*/
public function deleteByIds(int ...$serviceIds): void
{
$bindValues = [];
foreach ($serviceIds as $index => $serviceId) {
$bindValues[':service_id' . $index] = [\PDO::PARAM_INT => $serviceId];
}
$subRequest = implode(',', array_keys($bindValues));
$request = $this->translateDbName(
<<<SQL
DELETE FROM `:db`.service
WHERE service_id IN ({$subRequest})
AND service_register = '1'
SQL
);
$statement = $this->db->prepare($request);
foreach ($bindValues as $key => $data) {
$type = key($data);
$value = $data[$type];
$statement->bindValue($key, $value, $type);
}
$statement->execute();
}
/**
* @inheritDoc
*/
public function add(NewService $newService): int
{
$request = $this->translateDbName(
<<<'SQL'
INSERT INTO `:db`.service
(
cg_additive_inheritance,
contact_additive_inheritance,
command_command_id,
command_command_id_arg,
command_command_id2,
command_command_id_arg2,
service_acknowledgement_timeout,
service_activate,
service_event_handler_enabled,
service_active_checks_enabled,
service_flap_detection_enabled,
service_check_freshness,
service_notifications_enabled,
service_passive_checks_enabled,
service_is_volatile,
service_low_flap_threshold,
service_high_flap_threshold,
service_max_check_attempts,
service_description,
service_comment,
service_freshness_threshold,
service_normal_check_interval,
service_notification_interval,
service_notification_options,
service_recovery_notification_delay,
service_retry_check_interval,
service_template_model_stm_id,
service_first_notification_delay,
timeperiod_tp_id,
timeperiod_tp_id2,
geo_coords,
service_register
) VALUES (
:contact_group_additive_inheritance,
:contact_additive_inheritance,
:command_id,
:command_arguments,
:event_handler_id,
:event_handler_arguments,
:acknowledgement_timeout,
:is_activated,
:event_handler_enabled,
:active_checks_enabled,
:flap_detection_enabled,
:check_freshness,
:notifications_enabled,
:passive_checks_enabled,
:volatility,
:low_flap_threshold,
:high_flap_threshold,
:max_check_attempts,
:description,
:comment,
:freshness_threshold,
:normal_check_interval,
:notification_interval,
:notification_options,
:recovery_notification_delay,
:retry_check_interval,
:service_template_id,
:first_notification_delay,
:check_time_period_id,
:notification_time_period_id,
:geo_coords,
"1"
)
SQL
);
$statement = $this->db->prepare($request);
$this->bindServiceBasicValues($statement, $newService);
$isAlreadyInTransaction = $this->db->inTransaction();
if (! $isAlreadyInTransaction) {
$this->db->beginTransaction();
}
try {
$statement->execute();
$newServiceId = (int) $this->db->lastInsertId();
$this->addExtensionService($newServiceId, $newService);
$this->linkSeverity($newServiceId, $newService->getSeverityId());
$this->linkHost($newServiceId, $newService->getHostId());
if (! $isAlreadyInTransaction) {
$this->db->commit();
}
return $newServiceId;
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
if (! $isAlreadyInTransaction) {
$this->db->rollBack();
}
throw $ex;
}
}
/**
* @inheritDoc
*/
public function update(Service $service): void
{
$alreadyInTransaction = $this->db->inTransaction();
if (! $alreadyInTransaction) {
$this->db->beginTransaction();
}
try {
$this->updateBasicInformations($service);
$this->updateExtensionService($service);
$this->updateSeverity($service);
$this->updateHost($service);
if (! $alreadyInTransaction) {
$this->db->commit();
}
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
if (! $alreadyInTransaction) {
$this->db->rollBack();
}
throw $ex;
}
}
private function updateBasicInformations(Service $service): void
{
$request = $this->translateDbName(
<<<'SQL'
UPDATE `:db`.service
SET
cg_additive_inheritance = :contact_group_additive_inheritance,
contact_additive_inheritance = :contact_additive_inheritance,
command_command_id = :command_id,
command_command_id_arg = :command_arguments,
command_command_id2 = :event_handler_id,
command_command_id_arg2 = :event_handler_arguments,
service_acknowledgement_timeout = :acknowledgement_timeout,
service_activate = :is_activated,
service_event_handler_enabled = :event_handler_enabled,
service_active_checks_enabled = :active_checks_enabled,
service_flap_detection_enabled = :flap_detection_enabled,
service_check_freshness = :check_freshness,
service_notifications_enabled = :notifications_enabled,
service_passive_checks_enabled = :passive_checks_enabled,
service_is_volatile = :volatility,
service_low_flap_threshold = :low_flap_threshold,
service_high_flap_threshold = :high_flap_threshold,
service_max_check_attempts = :max_check_attempts,
service_description = :description,
service_comment = :comment,
service_freshness_threshold = :freshness_threshold,
service_normal_check_interval = :normal_check_interval,
service_notification_interval = :notification_interval,
service_notification_options = :notification_options,
service_recovery_notification_delay = :recovery_notification_delay,
service_retry_check_interval = :retry_check_interval,
service_template_model_stm_id = :service_template_id,
service_first_notification_delay = :first_notification_delay,
timeperiod_tp_id = :check_time_period_id,
timeperiod_tp_id2 = :notification_time_period_id,
geo_coords = :geo_coords
WHERE service_id = :service_id
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':service_id', $service->getId(), \PDO::PARAM_INT);
$this->bindServiceBasicValues($statement, $service);
$statement->execute();
}
/**
* @param int $serviceId
* @param NewService $service
*
* @throws \Throwable
*/
private function addExtensionService(int $serviceId, NewService $service): void
{
$request = $this->translateDbName(
<<<'SQL'
INSERT INTO `:db`.extended_service_information
(
service_service_id,
esi_action_url,
esi_icon_image,
esi_icon_image_alt,
esi_notes,
esi_notes_url,
graph_id
) VALUES (
:service_id,
:action_url,
:icon_id,
:icon_alternative_text,
:notes,
:notes_url,
:graph_template_id
)
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':service_id', $serviceId, \PDO::PARAM_INT);
$statement->bindValue(':action_url', $service->getActionUrl());
$statement->bindValue(':icon_id', $service->getIconId(), \PDO::PARAM_INT);
$statement->bindValue(':icon_alternative_text', $service->getIconAlternativeText());
$statement->bindValue(':notes', $service->getNote());
$statement->bindValue(':notes_url', $service->getNoteUrl());
$statement->bindValue(':graph_template_id', $service->getGraphTemplateId(), \PDO::PARAM_INT);
$statement->execute();
}
/**
* @param Service $service
*
* @throws \Throwable
*/
private function updateExtensionService(Service $service): void
{
$request = $this->translateDbName(
<<<'SQL'
UPDATE `:db`.extended_service_information
SET
esi_action_url = :action_url,
esi_icon_image = :icon_id,
esi_icon_image_alt = :icon_alternative_text,
esi_notes = :notes,
esi_notes_url = :notes_url,
graph_id = :graph_template_id
WHERE service_service_id = :service_id
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':service_id', $service->getId(), \PDO::PARAM_INT);
$statement->bindValue(':action_url', $service->getActionUrl());
$statement->bindValue(':icon_id', $service->getIconId(), \PDO::PARAM_INT);
$statement->bindValue(':icon_alternative_text', $service->getIconAlternativeText());
$statement->bindValue(':notes', $service->getNote());
$statement->bindValue(':notes_url', $service->getNoteUrl());
$statement->bindValue(':graph_template_id', $service->getGraphTemplateId(), \PDO::PARAM_INT);
$statement->execute();
}
/**
* @param Service $service
*
* @throws \Throwable
*/
private function updateHost(Service $service): void
{
$this->deleteLinkToHost($service->getId());
$this->linkHost($service->getId(), $service->getHostId());
}
/**
* Link host to service template.
*
* @param int $serviceId
* @param int $hostId
*
* @throws \PDOException
*/
private function linkHost(int $serviceId, int $hostId): void
{
$request = $this->translateDbName(
<<<'SQL'
INSERT INTO `:db`.host_service_relation
(
host_host_id,
service_service_id
) VALUES
(
:host_id,
:service_id
)
SQL
);
$statement = $this->db->prepare($request);
$statement->bindParam(':service_id', $serviceId, \PDO::PARAM_INT);
$statement->bindParam(':host_id', $hostId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @param int $serviceId
*
* @throws \PDOException
*/
private function deleteLinkToHost(int $serviceId): void
{
$request = $this->translateDbName(
<<<'SQL'
DELETE FROM `:db`.host_service_relation
WHERE service_service_id = :service_id
SQL
);
$statement = $this->db->prepare($request);
$statement->bindParam(':service_id', $serviceId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @param Service $service
*
* @throws \Throwable
*/
private function updateSeverity(Service $service): void
{
$this->deleteLinkToSeverity($service->getId());
$this->linkSeverity($service->getId(), $service->getSeverityId());
}
/**
* @param int $serviceId
* @param int|null $severityId
*
* @throws \Throwable
*/
private function linkSeverity(int $serviceId, ?int $severityId): void
{
if ($severityId === null) {
return;
}
$request = $this->translateDbName(
<<<'SQL'
INSERT INTO `:db`.service_categories_relation
(
service_service_id,
sc_id
) VALUES
(
:service_id,
:severity_id
)
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':service_id', $serviceId, \PDO::PARAM_INT);
$statement->bindValue(':severity_id', $severityId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @param int $serviceId
*
* @throws \Throwable
*/
private function deleteLinkToSeverity(int $serviceId): void
{
$request = $this->translateDbName(
<<<'SQL'
DELETE screl
FROM `:db`.service_categories_relation screl
JOIN service_categories sc
ON screl.sc_id = sc.sc_id
AND sc.level IS NOT NULL
WHERE screl.service_service_id = :serviceId
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':serviceId', $serviceId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @param list<string> $arguments
*
* @return string
*/
private function serializeArguments(array $arguments): string
{
$serializedArguments = '';
foreach ($arguments as $argument) {
$serializedArguments .= '!' . str_replace(["\n", "\t", "\r"], ['#BR#', '#T#', '#R#'], $argument);
}
return $serializedArguments;
}
/**
* @param \PDOStatement $statement
* @param NewService|Service $service
*
* @throws \Throwable
*/
private function bindServiceBasicValues(\PDOStatement $statement, NewService|Service $service): void
{
$statement->bindValue(
':contact_group_additive_inheritance',
$service->isContactGroupAdditiveInheritance(),
\PDO::PARAM_INT
);
$statement->bindValue(
':contact_additive_inheritance',
$service->isContactAdditiveInheritance(),
\PDO::PARAM_INT
);
$statement->bindValue(':command_id', $service->getCommandId(), \PDO::PARAM_INT);
$statement->bindValue(
':command_arguments',
$this->serializeArguments($service->getCommandArguments())
);
$statement->bindValue(':event_handler_id', $service->getEventHandlerId(), \PDO::PARAM_INT);
$statement->bindValue(
':event_handler_arguments',
$this->serializeArguments($service->getEventHandlerArguments())
);
$statement->bindValue(
':acknowledgement_timeout',
$service->getAcknowledgementTimeout(),
\PDO::PARAM_INT
);
$statement->bindValue(
':is_activated',
(new BoolToEnumNormalizer())->normalize($service->isActivated()),
\PDO::PARAM_STR
);
$statement->bindValue(
':active_checks_enabled',
(string) YesNoDefaultConverter::toInt($service->getActiveChecks())
);
$statement->bindValue(
':event_handler_enabled',
(string) YesNoDefaultConverter::toInt($service->getEventHandlerEnabled())
);
$statement->bindValue(
':flap_detection_enabled',
(string) YesNoDefaultConverter::toInt($service->getFlapDetectionEnabled())
);
$statement->bindValue(
':check_freshness',
(string) YesNoDefaultConverter::toInt($service->getCheckFreshness())
);
$statement->bindValue(
':notifications_enabled',
(string) YesNoDefaultConverter::toInt($service->getNotificationsEnabled())
);
$statement->bindValue(
':passive_checks_enabled',
(string) YesNoDefaultConverter::toInt($service->getPassiveCheck())
);
$statement->bindValue(
':volatility',
(string) YesNoDefaultConverter::toInt($service->getVolatility())
);
$statement->bindValue(
':low_flap_threshold',
$service->getLowFlapThreshold(),
\PDO::PARAM_INT
);
$statement->bindValue(
':high_flap_threshold',
$service->getHighFlapThreshold(),
\PDO::PARAM_INT
);
$statement->bindValue(
':max_check_attempts',
$service->getMaxCheckAttempts(),
\PDO::PARAM_INT
);
$statement->bindValue(
':description',
$service->getName()
);
$statement->bindValue(
':comment',
$service->getComment()
);
$statement->bindValue(
':freshness_threshold',
$service->getFreshnessThreshold(),
\PDO::PARAM_INT
);
$statement->bindValue(
':normal_check_interval',
$service->getNormalCheckInterval(),
\PDO::PARAM_INT
);
$statement->bindValue(
':notification_interval',
$service->getNotificationInterval(),
\PDO::PARAM_INT
);
$statement->bindValue(
':notification_options',
NotificationTypeConverter::toString($service->getNotificationTypes())
);
$statement->bindValue(
':recovery_notification_delay',
$service->getRecoveryNotificationDelay(),
\PDO::PARAM_INT
);
$statement->bindValue(
':retry_check_interval',
$service->getRetryCheckInterval(),
\PDO::PARAM_INT
);
$statement->bindValue(
':service_template_id',
$service->getServiceTemplateParentId(),
\PDO::PARAM_INT
);
$statement->bindValue(
':first_notification_delay',
$service->getFirstNotificationDelay(),
\PDO::PARAM_INT
);
$statement->bindValue(
':check_time_period_id',
$service->getCheckTimePeriodId(),
\PDO::PARAM_INT
);
$statement->bindValue(
':notification_time_period_id',
$service->getNotificationTimePeriodId(),
\PDO::PARAM_INT
);
$statement->bindValue(
':geo_coords',
$service->getGeoCoords(),
\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/Service/Infrastructure/Repository/DbWriteServiceActionLogRepository.php | centreon/src/Core/Service/Infrastructure/Repository/DbWriteServiceActionLogRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\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\Domain\Common\GeoCoords;
use Core\Service\Application\Repository\ReadServiceRepositoryInterface;
use Core\Service\Application\Repository\WriteServiceRepositoryInterface;
use Core\Service\Domain\Model\NewService;
use Core\Service\Domain\Model\NotificationType;
use Core\Service\Domain\Model\Service;
use Core\Service\Infrastructure\Model\NotificationTypeConverter;
class DbWriteServiceActionLogRepository extends AbstractRepositoryRDB implements WriteServiceRepositoryInterface
{
use LoggerTrait;
/**
* @param WriteServiceRepositoryInterface $writeServiceRepository
* @param ContactInterface $contact
* @param ReadServiceRepositoryInterface $readServiceRepository
* @param WriteActionLogRepositoryInterface $writeActionLogRepository
* @param DatabaseConnection $db
*/
public function __construct(
private readonly WriteServiceRepositoryInterface $writeServiceRepository,
private readonly ContactInterface $contact,
private readonly ReadServiceRepositoryInterface $readServiceRepository,
private readonly WriteActionLogRepositoryInterface $writeActionLogRepository,
DatabaseConnection $db,
) {
$this->db = $db;
}
/**
* @inheritDoc
*/
public function delete(int $serviceId): void
{
try {
$service = $this->readServiceRepository->findById($serviceId);
if ($service === null) {
throw new RepositoryException(sprintf('Cannot find service to delete (ID: %d).', $serviceId));
}
$this->writeServiceRepository->delete($serviceId);
$actionLog = new ActionLog(
ActionLog::OBJECT_TYPE_SERVICE,
$serviceId,
$service->getName(),
ActionLog::ACTION_TYPE_DELETE,
$this->contact->getId()
);
$this->writeActionLogRepository->addAction($actionLog);
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['service_id' => $serviceId, 'trace' => $ex->getTraceAsString()]);
throw $ex;
}
}
/**
* @inheritDoc
*/
public function deleteByIds(int ...$serviceIds): void
{
$failedDeletions = [];
foreach ($serviceIds as $serviceId) {
try {
if (! $this->readServiceRepository->exists($serviceId)) {
throw new RepositoryException(sprintf('Cannot find service to delete (ID: %d).', $serviceId));
}
$serviceName = $this->readServiceRepository->findNameById($serviceId)
?? throw new RepositoryException(sprintf('Cannot find service name (ID: %d).', $serviceId));
$this->writeServiceRepository->delete($serviceId);
$actionLog = new ActionLog(
ActionLog::OBJECT_TYPE_SERVICE,
$serviceId,
$serviceName,
ActionLog::ACTION_TYPE_DELETE,
$this->contact->getId()
);
$this->writeActionLogRepository->addAction($actionLog);
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['service_id' => $serviceId, 'trace' => $ex->getTraceAsString()]);
$failedDeletions[] = $serviceId;
}
}
if ($failedDeletions !== []) {
throw new RepositoryException('Failed to delete services with IDs: ' . implode(',', $failedDeletions));
}
}
/**
* @inheritDoc
*/
public function add(NewService $newService): int
{
try {
$serviceId = $this->writeServiceRepository->add($newService);
if ($serviceId === 0) {
throw new RepositoryException('Service ID cannot be 0');
}
$actionLog = new ActionLog(
ActionLog::OBJECT_TYPE_SERVICE,
$serviceId,
$newService->getName(),
ActionLog::ACTION_TYPE_ADD,
$this->contact->getId()
);
$actionLogId = $this->writeActionLogRepository->addAction($actionLog);
$actionLog->setId($actionLogId);
$details = $this->getServicePropertiesAsArray($newService);
$this->writeActionLogRepository->addActionDetails($actionLog, $details);
return $serviceId;
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['service' => $newService, 'trace' => $ex->getTraceAsString()]);
throw $ex;
}
}
/**
* @inheritDoc
*/
public function update(Service $service): void
{
try {
$currentService = $this->readServiceRepository->findById($service->getId());
if ($currentService === null) {
throw new RepositoryException(sprintf('Cannot find service to update (ID: %d).', $service->getId()));
}
$currentServiceDetails = $this->getServicePropertiesAsArray($currentService);
$updatedServiceDetails = $this->getServicePropertiesAsArray($service);
$diff = array_diff_assoc($updatedServiceDetails, $currentServiceDetails);
$this->writeServiceRepository->update($service);
$actionsToLog = [];
if (array_key_exists('isActivated', $diff)) {
$actionType = (bool) $diff['isActivated']
? ActionLog::ACTION_TYPE_ENABLE
: ActionLog::ACTION_TYPE_DISABLE;
$actionsToLog[] = new ActionLog(
ActionLog::OBJECT_TYPE_SERVICE,
$service->getId(),
$service->getName(),
$actionType,
$this->contact->getId()
);
unset($diff['isActivated']);
}
if ($diff !== []) {
$actionsToLog[] = new ActionLog(
ActionLog::OBJECT_TYPE_SERVICE,
$service->getId(),
$service->getName(),
ActionLog::ACTION_TYPE_CHANGE,
$this->contact->getId()
);
}
foreach ($actionsToLog as $actionLog) {
$actionLogId = $this->writeActionLogRepository->addAction($actionLog);
if ($actionLogId === 0) {
throw new RepositoryException('Action log ID cannot be 0');
}
$actionLog->setId($actionLogId);
if ($actionLog->getActionType() === ActionLog::ACTION_TYPE_CHANGE) {
$this->writeActionLogRepository->addActionDetails($actionLog, $diff);
}
}
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['service' => $service, 'trace' => $ex->getTraceAsString()]);
throw $ex;
}
}
/**
* @param NewService|Service $service
*
* @return array<string,int|bool|string>
*/
private function getServicePropertiesAsArray(NewService|Service $service): array
{
$servicePropertiesArray = [];
$serviceReflection = new \ReflectionClass($service);
foreach ($serviceReflection->getProperties() as $property) {
$value = $property->getValue($service);
// Do not capture class name of function parameter in action logs
if ($property->getName() === 'className') {
continue;
}
if ($value === null) {
$value = '';
}
if ($value instanceof YesNoDefault) {
$value = YesNoDefaultConverter::toString($value);
}
if ($value instanceof GeoCoords) {
$value = $value->__toString();
}
if (is_array($value)) {
if ($value === []) {
$value = '';
} elseif (is_string($value[0])) {
$value = '!' . implode('!', str_replace(["\n", "\t", "\r"], ['#BR#', '#T#', '#R#'], $value));
} elseif ($value[0] instanceof NotificationType) {
$value = NotificationTypeConverter::toString($value);
}
}
$servicePropertiesArray[$property->getName()] = $value;
}
return $servicePropertiesArray;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Infrastructure/Repository/TinyServiceFactory.php | centreon/src/Core/Service/Infrastructure/Repository/TinyServiceFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Infrastructure\Repository;
use Core\Service\Domain\Model\TinyService;
class TinyServiceFactory
{
/**
* @param array{service_id: int, service_description: string, host_name: string} $data
*
* @return TinyService
*/
public static function createFromDb(array $data): TinyService
{
return new TinyService((int) $data['service_id'], $data['service_description'], $data['host_name']);
}
/**
* @param array{id: int, name: string, host_name: string} $data
*
* @return TinyService
*/
public static function createFromApi(array $data): TinyService
{
return new TinyService((int) $data['id'], $data['name'], $data['host_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/Service/Infrastructure/Repository/DbWriteRealTimeServiceRepository.php | centreon/src/Core/Service/Infrastructure/Repository/DbWriteRealTimeServiceRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Infrastructure\Repository;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Core\Service\Application\Repository\WriteRealTimeServiceRepositoryInterface;
class DbWriteRealTimeServiceRepository extends AbstractRepositoryRDB implements WriteRealTimeServiceRepositoryInterface
{
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function addServiceToResourceAcls(int $hostId, int $serviceId, array $accessGroups): void
{
$accessGroupIds = array_map(
fn (AccessGroup $accessGroup) => $accessGroup->getId(),
$accessGroups
);
$request = <<<'SQL'
INSERT INTO `:dbstg`.`centreon_acl`(`group_id`, `host_id`, `service_id`)
VALUES
SQL;
foreach ($accessGroupIds as $accessGroupId) {
$request .= <<<SQL
(:group_{$accessGroupId}, :host_id, :service_id),
SQL;
}
$statement = $this->db->prepare($this->translateDbName(trim($request, ',')));
foreach ($accessGroupIds as $accessGroupId) {
$statement->bindValue(':group_' . $accessGroupId, $accessGroupId, \PDO::PARAM_INT);
}
$statement->bindValue(':host_id', $hostId, \PDO::PARAM_INT);
$statement->bindValue(':service_id', $serviceId, \PDO::PARAM_INT);
$statement->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Infrastructure/Repository/DbReadServiceRepository.php | centreon/src/Core/Service/Infrastructure/Repository/DbReadServiceRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Infrastructure\Repository;
use Assert\AssertionFailedException;
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\Domain\SimpleEntity;
use Core\Common\Domain\TrimmedString;
use Core\Common\Domain\YesNoDefault;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait;
use Core\Common\Infrastructure\RequestParameters\Normalizer\BoolToEnumNormalizer;
use Core\Domain\Common\GeoCoords;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Core\Service\Application\Repository\ReadServiceRepositoryInterface;
use Core\Service\Domain\Model\NotificationType;
use Core\Service\Domain\Model\Service;
use Core\Service\Domain\Model\ServiceInheritance;
use Core\Service\Domain\Model\ServiceLight;
use Core\Service\Domain\Model\ServiceNamesByHost;
use Core\Service\Domain\Model\ServiceRelation;
use Core\ServiceCategory\Infrastructure\Repository\ServiceCategoryRepositoryTrait;
use Core\ServiceGroup\Domain\Model\ServiceGroupRelation;
use Utility\SqlConcatenator;
/**
* @phpstan-type _Service array{
* service_id: int,
* cg_additive_inheritance: int|null,
* contact_additive_inheritance: int|null,
* command_command_id: int|null,
* command_command_id2: int|null,
* command_command_id_arg: string|null,
* command_command_id_arg2: string|null,
* service_acknowledgement_timeout: int|null,
* service_activate: string,
* service_active_checks_enabled: string,
* service_event_handler_enabled: string,
* service_flap_detection_enabled: string,
* service_check_freshness: string,
* service_locked: int,
* service_notifications_enabled: string|null,
* service_passive_checks_enabled: string|null,
* service_is_volatile: string,
* service_low_flap_threshold: int|null,
* service_high_flap_threshold: int|null,
* service_max_check_attempts: int|null,
* service_description: string,
* service_comment: string,
* service_alias: string,
* service_freshness_threshold: int|null,
* service_normal_check_interval: int|null,
* service_notification_interval: int|null,
* service_notification_options: string|null,
* service_notifications_enabled: string,
* service_passive_checks_enabled: string,
* service_recovery_notification_delay: int|null,
* service_retry_check_interval: int|null,
* service_template_model_stm_id: int|null,
* service_first_notification_delay: int|null,
* timeperiod_tp_id: int|null,
* timeperiod_tp_id2: int|null,
* esi_action_url: string|null,
* esi_icon_image: int|null,
* esi_icon_image_alt: string|null,
* esi_notes: string|null,
* esi_notes_url: string|null,
* graph_id: int|null,
* severity_id: int|null,
* host_ids: string|null,
* service_categories_ids: string|null,
* geo_coords: string|null
* }
*/
class DbReadServiceRepository extends AbstractRepositoryRDB implements ReadServiceRepositoryInterface
{
use LoggerTrait;
use ServiceCategoryRepositoryTrait;
use SqlMultipleBindTrait;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function exist(array $serviceIds): array
{
$this->debug('Check existence of services', ['service_ids' => $serviceIds]);
if ($serviceIds === []) {
return [];
}
$bindValues = [];
foreach ($serviceIds as $index => $serviceId) {
$bindValues[":service_{$index}"] = $serviceId;
}
$serviceIdsList = implode(', ', array_keys($bindValues));
$request = $this->translateDbName(
<<<SQL
SELECT
service_id
FROM `:db`.service
WHERE service_id IN ({$serviceIdsList})
AND service_register = '1'
SQL
);
$statement = $this->db->prepare($request);
foreach ($bindValues as $bindKey => $bindValue) {
$statement->bindValue($bindKey, $bindValue, \PDO::PARAM_INT);
}
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
return $statement->fetchAll(\PDO::FETCH_COLUMN);
}
/**
* @inheritDoc
*/
public function exists(int $serviceId): bool
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
SELECT 1
FROM `:db`.`service` s
WHERE s.`service_id` = :service_id
AND s.`service_register` = '1'
SQL
));
$statement->bindValue(':service_id', $serviceId, \PDO::PARAM_INT);
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* @inheritDoc
*/
public function existsByAccessGroups(int $serviceId, array $accessGroups): bool
{
if ($accessGroups === []) {
$this->debug('Access groups array empty');
return false;
}
$accessGroupIds = array_map(
static fn (AccessGroup $accessGroup) => $accessGroup->getId(),
$accessGroups
);
$bindValuesArray = [];
foreach ($accessGroupIds as $index => $id) {
$bindValuesArray[':access_group_id_' . $index] = $id;
}
$bindParamsAsString = implode(',', array_keys($bindValuesArray));
$subRequest = $this->generateServiceCategoryAclSubRequest($accessGroupIds);
$categoryAcls = empty($subRequest)
? ''
: <<<SQL
AND scr.sc_id IN ({$subRequest})
SQL;
$statement = $this->db->prepare($this->translateDbName(
<<<SQL
SELECT 1
FROM `:db`.`service` s
LEFT JOIN `:db`.`service_categories_relation` scr
ON scr.`service_service_id` = s.`service_id`
JOIN `:dbstg`.`centreon_acl` acl
WHERE acl.`group_id` IN ({$bindParamsAsString})
AND s.`service_id` = :service_id
AND s.`service_register` = '1'
{$categoryAcls}
SQL
));
$statement->bindValue(':service_id', $serviceId, \PDO::PARAM_INT);
foreach ($bindValuesArray as $bindParam => $bindValue) {
$statement->bindValue($bindParam, $bindValue, \PDO::PARAM_INT);
}
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* @inheritDoc
*/
public function findMonitoringServerId(int $serviceId): int
{
$request = $this->translateDbName(
<<<'SQL'
SELECT id
FROM `:db`.`nagios_server` ns
INNER JOIN `:db`.`ns_host_relation` nshr
ON nshr.nagios_server_id = ns.id
INNER JOIN `:db`.`host_service_relation` hsr
ON hsr.host_host_id = nshr.host_host_id
WHERE hsr.service_service_id = :service_id
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':service_id', $serviceId, \PDO::PARAM_INT);
$statement->execute();
return (int) $statement->fetchColumn();
}
/**
* @inheritDoc
*/
public function findServiceIdsLinkedToHostId(int $hostId): array
{
$request = $this->translateDbName(
<<<'SQL'
SELECT service.service_id
FROM `:db`.service
INNER JOIN `:db`.host_service_relation hsr
ON hsr.service_service_id = service.service_id
WHERE hsr.host_host_id = :host_id
AND service.service_register = '1'
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':host_id', $hostId, \PDO::PARAM_INT);
$statement->execute();
$serviceIds = [];
while (($serviceId = $statement->fetchColumn()) !== false) {
$serviceIds[] = (int) $serviceId;
}
return $serviceIds;
}
/**
* @inheritDoc
*/
public function findServiceIdsExclusivelyLinkedToHostId(int $hostId): array
{
$request = $this->translateDbName(
<<<'SQL'
SELECT hsr.service_service_id
FROM `:db`.host_service_relation hsr
INNER JOIN `:db`.host h
ON h.host_id = hsr.host_host_id
INNER JOIN (
SELECT service_service_id
FROM `:db`.host_service_relation
GROUP BY service_service_id
HAVING COUNT(*) = 1
) uniq
ON uniq.service_service_id = hsr.service_service_id
WHERE hsr.host_host_id = :host_id
AND h.host_register = '1'
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':host_id', $hostId, \PDO::PARAM_INT);
$statement->execute();
$serviceIds = [];
while (($serviceId = $statement->fetchColumn()) !== false) {
$serviceIds[] = (int) $serviceId;
}
return $serviceIds;
}
/**
* @inheritDoc
*/
public function findServiceNamesByHost(int $hostId): ?ServiceNamesByHost
{
$request = $this->translateDbName(
<<<'SQL'
SELECT service.service_description as service_name
FROM `:db`.service
INNER JOIN `:db`.host_service_relation hsr
ON hsr.service_service_id = service.service_id
WHERE hsr.host_host_id = :host_id
AND service.service_register = '1'
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':host_id', $hostId, \PDO::PARAM_INT);
$statement->execute();
/** @var string[] $results */
$results = $statement->fetchAll(\PDO::FETCH_COLUMN);
return new ServiceNamesByHost($hostId, $results);
}
/**
* @inheritDoc
*/
public function findById(int $serviceId): ?Service
{
$request = <<<'SQL'
SELECT service_id,
service.cg_additive_inheritance,
service.contact_additive_inheritance,
service.command_command_id,
service.command_command_id2,
service.command_command_id_arg,
service.command_command_id_arg2,
service.timeperiod_tp_id,
service.timeperiod_tp_id2,
service.geo_coords,
service_acknowledgement_timeout,
service_activate,
service_active_checks_enabled,
service_event_handler_enabled,
service_flap_detection_enabled,
service_check_freshness,
service_locked,
service_notifications_enabled,
service_passive_checks_enabled,
service_is_volatile,
service_low_flap_threshold,
service_high_flap_threshold,
service_max_check_attempts,
service_description,
service_comment,
service_alias,
service_freshness_threshold,
service_normal_check_interval,
service_notification_interval,
service_notification_options,
service_recovery_notification_delay,
service_retry_check_interval,
service_template_model_stm_id,
service_first_notification_delay,
esi.esi_action_url,
esi.esi_icon_image,
esi.esi_icon_image_alt,
esi.esi_notes,
esi.esi_notes_url,
esi.graph_id,
GROUP_CONCAT(DISTINCT severity.sc_id) as severity_id,
GROUP_CONCAT(DISTINCT hsr.host_host_id) AS host_ids
FROM `:db`.service
LEFT JOIN `:db`.extended_service_information esi
ON esi.service_service_id = service.service_id
LEFT JOIN `:db`.service_categories_relation scr
ON scr.service_service_id = service.service_id
LEFT JOIN `:db`.service_categories severity
ON severity.sc_id = scr.sc_id
AND severity.level IS NOT NULL
LEFT JOIN `:db`.host_service_relation hsr
ON hsr.service_service_id = service.service_id
LEFT JOIN `:db`.host
ON host.host_id = hsr.host_host_id
AND host.host_register = '1'
WHERE service.service_id = :id
AND service.service_register = '1'
GROUP BY
service.service_id,
esi.esi_action_url,
esi.esi_icon_image,
esi.esi_icon_image_alt,
esi.esi_notes,
esi.esi_notes_url,
esi.graph_id
SQL;
$statement = $this->db->prepare($this->translateDbName($request));
$statement->bindValue(':id', $serviceId, \PDO::PARAM_INT);
$statement->execute();
if ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
/** @var _Service $result */
return $this->createService($result);
}
return null;
}
/**
* @inheritDoc
*/
public function findByIds(int ...$serviceIds): array
{
[$bindValues, $serviceIdsQuery] = $this->createMultipleBindQuery($serviceIds, ':id_');
$request = <<<SQL
SELECT service_id,
service_description,
host.host_name
FROM `:db`.service
LEFT JOIN `:db`.host_service_relation hsr
ON hsr.service_service_id = service.service_id
LEFT JOIN `:db`.host
ON host.host_id = hsr.host_host_id
AND host.host_register = '1'
WHERE service.service_id IN ({$serviceIdsQuery})
AND service.service_register = '1'
ORDER BY service.service_id
SQL;
$statement = $this->db->prepare($this->translateDbName($request));
foreach ($bindValues as $bindKey => $serviceId) {
$statement->bindValue($bindKey, $serviceId, \PDO::PARAM_INT);
}
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
$services = [];
foreach ($statement as $result) {
/** @var array{service_id: int, service_description: string, host_name: string} $result */
$services[] = TinyServiceFactory::createFromDb($result);
}
return $services;
}
/**
* @inheritDoc
*/
public function findAll(): \Traversable&\Countable
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function findParents(int $serviceId): array
{
$request = $this->translateDbName(
<<<'SQL'
WITH RECURSIVE parents AS (
SELECT * FROM `:db`.`service`
WHERE `service_id` = :service_id
AND `service_register` = '1'
UNION
SELECT rel.* FROM `:db`.`service` AS rel, parents AS p
WHERE rel.`service_id` = p.`service_template_model_stm_id`
)
SELECT `service_id` AS child_id, `service_template_model_stm_id` AS parent_id
FROM parents
WHERE `service_template_model_stm_id` IS NOT NULL
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':service_id', $serviceId, \PDO::PARAM_INT);
$statement->execute();
$serviceTemplateInheritances = [];
while ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
/** @var array{child_id: int, parent_id: int} $result */
$serviceTemplateInheritances[] = new ServiceInheritance(
(int) $result['parent_id'],
(int) $result['child_id']
);
}
return $serviceTemplateInheritances;
}
/**
* @inheritDoc
*/
public function findByRequestParameter(RequestParametersInterface $requestParameters): array
{
$concatenator = $this->findServicesRequest();
$concatenator->defineSelect(
<<<'SQL'
SELECT service.service_id,
service.service_description,
service.timeperiod_tp_id as check_timeperiod_id,
checktp.tp_name as check_timeperiod_name,
service.timeperiod_tp_id2 as notification_timeperiod_id,
notificationtp.tp_name as notification_timeperiod_name,
service.service_activate,
service.service_normal_check_interval,
service.service_retry_check_interval,
service.service_template_model_stm_id as service_template_id,
serviceTemplate.service_description as service_template_name,
GROUP_CONCAT(DISTINCT severity.sc_id) as severity_id,
GROUP_CONCAT(DISTINCT severity.sc_name) as severity_name,
GROUP_CONCAT(DISTINCT category.sc_id) as category_ids,
GROUP_CONCAT(DISTINCT hsr.host_host_id) AS host_ids,
GROUP_CONCAT(DISTINCT CONCAT(sgr.servicegroup_sg_id, '-', sgr.host_host_id)) as sg_host_concat
SQL
);
$concatenator->withCalcFoundRows(true);
return $this->retrieveServices($concatenator, $requestParameters);
}
/**
* @inheritDoc
*/
public function findByRequestParameterAndAccessGroup(
RequestParametersInterface $requestParameters,
array $accessGroups,
): array {
if ($accessGroups === []) {
$this->debug('No access group for this user, return empty');
return [];
}
$accessGroupIds = array_map(
static fn ($accessGroup) => $accessGroup->getId(),
$accessGroups
);
$concatenator = $this->findServicesRequest($accessGroupIds);
$concatenator->defineSelect(
<<<'SQL'
SELECT service.service_id,
service.service_description,
service.timeperiod_tp_id as check_timeperiod_id,
checktp.tp_name as check_timeperiod_name,
service.timeperiod_tp_id2 as notification_timeperiod_id,
notificationtp.tp_name as notification_timeperiod_name,
service.service_activate,
service.service_normal_check_interval,
service.service_retry_check_interval,
service.service_template_model_stm_id as service_template_id,
serviceTemplate.service_description as service_template_name,
GROUP_CONCAT(DISTINCT severity.sc_id) as severity_id,
GROUP_CONCAT(DISTINCT severity.sc_name) as severity_name,
GROUP_CONCAT(DISTINCT category.sc_id) as category_ids,
GROUP_CONCAT(DISTINCT hsr.host_host_id) AS host_ids,
GROUP_CONCAT(DISTINCT CONCAT(sgr.servicegroup_sg_id, '-', sgr.host_host_id)) as sg_host_concat
SQL
);
$concatenator->withCalcFoundRows(true);
$concatenator->appendJoins(
<<<'SQL'
JOIN `:dbstg`.centreon_acl acl
ON service.service_id = acl.service_id
SQL
);
$concatenator->appendWhere(
<<<'SQL'
WHERE acl.group_id IN (:access_group_ids)
SQL
);
$concatenator->storeBindValueMultiple(':access_group_ids', $accessGroupIds, \PDO::PARAM_INT);
return $this->retrieveServices($concatenator, $requestParameters);
}
/**
* @inheritDoc
*/
public function findServiceRelationsByHostGroupId(int $hostGroupId): array
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
SELECT (
SELECT GROUP_CONCAT(DISTINCT host_service_relation.hostgroup_hg_id)
FROM host_service_relation
WHERE service_service_id = hsr.service_service_id
GROUP BY service_service_id
) AS hostgroups,
hsr.service_service_id
FROM host_service_relation hsr
WHERE hsr.hostgroup_hg_id = :hostGroupId;
SQL
));
$statement->bindValue(':hostGroupId', $hostGroupId, \PDO::PARAM_INT);
$statement->execute();
$serviceRelations = [];
while (is_array($result = $statement->fetch(\PDO::FETCH_ASSOC))) {
/**
* @var array{hostgroups: string, service_service_id: string} $result
*/
$serviceRelations[] = new ServiceRelation(
serviceId: (int) $result['service_service_id'],
hostGroupIds: array_map('intval', explode(',', $result['hostgroups']))
);
}
return $serviceRelations;
}
/**
* @inheritDoc
*/
public function findNameById(int $serviceId): ?string
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
SELECT service_description
FROM `:db`.service
WHERE service_id = :service_id
SQL
));
$statement->bindValue(':service_id', $serviceId, \PDO::PARAM_INT);
$statement->execute();
$result = $statement->fetchColumn();
return is_string($result) ? $result : null;
}
/**
* @param int[] $accessGroupIds
*
* @throws \Throwable
*
* @return SqlConcatenator
*/
private function findServicesRequest(array $accessGroupIds = []): SqlConcatenator
{
$categoryAcls = '';
$groupAcls = '';
$hostGroupAcls = '';
$hostCategoryAcls = '';
if ($accessGroupIds !== []) {
if ($this->hasRestrictedAccessToServiceCategories($accessGroupIds)) {
$categoryAcls = <<<'SQL'
AND scr.sc_id IN (
SELECT arscr.sc_id
FROM `:db`.acl_resources_sc_relations arscr
INNER JOIN `:db`.acl_resources res
ON arscr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_res_group_relations argr
ON res.acl_res_id = argr.acl_res_id
INNER JOIN `:db`.acl_groups ag
ON argr.acl_group_id = ag.acl_group_id
WHERE ag.acl_group_id IN (:access_group_ids)
)
SQL;
}
if ($this->hasRestrictedAccessToHostCategories($accessGroupIds)) {
$hostCategoryAcls = <<<'SQL'
AND hcr.hostcategories_hc_id IN (
SELECT arhcr.hc_id
FROM acl_resources_hc_relations arhcr
INNER JOIN `:db`.acl_resources res
ON arhcr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_res_group_relations argr
ON res.acl_res_id = argr.acl_res_id
INNER JOIN `:db`.acl_groups ag
ON argr.acl_group_id = ag.acl_group_id
WHERE ag.acl_group_id IN (:access_group_ids)
)
SQL;
}
if (! $this->hasAccessToAllServiceGroups($accessGroupIds)) {
$groupAcls = <<<'SQL'
AND sgr.servicegroup_sg_id in (
SELECT arsgr.sg_id
FROM `:db`.acl_resources_sg_relations arsgr
INNER JOIN `:db`.acl_resources res
ON arsgr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_res_group_relations argr
ON res.acl_res_id = argr.acl_res_id
INNER JOIN `:db`.acl_groups ag
ON argr.acl_group_id = ag.acl_group_id
WHERE ag.acl_group_id IN (:access_group_ids)
)
SQL;
}
if (! $this->hasAccessToAllHostGroups($accessGroupIds)) {
$hostGroupAcls = <<<'SQL'
AND hgr.hostgroup_hg_id IN (
SELECT arhgr.hg_hg_id
FROM `:db`.acl_resources_hg_relations arhgr
INNER JOIN `:db`.acl_resources res
ON arhgr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_res_group_relations argr
ON res.acl_res_id = argr.acl_res_id
INNER JOIN `:db`.acl_groups ag
ON argr.acl_group_id = ag.acl_group_id
WHERE ag.acl_group_id IN (:access_group_ids)
)
SQL;
}
}
$concatenator = new SqlConcatenator();
$concatenator->defineFrom('`:db`.service');
$concatenator
->appendJoins(
<<<SQL
LEFT JOIN `:db`.service as serviceTemplate
ON service.service_template_model_stm_id = serviceTemplate.service_id
AND serviceTemplate.service_register = '0'
LEFT JOIN `:db`.timeperiod checktp
ON checktp.tp_id = service.timeperiod_tp_id
LEFT JOIN `:db`.timeperiod notificationtp
ON notificationtp.tp_id = service.timeperiod_tp_id2
LEFT JOIN `:db`.service_categories_relation scr
ON scr.service_service_id = service.service_id
{$categoryAcls}
LEFT JOIN `:db`.service_categories severity
ON severity.sc_id = scr.sc_id
AND severity.level IS NOT NULL
LEFT JOIN `:db`.service_categories category
ON category.sc_id = scr.sc_id
AND category.level IS NULL
LEFT JOIN `:db`.servicegroup_relation sgr
ON sgr.service_service_id = service.service_id
AND sgr.servicegroup_sg_id
{$groupAcls}
LEFT JOIN `:db`.servicegroup
ON servicegroup.sg_id = sgr.servicegroup_sg_id
LEFT JOIN `:db`.host_service_relation hsr
ON hsr.service_service_id = service.service_id
LEFT JOIN `:db`.host
ON host.host_id = hsr.host_host_id
AND host.host_register = '1'
LEFT JOIN `:db`.hostgroup_relation hgr
ON hgr.host_host_id = host.host_id
{$hostGroupAcls}
LEFT JOIN `:db`.hostgroup
ON hostgroup.hg_id = hgr.hostgroup_hg_id
LEFT JOIN `:db`.hostcategories_relation hcr
ON hcr.host_host_id = host.host_id
{$hostCategoryAcls}
LEFT JOIN `:db`.hostcategories
ON hostcategories.hc_id = hcr.hostcategories_hc_id
AND hostcategories.level IS NULL
SQL
)
->appendWhere(
<<<'SQL'
WHERE service.service_register = '1'
SQL
)
->appendGroupBy(
<<<'SQL'
GROUP BY service.service_id
SQL
);
return $concatenator;
}
/**
* @param SqlConcatenator $concatenator
* @param RequestParametersInterface $requestParameters
*
* @throws \Throwable
*
* @return ServiceLight[]
*/
private function retrieveServices(SqlConcatenator $concatenator, RequestParametersInterface $requestParameters): array
{
// Settup for search, pagination, order
$sqlTranslator = new SqlRequestParametersTranslator($requestParameters);
$sqlTranslator->setConcordanceArray([
'name' => 'service.service_description',
'host.id' => 'host.host_id',
'host.name' => 'host.host_name',
'category.id' => 'category.sc_id',
'category.name' => 'category.sc_name',
'severity.id' => 'severity.sc_id',
'severity.name' => 'severity.sc_name',
'group.id' => 'servicegroup.sg_id',
'group.name' => 'servicegroup.sg_name',
'hostgroup.id' => 'hostgroup.hg_id',
'hostgroup.name' => 'hostgroup.hg_name',
'hostcategory.id' => 'hostcategories.hc_id',
'hostcategory.name' => 'hostcategories.hc_name',
]);
$sqlTranslator->addNormalizer('is_activated', new BoolToEnumNormalizer());
$sqlTranslator->translateForConcatenator($concatenator);
$statement = $this->db->prepare($this->translateDbName($concatenator->__toString()));
$sqlTranslator->bindSearchValues($statement);
$concatenator->bindValuesToStatement($statement);
$statement->execute();
$sqlTranslator->calculateNumberOfRows($this->db);
$services = [];
while (is_array($result = $statement->fetch(\PDO::FETCH_ASSOC))) {
$services[] = new ServiceLight(
id: $result['service_id'],
name: new TrimmedString($result['service_description']),
hostIds: array_map('intval', explode(',', $result['host_ids'])),
categoryIds: $result['category_ids']
? array_map('intval', explode(',', $result['category_ids']))
: [],
groups: $result['sg_host_concat']
? array_map(
static function (string $sgRel) use ($result): ServiceGroupRelation {
[$sgId, $hostId] = explode('-', $sgRel);
return new ServiceGroupRelation(
serviceId: $result['service_id'],
serviceGroupId: (int) $sgId,
hostId: (int) $hostId
);
},
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Infrastructure/API/FindRealTimeUniqueServiceNames/FindRealTimeUniqueServiceNamesController.php | centreon/src/Core/Service/Infrastructure/API/FindRealTimeUniqueServiceNames/FindRealTimeUniqueServiceNamesController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Infrastructure\API\FindRealTimeUniqueServiceNames;
use Centreon\Application\Controller\AbstractController;
use Core\Service\Application\UseCase\FindRealTimeUniqueServiceNames\FindRealTimeUniqueServiceNames;
use Core\Service\Application\UseCase\FindRealTimeUniqueServiceNames\FindRealTimeUniqueServiceNamesPresenterInterface;
use Symfony\Component\HttpFoundation\Response;
final class FindRealTimeUniqueServiceNamesController extends AbstractController
{
/**
* @param FindRealTimeUniqueServiceNames $useCase
* @param FindRealTimeUniqueServiceNamesPresenterInterface $presenter
*
* @return Response
*/
public function __invoke(
FindRealTimeUniqueServiceNames $useCase,
FindRealTimeUniqueServiceNamesPresenterInterface $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiRealtime();
$useCase($presenter);
return $presenter->show();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Infrastructure/API/FindRealTimeUniqueServiceNames/FindRealTimeUniqueServiceNamesPresenter.php | centreon/src/Core/Service/Infrastructure/API/FindRealTimeUniqueServiceNames/FindRealTimeUniqueServiceNamesPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Infrastructure\API\FindRealTimeUniqueServiceNames;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Service\Application\UseCase\FindRealTimeUniqueServiceNames\FindRealTimeUniqueServiceNamesPresenterInterface;
use Core\Service\Application\UseCase\FindRealTimeUniqueServiceNames\FindRealTimeUniqueServiceNamesResponse;
final class FindRealTimeUniqueServiceNamesPresenter extends AbstractPresenter implements FindRealTimeUniqueServiceNamesPresenterInterface
{
/**
* @param RequestParametersInterface $requestParameters
* @param PresenterFormatterInterface $presenterFormatter
*/
public function __construct(
private readonly RequestParametersInterface $requestParameters,
protected PresenterFormatterInterface $presenterFormatter,
) {
parent::__construct($presenterFormatter);
}
/**
* @inheritDoc
*/
public function presentResponse(FindRealTimeUniqueServiceNamesResponse|ResponseStatusInterface $response): void
{
$result = [];
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
$result = array_map(
static fn (string $name): array => ['name' => $name],
$response->names
);
}
$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/Service/Infrastructure/API/FindServices/FindServicesController.php | centreon/src/Core/Service/Infrastructure/API/FindServices/FindServicesController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Infrastructure\API\FindServices;
use Centreon\Application\Controller\AbstractController;
use Core\Service\Application\UseCase\FindServices\FindServices;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class FindServicesController extends AbstractController
{
/**
* @param FindServices $useCase
* @param FindServicesOnPremPresenter $onPremPresenter
* @param FindServicesSaasPresenter $saasPresenter
* @param bool $isCloudPlatform
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
FindServices $useCase,
FindServicesOnPremPresenter $onPremPresenter,
FindServicesSaasPresenter $saasPresenter,
bool $isCloudPlatform,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
$presenter = $isCloudPlatform ? $saasPresenter : $onPremPresenter;
$useCase($presenter);
return $presenter->show();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Infrastructure/API/FindServices/FindServicesOnPremPresenter.php | centreon/src/Core/Service/Infrastructure/API/FindServices/FindServicesOnPremPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Infrastructure\API\FindServices;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Infrastructure\Common\Presenter\PresenterTrait;
use Core\Service\Application\UseCase\FindServices\FindServicesPresenterInterface;
use Core\Service\Application\UseCase\FindServices\FindServicesResponse;
class FindServicesOnPremPresenter extends AbstractPresenter implements FindServicesPresenterInterface
{
use PresenterTrait;
public function __construct(
private readonly RequestParametersInterface $requestParameters,
protected PresenterFormatterInterface $presenterFormatter,
) {
parent::__construct($presenterFormatter);
}
public function presentResponse(ResponseStatusInterface|FindServicesResponse $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
$result = [];
foreach ($response->services as $dto) {
$result[] = [
'id' => $dto->id,
'name' => $dto->name,
'hosts' => array_map(fn ($host): array => [
'id' => $host['id'],
'name' => $host['name'],
], $dto->hosts),
'service_template' => $dto->serviceTemplate
? ['id' => $dto->serviceTemplate['id'], 'name' => $dto->serviceTemplate['name']]
: null,
'check_timeperiod' => $dto->checkTimePeriod
? ['id' => $dto->checkTimePeriod['id'], 'name' => $dto->checkTimePeriod['name']]
: null,
'notification_timeperiod' => $dto->notificationTimePeriod
? ['id' => $dto->notificationTimePeriod['id'], 'name' => $dto->notificationTimePeriod['name']]
: null,
'severity' => $dto->severity
? ['id' => $dto->severity['id'], 'name' => $dto->severity['name']]
: null,
'categories' => array_map(fn ($category): array => [
'id' => $category['id'],
'name' => $category['name'],
], $dto->categories),
'groups' => array_map(fn ($group): array => [
'id' => $group['id'],
'name' => $group['name'],
'host_id' => $group['hostId'],
'host_name' => $group['hostName'],
], $dto->groups),
'normal_check_interval' => $dto->normalCheckInterval,
'retry_check_interval' => $dto->retryCheckInterval,
'is_activated' => $dto->isActivated,
];
}
$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/Service/Infrastructure/API/FindServices/FindServicesSaasPresenter.php | centreon/src/Core/Service/Infrastructure/API/FindServices/FindServicesSaasPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Infrastructure\API\FindServices;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Infrastructure\Common\Presenter\PresenterTrait;
use Core\Service\Application\UseCase\FindServices\FindServicesPresenterInterface;
use Core\Service\Application\UseCase\FindServices\FindServicesResponse;
class FindServicesSaasPresenter extends AbstractPresenter implements FindServicesPresenterInterface
{
use PresenterTrait;
public function __construct(
private readonly RequestParametersInterface $requestParameters,
protected PresenterFormatterInterface $presenterFormatter,
) {
parent::__construct($presenterFormatter);
}
public function presentResponse(ResponseStatusInterface|FindServicesResponse $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
$result = [];
foreach ($response->services as $dto) {
$result[] = [
'id' => $dto->id,
'name' => $dto->name,
'host' => array_map(fn ($host): array => [
'id' => $host['id'],
'name' => $host['name'],
], $dto->hosts),
'service_template' => $dto->serviceTemplate
? ['id' => $dto->serviceTemplate['id'], 'name' => $dto->serviceTemplate['name']]
: null,
'check_timeperiod' => $dto->checkTimePeriod
? ['id' => $dto->checkTimePeriod['id'], 'name' => $dto->checkTimePeriod['name']]
: null,
'severity' => $dto->severity
? ['id' => $dto->severity['id'], 'name' => $dto->severity['name']]
: null,
'categories' => array_map(fn ($category): array => [
'id' => $category['id'],
'name' => $category['name'],
], $dto->categories),
'groups' => array_map(fn ($group): array => [
'id' => $group['id'],
'name' => $group['name'],
'host_id' => $group['hostId'],
'host_name' => $group['hostName'],
], $dto->groups),
'normal_check_interval' => $dto->normalCheckInterval,
'retry_check_interval' => $dto->retryCheckInterval,
'is_activated' => $dto->isActivated,
];
}
$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/Service/Infrastructure/API/FindRealTimeServiceStatusesCount/FindRealTimeServiceStatusesCountController.php | centreon/src/Core/Service/Infrastructure/API/FindRealTimeServiceStatusesCount/FindRealTimeServiceStatusesCountController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Infrastructure\API\FindRealTimeServiceStatusesCount;
use Centreon\Application\Controller\AbstractController;
use Core\Service\Application\UseCase\FindRealTimeServiceStatusesCount\FindRealTimeServiceStatusesCount;
use Core\Service\Application\UseCase\FindRealTimeServiceStatusesCount\FindRealTimeServiceStatusesCountPresenterInterface;
use Symfony\Component\HttpFoundation\Response;
final class FindRealTimeServiceStatusesCountController extends AbstractController
{
/**
* @param FindRealTimeServiceStatusesCount $useCase
* @param FindRealTimeServiceStatusesCountPresenterInterface $presenter
*
* @return Response
*/
public function __invoke(
FindRealTimeServiceStatusesCount $useCase,
FindRealTimeServiceStatusesCountPresenterInterface $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiRealtime();
$useCase($presenter);
return $presenter->show();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Infrastructure/API/FindRealTimeServiceStatusesCount/FindRealTimeServiceStatusesCountPresenter.php | centreon/src/Core/Service/Infrastructure/API/FindRealTimeServiceStatusesCount/FindRealTimeServiceStatusesCountPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Infrastructure\API\FindRealTimeServiceStatusesCount;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Service\Application\UseCase\FindRealTimeServiceStatusesCount\FindRealTimeServiceStatusesCountPresenterInterface;
use Core\Service\Application\UseCase\FindRealTimeServiceStatusesCount\FindRealTimeServiceStatusesCountResponse;
class FindRealTimeServiceStatusesCountPresenter extends AbstractPresenter implements FindRealTimeServiceStatusesCountPresenterInterface
{
/**
* @param FindRealTimeServiceStatusesCountResponse|ResponseStatusInterface $response
*/
public function presentResponse(FindRealTimeServiceStatusesCountResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
$this->present([
'ok' => ['total' => $response->okStatuses],
'warning' => ['total' => $response->warningStatuses],
'critical' => ['total' => $response->criticalStatuses],
'unknown' => ['total' => $response->unknownStatuses],
'pending' => ['total' => $response->pendingStatuses],
'total' => $response->total,
]);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Infrastructure/API/PartialUpdateService/PartialUpdateServiceController.php | centreon/src/Core/Service/Infrastructure/API/PartialUpdateService/PartialUpdateServiceController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Infrastructure\API\PartialUpdateService;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Common\Domain\YesNoDefault;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Service\Application\UseCase\PartialUpdateService\MacroDto;
use Core\Service\Application\UseCase\PartialUpdateService\PartialUpdateService;
use Core\Service\Application\UseCase\PartialUpdateService\PartialUpdateServiceRequest;
use Core\Service\Infrastructure\Model\YesNoDefaultConverter;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
/**
* @phpstan-type _Service = array{
* name?: string,
* host_id?: int,
* service_template_id?: int|null,
* check_command_id?: int|null,
* check_timeperiod_id?: int|null,
* notification_timeperiod_id?: int|null,
* event_handler_command_id?: int|null,
* icon_id?: int|null,
* severity_id?: int|null,
* graph_template_id?: int|null,
* check_command_args?: list<string>|null,
* event_handler_command_args?: list<string>|null,
* max_check_attempts?: int|null,
* normal_check_interval?: int|null,
* retry_check_interval?: int|null,
* active_check_enabled?: int|null,
* passive_check_enabled?: int|null,
* volatility_enabled?: int|null,
* notification_enabled?: int|null,
* notification_interval?: int|null,
* notification_type?: int|null,
* first_notification_delay?: int|null,
* recovery_notification_delay?: int|null,
* acknowledgement_timeout?: int|null,
* freshness_checked?: int|null,
* freshness_threshold?: int|null,
* flap_detection_enabled?: int|null,
* low_flap_threshold?: int|null,
* high_flap_threshold?: int|null,
* event_handler_enabled?: int|null,
* note?: string|null,
* note_url?: string|null,
* action_url?: string|null,
* icon_alternative?: string|null,
* comment?: string|null,
* geo_coords?: string|null,
* macros?: array<array{name: string, value: string|null, is_password: bool, description: string|null}>,
* service_categories?: list<int>|null,
* service_groups?: list<int>|null,
* is_activated?: boolean,
* is_contact_group_additive_inheritance?: boolean,
* is_contact_additive_inheritance?: boolean,
* }
*/
final class PartialUpdateServiceController extends AbstractController
{
use LoggerTrait;
/**
* @param Request $request
* @param PartialUpdateService $useCase
* @param DefaultPresenter $presenter
* @param bool $isCloudPlatform
* @param int $serviceId
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
Request $request,
PartialUpdateService $useCase,
DefaultPresenter $presenter,
bool $isCloudPlatform,
int $serviceId,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
try {
$dto = $this->createDto($request, $isCloudPlatform);
$useCase($dto, $presenter, $serviceId);
} catch (\InvalidArgumentException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
}
return $presenter->show();
}
/**
* @param Request $request
* @param bool $isCloudPlatform
*
* @return PartialUpdateServiceRequest
*/
private function createDto(Request $request, bool $isCloudPlatform): PartialUpdateServiceRequest
{
/** @var _Service $data */
$data = $this->validateAndRetrieveDataSent(
$request,
$isCloudPlatform
? __DIR__ . DIRECTORY_SEPARATOR . 'PartialUpdateServiceSaasSchema.json'
: __DIR__ . DIRECTORY_SEPARATOR . 'PartialUpdateServiceOnPremSchema.json'
);
$dto = new PartialUpdateServiceRequest();
/** @var array<string,string> $nonEmptyProperties */
$nonEmptyProperties = [
'name' => 'name',
'hostId' => 'host_id',
];
if ($isCloudPlatform === true) {
$nonEmptyProperties['template'] = 'service_template_id';
}
foreach ($nonEmptyProperties as $dtoKey => $dataKey) {
if (\array_key_exists($dataKey, $data)) {
$dto->{$dtoKey} = $data[$dataKey];
}
}
/** @var array<string,string> $dataOrEmptyArrayProperties */
$dataOrEmptyArrayProperties = [
'commandArguments' => 'check_command_args',
'eventHandlerArguments' => 'event_handler_command_args',
'categories' => 'service_categories',
'groups' => 'service_groups',
];
foreach ($dataOrEmptyArrayProperties as $dtoKey => $dataKey) {
if (\array_key_exists($dataKey, $data)) {
$dto->{$dtoKey} = $data[$dataKey] ?? [];
}
}
/** @var array<string,string> $dataOrNullProperties */
$dataOrNullProperties = [
'note' => 'note',
'noteUrl' => 'note_url',
'actionUrl' => 'action_url',
'iconAlternativeText' => 'icon_alternative',
'comment' => 'comment',
'geoCoords' => 'geo_coords',
'commandId' => 'check_command_id',
'checkTimePeriodId' => 'check_timeperiod_id',
'notificationTimePeriodId' => 'notification_timeperiod_id',
'eventHandlerId' => 'event_handler_command_id',
'graphTemplateId' => 'graph_template_id',
'iconId' => 'icon_id',
'severityId' => 'severity_id',
'maxCheckAttempts' => 'max_check_attempts',
'normalCheckInterval' => 'normal_check_interval',
'retryCheckInterval' => 'retry_check_interval',
'notificationInterval' => 'notification_interval',
'notificationTypes' => 'notification_type',
'firstNotificationDelay' => 'first_notification_delay',
'recoveryNotificationDelay' => 'recovery_notification_delay',
'acknowledgementTimeout' => 'acknowledgement_timeout',
'freshnessThreshold' => 'freshness_threshold',
'lowFlapThreshold' => 'low_flap_threshold',
'highFlapThreshold' => 'high_flap_threshold',
];
if ($isCloudPlatform === false) {
$dataOrNullProperties['template'] = 'service_template_id';
}
foreach ($dataOrNullProperties as $dtoKey => $dataKey) {
if (\array_key_exists($dataKey, $data)) {
$dto->{$dtoKey} = $data[$dataKey] ?? null;
}
}
/** @var array<string,string> $dataOrDefaultValueProperties */
$dataOrDefaultValueProperties = [
'activeChecks' => 'active_check_enabled',
'passiveCheck' => 'passive_check_enabled',
'volatility' => 'volatility_enabled',
'notificationsEnabled' => 'notification_enabled',
'checkFreshness' => 'freshness_checked',
'flapDetectionEnabled' => 'flap_detection_enabled',
'eventHandlerEnabled' => 'event_handler_enabled',
];
foreach ($dataOrDefaultValueProperties as $dtoKey => $dataKey) {
if (\array_key_exists($dataKey, $data)) {
$dto->{$dtoKey} = $data[$dataKey] ?? YesNoDefaultConverter::toInt(YesNoDefault::Default);
}
}
if (\array_key_exists('is_contact_group_additive_inheritance', $data)) {
$dto->isContactGroupAdditiveInheritance = $data['is_contact_group_additive_inheritance'];
}
if (\array_key_exists('is_contact_additive_inheritance', $data)) {
$dto->isContactAdditiveInheritance = $data['is_contact_additive_inheritance'];
}
if (\array_key_exists('is_activated', $data)) {
$dto->isActivated = $data['is_activated'];
}
if (\array_key_exists('macros', $data)) {
$dto->macros = [];
foreach ($data['macros'] as $macro) {
$dto->macros[] = new MacroDto(
$macro['name'],
$macro['value'],
(bool) $macro['is_password'],
$macro['description']
);
}
}
return $dto;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Infrastructure/API/DeleteService/DeleteServiceController.php | centreon/src/Core/Service/Infrastructure/API/DeleteService/DeleteServiceController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Infrastructure\API\DeleteService;
use Centreon\Application\Controller\AbstractController;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Service\Application\UseCase\DeleteService\DeleteService;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class DeleteServiceController extends AbstractController
{
/**
* @param DeleteService $useCase
* @param DefaultPresenter $presenter
* @param int $serviceId
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
DeleteService $useCase,
DefaultPresenter $presenter,
int $serviceId,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($serviceId, $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/Service/Infrastructure/API/DeployServices/DeployServicesSaasPresenter.php | centreon/src/Core/Service/Infrastructure/API/DeployServices/DeployServicesSaasPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Infrastructure\API\DeployServices;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\CreatedResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Service\Application\UseCase\DeployServices\DeployServiceDto;
use Core\Service\Application\UseCase\DeployServices\DeployServicesPresenterInterface;
use Core\Service\Application\UseCase\DeployServices\DeployServicesResponse;
class DeployServicesSaasPresenter extends AbstractPresenter implements DeployServicesPresenterInterface
{
/**
* @inheritDoc
*/
public function presentResponse(DeployServicesResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
$this->present(
new CreatedResponse(
null,
[
'services' => array_map(
static fn (DeployServiceDto $service): array => [
'id' => $service->id,
'name' => $service->name,
'host_id' => $service->hostId,
'geo_coords' => $service->geoCoords,
'service_template_id' => $service->serviceTemplateId,
'check_timeperiod_id' => $service->checkTimePeriodId,
'max_check_attempts' => $service->maxCheckAttempts,
'normal_check_interval' => $service->normalCheckInterval,
'retry_check_interval' => $service->retryCheckInterval,
'note' => $service->note,
'note_url' => $service->noteUrl,
'action_url' => $service->actionUrl,
'icon_id' => $service->iconId,
'severity_id' => $service->severityId,
],
$response->services
),
]
)
);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Infrastructure/API/DeployServices/DeployServicesController.php | centreon/src/Core/Service/Infrastructure/API/DeployServices/DeployServicesController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Service\Infrastructure\API\DeployServices;
use Centreon\Application\Controller\AbstractController;
use Core\Service\Application\UseCase\DeployServices\DeployServices;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class DeployServicesController extends AbstractController
{
/**
* @param DeployServices $useCase
* @param DeployServicesOnPremPresenter $onPremPresenter
* @param DeployServicesSaasPresenter $saasPresenter
* @param bool $isCloudPlatform
* @param int $hostId
*
* @throws AccessDeniedException
*/
public function __invoke(
DeployServices $useCase,
DeployServicesOnPremPresenter $onPremPresenter,
DeployServicesSaasPresenter $saasPresenter,
bool $isCloudPlatform,
int $hostId,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
$presenter = $isCloudPlatform ? $saasPresenter : $onPremPresenter;
$useCase($presenter, $hostId);
return $presenter->show();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.