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/Notification/Infrastructure/API/UpdateNotification/UpdateNotificationPresenter.php | centreon/src/Core/Notification/Infrastructure/API/UpdateNotification/UpdateNotificationPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Notification\Infrastructure\API\UpdateNotification;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Notification\Application\UseCase\UpdateNotification\UpdateNotificationPresenterInterface;
class UpdateNotificationPresenter extends DefaultPresenter implements UpdateNotificationPresenterInterface
{
public function presentResponse(ResponseStatusInterface $response): void
{
$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/Timezone/Application/Repository/ReadTimezoneRepositoryInterface.php | centreon/src/Core/Timezone/Application/Repository/ReadTimezoneRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Timezone\Application\Repository;
interface ReadTimezoneRepositoryInterface
{
/**
* Determine if a timezone exists by its ID.
*
* @param int $timezoneId
*
* @return bool
*/
public function exists(int $timezoneId): bool;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Timezone/Domain/Model/Timezone.php | centreon/src/Core/Timezone/Domain/Model/Timezone.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Timezone\Domain\Model;
use Centreon\Domain\Common\Assertion\Assertion;
class Timezone
{
/**
* @param int $id
* @param string $name
* @param string $offset
* @param string $daylightSavingTimeOffset
* @param string $description
*
* @throws \Assert\AssertionFailedException
*/
public function __construct(
private readonly int $id,
private readonly string $name,
private readonly string $offset,
private readonly string $daylightSavingTimeOffset,
private readonly string $description = '',
) {
$shortName = (new \ReflectionClass($this))->getShortName();
Assertion::notEmptyString($name, "{$shortName}::name");
Assertion::regex($offset, '/^[-+][0-9]{2}:[0-9]{2}$/', "{$shortName}::offset");
Assertion::regex(
$daylightSavingTimeOffset,
'/^[-+][0-9]{2}:[0-9]{2}$/',
"{$shortName}::daylightSavingTimeOffset"
);
}
public function getId(): int
{
return $this->id;
}
public function getName(): string
{
return $this->name;
}
public function getOffset(): string
{
return $this->offset;
}
public function getDaylightSavingTimeOffset(): string
{
return $this->daylightSavingTimeOffset;
}
public function getDescription(): string
{
return $this->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/Timezone/Infrastructure/Repository/DbReadTimezoneRepository.php | centreon/src/Core/Timezone/Infrastructure/Repository/DbReadTimezoneRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Timezone\Infrastructure\Repository;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Timezone\Application\Repository\ReadTimezoneRepositoryInterface;
class DbReadTimezoneRepository extends AbstractRepositoryRDB implements ReadTimezoneRepositoryInterface
{
use LoggerTrait;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function exists(int $timezoneId): bool
{
$this->info('Check existence of timezone with ID #' . $timezoneId);
$request = $this->translateDbName(
<<<'SQL'
SELECT 1
FROM `:db`.timezone
WHERE timezone_id = :timezoneId
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':timezoneId', $timezoneId, \PDO::PARAM_INT);
$statement->execute();
return (bool) $statement->fetchColumn();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Tag/RealTime/Application/UseCase/FindTag/FindTagResponse.php | centreon/src/Core/Tag/RealTime/Application/UseCase/FindTag/FindTagResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Tag\RealTime\Application\UseCase\FindTag;
use Core\Application\RealTime\Common\RealTimeResponseTrait;
use Core\Tag\RealTime\Domain\Model\Tag;
class FindTagResponse
{
use RealTimeResponseTrait;
/** @var array<int, array<string, int|string>> */
public array $tags;
/**
* @param Tag[] $tags
*/
public function __construct(array $tags)
{
$this->tags = $this->tagsToArray($tags);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Tag/RealTime/Application/Repository/ReadTagRepositoryInterface.php | centreon/src/Core/Tag/RealTime/Application/Repository/ReadTagRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Tag\RealTime\Application\Repository;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Core\Tag\RealTime\Domain\Model\Tag;
interface ReadTagRepositoryInterface
{
/**
* Find all tags.
*
* @param int $typeId
*
* @throws \Throwable
*
* @return Tag[]
*/
public function findAllByTypeId(int $typeId): array;
/**
* Find all tags.
*
* @param int $typeId
* @param AccessGroup[] $accessGroups
*
* @throws \Throwable
*
* @return Tag[]
*/
public function findAllByTypeIdAndAccessGroups(int $typeId, array $accessGroups): array;
/**
* Find tags of type typeId linked to the resource (identified by id and parentId).
*
* @param int $id
* @param int $parentId
* @param int $typeId
*
* @throws \Throwable
*
* @return Tag[]
*/
public function findAllByResourceAndTypeId(int $id, int $parentId, int $typeId): array;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Tag/RealTime/Domain/Model/Tag.php | centreon/src/Core/Tag/RealTime/Domain/Model/Tag.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Tag\RealTime\Domain\Model;
use Centreon\Domain\Common\Assertion\Assertion;
class Tag
{
public const SERVICE_GROUP_TYPE_ID = 0;
public const HOST_GROUP_TYPE_ID = 1;
public const SERVICE_CATEGORY_TYPE_ID = 2;
public const HOST_CATEGORY_TYPE_ID = 3;
private int $type;
/**
* @param int $id
* @param string $name
* @param int $type
*
* @throws \Assert\AssertionFailedException
*/
public function __construct(private int $id, private string $name, int $type)
{
Assertion::notEmpty($name, 'Tag::name');
$this->name = $name;
$this->setType($type);
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* Setter for $type property.
*
* @param int $type
*
* @throws \InvalidArgumentException
*
* @return Tag
*/
public function setType(int $type): self
{
if (! in_array($type, self::getAvailableTypeIds(), true)) {
throw new \InvalidArgumentException('Type Id is not valid');
}
$this->type = $type;
return $this;
}
/**
* @return int
*/
public function getType(): int
{
return $this->type;
}
/**
* Retrieves the list of available type ids.
*
* @return int[]
*/
private static function getAvailableTypeIds(): array
{
return [
self::SERVICE_GROUP_TYPE_ID,
self::HOST_GROUP_TYPE_ID,
self::SERVICE_CATEGORY_TYPE_ID,
self::HOST_CATEGORY_TYPE_ID,
];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Tag/RealTime/Infrastructure/Repository/Tag/DbTagFactory.php | centreon/src/Core/Tag/RealTime/Infrastructure/Repository/Tag/DbTagFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Tag\RealTime\Infrastructure\Repository\Tag;
use Core\Tag\RealTime\Domain\Model\Tag;
/**
* @phpstan-import-type _tag from DbReadTagRepository
*/
class DbTagFactory
{
/**
* Create ServiceCategory model using data from database.
*
* @param _tag $data
*
* @return Tag
*/
public static function createFromRecord(array $data): Tag
{
return new Tag((int) $data['id'], $data['name'], (int) $data['type']);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Tag/RealTime/Infrastructure/Repository/Tag/DbReadTagRepository.php | centreon/src/Core/Tag/RealTime/Infrastructure/Repository/Tag/DbReadTagRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Tag\RealTime\Infrastructure\Repository\Tag;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use Core\Tag\RealTime\Application\Repository\ReadTagRepositoryInterface;
use Core\Tag\RealTime\Domain\Model\Tag;
use Utility\SqlConcatenator;
/**
* @phpstan-type _tag array{
* id: int,
* name: string,
* type: int
* }
*/
class DbReadTagRepository extends AbstractRepositoryDRB implements ReadTagRepositoryInterface
{
use LoggerTrait;
/** @var SqlRequestParametersTranslator */
private SqlRequestParametersTranslator $sqlRequestTranslator;
/**
* @param DatabaseConnection $db
* @param SqlRequestParametersTranslator $sqlRequestTranslator
*/
public function __construct(DatabaseConnection $db, SqlRequestParametersTranslator $sqlRequestTranslator)
{
$this->db = $db;
$this->sqlRequestTranslator = $sqlRequestTranslator;
$this->sqlRequestTranslator
->getRequestParameters()
->setConcordanceStrictMode(RequestParameters::CONCORDANCE_MODE_STRICT);
$this->sqlRequestTranslator->setConcordanceArray([
'name' => 'tags.name',
]);
}
/**
* @inheritDoc
*/
public function findAllByTypeId(int $typeId): array
{
$this->info('Fetching tags from database of type', ['type' => $typeId]);
$request = 'SELECT SQL_CALC_FOUND_ROWS 1 AS REALTIME, id, name, `type`
FROM `:dbstg`.tags';
// Handle search
$searchRequest = $this->sqlRequestTranslator->translateSearchParameterToSql();
$request .= $searchRequest === null ? ' WHERE ' : $searchRequest . ' AND ';
$request .= ' type = :type AND EXISTS (
SELECT 1 FROM `:dbstg`.resources_tags AS rtags
WHERE rtags.tag_id = tags.tag_id
)';
// Handle sort
$sortRequest = $this->sqlRequestTranslator->translateSortParameterToSql();
$request .= $sortRequest ?? ' ORDER BY name ASC';
// Handle pagination
$request .= $this->sqlRequestTranslator->translatePaginationToSql();
$statement = $this->db->prepare($this->translateDbName($request));
foreach ($this->sqlRequestTranslator->getSearchValues() as $key => $data) {
/** @var int */
$type = key($data);
$value = $data[$type];
$statement->bindValue($key, $value, $type);
}
$statement->bindValue(':type', $typeId, \PDO::PARAM_INT);
$statement->execute();
// Set total
$result = $this->db->query('SELECT FOUND_ROWS() AS REALTIME');
if ($result !== false && ($total = $result->fetchColumn()) !== false) {
$this->sqlRequestTranslator->getRequestParameters()->setTotal((int) $total);
}
$tags = [];
while ($record = $statement->fetch(\PDO::FETCH_ASSOC)) {
/** @var _tag $record */
$tags[] = DbTagFactory::createFromRecord($record);
}
return $tags;
}
/**
* @inheritDoc
*/
public function findAllByTypeIdAndAccessGroups(int $typeId, 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
);
$this->info(
'Fetching tags from database of type and access groups',
['type' => $typeId, 'access_group_ids' => $accessGroupIds]
);
if ((
$typeId === Tag::HOST_CATEGORY_TYPE_ID
&& ! $this->hasRestrictedAccessToHostCategories($accessGroupIds)
)
|| (
$typeId === Tag::SERVICE_CATEGORY_TYPE_ID
&& ! $this->hasRestrictedAccessToServiceCategories($accessGroupIds)
)
) {
return $this->findAllByTypeId($typeId);
}
switch ($typeId) {
case Tag::HOST_CATEGORY_TYPE_ID:
$aclJoins = <<<'SQL'
INNER JOIN `:db`.acl_resources_hc_relations arhr
ON tags.id = arhr.hc_id
INNER JOIN `:db`.acl_resources res
ON arhr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_res_group_relations argr
ON res.acl_res_id = argr.acl_res_id
INNER JOIN `:db`.acl_groups ag
ON argr.acl_group_id = ag.acl_group_id
SQL;
break;
case Tag::SERVICE_CATEGORY_TYPE_ID:
$aclJoins = <<<'SQL'
INNER JOIN `:db`.acl_resources_sc_relations arsr
ON tags.id = arsr.sc_id
INNER JOIN `:db`.acl_resources res
ON arsr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_res_group_relations argr
ON res.acl_res_id = argr.acl_res_id
INNER JOIN `:db`.acl_groups ag
ON argr.acl_group_id = ag.acl_group_id
SQL;
break;
case Tag::HOST_GROUP_TYPE_ID:
$aclJoins = <<<'SQL'
INNER JOIN `:db`.acl_resources_hg_relations arhr
ON hg.hg_id = arhr.hg_hg_id
INNER JOIN `:db`.acl_resources res
ON arhr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_res_group_relations argr
ON res.acl_res_id = argr.acl_res_id
INNER JOIN `:db`.acl_groups ag
ON argr.acl_group_id = ag.acl_group_id
SQL;
break;
case Tag::SERVICE_GROUP_TYPE_ID:
$aclJoins = <<<'SQL'
INNER JOIN `:db`.acl_resources_sg_relations arsr
ON sg.sg_id = arsr.sg_id
INNER JOIN `:db`.acl_resources res
ON arsr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_res_group_relations argr
ON res.acl_res_id = argr.acl_res_id
INNER JOIN `:db`.acl_groups ag
ON argr.acl_group_id = ag.acl_group_id
SQL;
break;
default:
throw new \Exception('Unknown tag type');
}
// Handle search
$searchRequest = $this->sqlRequestTranslator->translateSearchParameterToSql();
$search = $searchRequest === null ? 'WHERE' : "{$searchRequest} AND ";
foreach ($accessGroupIds as $key => $id) {
$bindValues[":access_group_id_{$key}"] = $id;
}
$aclGroupBind = implode(', ', array_keys($bindValues));
// Handle sort
$sortRequest = $this->sqlRequestTranslator->translateSortParameterToSql();
$sort = $sortRequest ?? ' ORDER BY name ASC';
// Handle pagination
$pagination = $this->sqlRequestTranslator->translatePaginationToSql();
$statement = $this->db->prepare($this->translateDbName(
<<<SQL
SELECT SQL_CALC_FOUND_ROWS 1 AS REALTIME, id, name, `type`
FROM `:dbstg`.tags
{$aclJoins}
{$search}
type = :type AND EXISTS (
SELECT 1 FROM `:dbstg`.resources_tags AS rtags
WHERE rtags.tag_id = tags.tag_id
)
AND ag.acl_group_id IN ({$aclGroupBind})
{$sort}
{$pagination}
SQL
));
foreach ($this->sqlRequestTranslator->getSearchValues() as $key => $data) {
/** @var int */
$type = key($data);
$value = $data[$type];
$statement->bindValue($key, $value, $type);
}
$statement->bindValue(':type', $typeId, \PDO::PARAM_INT);
foreach ($bindValues as $bindName => $bindValue) {
$statement->bindValue($bindName, $bindValue, \PDO::PARAM_INT);
}
$statement->execute();
// Set total
$result = $this->db->query('SELECT FOUND_ROWS() AS REALTIME');
if ($result !== false && ($total = $result->fetchColumn()) !== false) {
$this->sqlRequestTranslator->getRequestParameters()->setTotal((int) $total);
}
$tags = [];
while ($record = $statement->fetch(\PDO::FETCH_ASSOC)) {
/** @var _tag $record */
$tags[] = DbTagFactory::createFromRecord($record);
}
return $tags;
}
/**
* @inheritDoc
*/
public function findAllByResourceAndTypeId(int $id, int $parentId, int $typeId): array
{
$this->info(
'Fetching tags from database for specified resource id, parentId and typeId',
[
'id' => $id,
'parentId' => $parentId,
'type' => $typeId,
]
);
$request = 'SELECT 1 AS REALTIME, tags.id AS id, tags.name AS name, tags.`type` AS `type`
FROM `:dbstg`.tags
LEFT JOIN `:dbstg`.resources_tags
ON tags.tag_id = resources_tags.tag_id
LEFT JOIN `:dbstg`.resources
ON resources_tags.resource_id = resources.resource_id
WHERE resources.id = :id AND resources.parent_id = :parentId AND tags.type = :typeId';
$statement = $this->db->prepare($this->translateDbName($request));
$statement->bindValue(':id', $id, \PDO::PARAM_INT);
$statement->bindValue(':parentId', $parentId, \PDO::PARAM_INT);
$statement->bindValue(':typeId', $typeId, \PDO::PARAM_INT);
$statement->execute();
$tags = [];
while ($record = $statement->fetch(\PDO::FETCH_ASSOC)) {
/** @var _tag $record */
$tags[] = DbTagFactory::createFromRecord($record);
}
return $tags;
}
/**
* Determine if service categories are filtered for given access group ids:
* - true: accessible service categories are filtered
* - false: accessible service categories are not filtered.
*
* @param int[] $accessGroupIds
*
* @phpstan-param non-empty-array<int> $accessGroupIds
*
* @return bool
*/
private function hasRestrictedAccessToServiceCategories(array $accessGroupIds): bool
{
$concatenator = new SqlConcatenator();
$concatenator->defineSelect(
<<<'SQL'
SELECT 1
FROM `:db`.acl_resources_sc_relations arsr
INNER JOIN `:db`.acl_resources res
ON arsr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_res_group_relations argr
ON res.acl_res_id = argr.acl_res_id
INNER JOIN `:db`.acl_groups ag
ON argr.acl_group_id = ag.acl_group_id
SQL
);
$concatenator->storeBindValueMultiple(':access_group_ids', $accessGroupIds, \PDO::PARAM_INT)
->appendWhere('ag.acl_group_id IN (:access_group_ids)');
$statement = $this->db->prepare($this->translateDbName($concatenator->__toString()));
$concatenator->bindValuesToStatement($statement);
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* Determine if host categories are filtered for given access group ids:
* - true: accessible host categories are filtered
* - false: accessible host categories are not filtered.
*
* @param int[] $accessGroupIds
*
* @phpstan-param non-empty-array<int> $accessGroupIds
*
* @return bool
*/
private function hasRestrictedAccessToHostCategories(array $accessGroupIds): bool
{
$concatenator = new SqlConcatenator();
$concatenator->defineSelect(
<<<'SQL'
SELECT 1
FROM `:db`.acl_resources_hc_relations arhr
INNER JOIN `:db`.acl_resources res
ON arhr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_res_group_relations argr
ON res.acl_res_id = argr.acl_res_id
INNER JOIN `:db`.acl_groups ag
ON argr.acl_group_id = ag.acl_group_id
SQL
);
$concatenator->storeBindValueMultiple(':access_group_ids', $accessGroupIds, \PDO::PARAM_INT)
->appendWhere('ag.acl_group_id IN (:access_group_ids)');
$statement = $this->db->prepare($this->translateDbName($concatenator->__toString()));
$concatenator->bindValuesToStatement($statement);
$statement->execute();
return (bool) $statement->fetchColumn();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Metric/Application/UseCase/FindMetricsByService/FindMetricsByServicePresenterInterface.php | centreon/src/Core/Metric/Application/UseCase/FindMetricsByService/FindMetricsByServicePresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Metric\Application\UseCase\FindMetricsByService;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface FindMetricsByServicePresenterInterface
{
/**
* @param FindMetricsByServiceResponse|ResponseStatusInterface $response
*/
public function presentResponse(FindMetricsByServiceResponse|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/Metric/Application/UseCase/FindMetricsByService/FindMetricsByServiceResponse.php | centreon/src/Core/Metric/Application/UseCase/FindMetricsByService/FindMetricsByServiceResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Metric\Application\UseCase\FindMetricsByService;
final class FindMetricsByServiceResponse
{
/** @var MetricDto[] */
public array $metricsDto;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Metric/Application/UseCase/FindMetricsByService/FindMetricsByService.php | centreon/src/Core/Metric/Application/UseCase/FindMetricsByService/FindMetricsByService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Metric\Application\UseCase\FindMetricsByService;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Metric\Application\Repository\ReadMetricRepositoryInterface;
use Core\Metric\Domain\Model\Metric;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
final class FindMetricsByService
{
use LoggerTrait;
/**
* @param ContactInterface $user
* @param ReadMetricRepositoryInterface $metricRepository
* @param ReadAccessGroupRepositoryInterface $accessGroupRepository
* @param RequestParametersInterface $requestParameters
*/
public function __construct(
private ContactInterface $user,
private ReadMetricRepositoryInterface $metricRepository,
private ReadAccessGroupRepositoryInterface $accessGroupRepository,
private RequestParametersInterface $requestParameters,
) {
}
/**
* @param int $hostId
* @param int $serviceId
* @param FindMetricsByServicePresenterInterface $presenter
*/
public function __invoke(
int $hostId,
int $serviceId,
FindMetricsByServicePresenterInterface $presenter,
): void {
try {
$this->info('Finding metrics for service', ['id' => $serviceId]);
if ($this->user->isAdmin()) {
$metrics = $this->metricRepository->findByHostIdAndServiceId($hostId, $serviceId, $this->requestParameters);
} else {
$accessGroups = $this->accessGroupRepository->findByContact($this->user);
$metrics = $this->metricRepository->findByHostIdAndServiceIdAndAccessGroups(
$hostId,
$serviceId,
$accessGroups,
$this->requestParameters
);
}
if ($metrics === []) {
$presenter->presentResponse(new NotFoundResponse('metrics'));
} else {
$presenter->presentResponse($this->createResponse($metrics));
}
} catch (\Throwable $ex) {
$this->error('An error occured while finding metrics', ['trace' => (string) $ex]);
$presenter->presentResponse(new ErrorResponse('An error occured while finding metrics'));
}
}
/**
* Create Response.
*
* @param Metric[] $metrics
*
* @return FindMetricsByServiceResponse
*/
private function createResponse(array $metrics): FindMetricsByServiceResponse
{
$response = new FindMetricsByServiceResponse();
$metricsDto = [];
foreach ($metrics as $metric) {
$metricDto = new MetricDto();
$metricDto->id = $metric->getId();
$metricDto->unit = $metric->getUnit();
$metricDto->name = $metric->getName();
$metricDto->currentValue = $metric->getCurrentValue();
$metricDto->warningHighThreshold = $metric->getWarningHighThreshold();
$metricDto->warningLowThreshold = $metric->getWarningLowThreshold();
$metricDto->criticalHighThreshold = $metric->getCriticalHighThreshold();
$metricDto->criticalLowThreshold = $metric->getCriticalLowThreshold();
$metricsDto[] = $metricDto;
}
$response->metricsDto = $metricsDto;
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/Metric/Application/UseCase/FindMetricsByService/MetricDto.php | centreon/src/Core/Metric/Application/UseCase/FindMetricsByService/MetricDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Metric\Application\UseCase\FindMetricsByService;
class MetricDto
{
public int $id = 0;
public string $name = '';
public ?string $unit = null;
public ?float $currentValue = null;
public ?float $warningHighThreshold = null;
public ?float $warningLowThreshold = null;
public ?float $criticalHighThreshold = null;
public ?float $criticalLowThreshold = 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/Metric/Application/UseCase/DownloadPerformanceMetrics/DownloadPerformanceMetricPresenterInterface.php | centreon/src/Core/Metric/Application/UseCase/DownloadPerformanceMetrics/DownloadPerformanceMetricPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Metric\Application\UseCase\DownloadPerformanceMetrics;
use Core\Application\Common\UseCase\PresenterInterface;
interface DownloadPerformanceMetricPresenterInterface extends PresenterInterface
{
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Metric/Application/UseCase/DownloadPerformanceMetrics/DownloadPerformanceMetricResponse.php | centreon/src/Core/Metric/Application/UseCase/DownloadPerformanceMetrics/DownloadPerformanceMetricResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Metric\Application\UseCase\DownloadPerformanceMetrics;
use Core\Metric\Domain\Model\PerformanceMetric;
final class DownloadPerformanceMetricResponse
{
/** @var PerformanceMetric[] */
public iterable $performanceMetrics = [];
public string $filename;
/**
* @param iterable<PerformanceMetric> $performanceMetrics
* @param string $filename
*/
public function __construct(iterable $performanceMetrics, string $filename)
{
$this->performanceMetrics = $this->performanceMetricToArray($performanceMetrics);
$this->filename = $filename;
}
/**
* @param iterable<PerformanceMetric> $performanceMetrics
*
* @return iterable<mixed>
*/
private function performanceMetricToArray(iterable $performanceMetrics): iterable
{
foreach ($performanceMetrics as $performanceMetric) {
yield $this->formatPerformanceMetric($performanceMetric);
}
}
/**
* @param PerformanceMetric $performanceMetric
*
* @return array<string, mixed>
*/
private function formatPerformanceMetric(PerformanceMetric $performanceMetric): array
{
$formattedData = [
'time' => $performanceMetric->getDateValue()->getTimestamp(),
'humantime' => $performanceMetric->getDateValue()->format('Y-m-d H:i:s'),
];
foreach ($performanceMetric->getMetricValues() as $metricValue) {
$formattedData[$metricValue->getName()] = sprintf('%f', $metricValue->getValue());
}
return $formattedData;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Metric/Application/UseCase/DownloadPerformanceMetrics/DownloadPerformanceMetrics.php | centreon/src/Core/Metric/Application/UseCase/DownloadPerformanceMetrics/DownloadPerformanceMetrics.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Metric\Application\UseCase\DownloadPerformanceMetrics;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Application\Common\UseCase\PresenterInterface;
use Core\Application\RealTime\Repository\ReadIndexDataRepositoryInterface;
use Core\Application\RealTime\Repository\ReadPerformanceDataRepositoryInterface;
use Core\Domain\RealTime\Model\IndexData;
use Core\Metric\Application\Exception\MetricException;
use Core\Metric\Application\Repository\ReadMetricRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Service\Application\Repository\ReadServiceRepositoryInterface;
final class DownloadPerformanceMetrics
{
use LoggerTrait;
/**
* @param ReadIndexDataRepositoryInterface $indexDataRepository
* @param ReadMetricRepositoryInterface $metricRepository
* @param ReadPerformanceDataRepositoryInterface $performanceDataRepository
* @param ReadAccessGroupRepositoryInterface $readAccessGroupRepository
* @param ReadServiceRepositoryInterface $readServiceRepository
* @param ContactInterface $user
*/
public function __construct(
readonly private ReadIndexDataRepositoryInterface $indexDataRepository,
readonly private ReadMetricRepositoryInterface $metricRepository,
readonly private ReadPerformanceDataRepositoryInterface $performanceDataRepository,
readonly private ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
readonly private ReadServiceRepositoryInterface $readServiceRepository,
readonly private ContactInterface $user,
) {
}
/**
* @param DownloadPerformanceMetricRequest $request
* @param DownloadPerformanceMetricPresenterInterface $presenter
*/
public function __invoke(
DownloadPerformanceMetricRequest $request,
PresenterInterface $presenter,
): void {
try {
if (
! $this->user->hasTopologyRole(Contact::ROLE_MONITORING_PERFORMANCES_RW)
&& ! $this->user->hasTopologyRole(Contact::ROLE_MONITORING_RESOURCES_STATUS_RW)
) {
$this->error(
"User doesn't have sufficient rights to download the performance metrics",
[
'user_id' => $this->user->getId(),
'host_id' => $request->hostId,
'service_id' => $request->serviceId]
);
$presenter->setResponseStatus(
new ForbiddenResponse(MetricException::downloadNotAllowed())
);
return;
}
$this->info(
'Retrieve performance metrics',
[
'host_id' => $request->hostId,
'service_id' => $request->serviceId,
]
);
if (! $this->user->isAdmin()) {
$accessGroups = $this->readAccessGroupRepository->findByContact($this->user);
$this->debug('Filtering by access groups', ['access_groups' => $accessGroups]);
$isServiceExists = $this->readServiceRepository->existsByAccessGroups(
$request->serviceId,
$accessGroups
);
if (! $isServiceExists) {
$this->error(
'Service not found',
['host_id' => $request->hostId, 'service_id' => $request->serviceId]
);
$presenter->present(new NotFoundResponse('Service'));
return;
}
}
$index = $this->indexDataRepository->findIndexByHostIdAndServiceId($request->hostId, $request->serviceId);
$metrics = $this->metricRepository->findMetricsByIndexId($index);
$performanceMetrics = $this->performanceDataRepository->findDataByMetricsAndDates(
$metrics,
$request->startDate,
$request->endDate
);
$fileName = $this->generateDownloadFileNameByIndex($index);
$this->info('Filename used to download metrics', ['filename' => $fileName]);
$presenter->present(new DownloadPerformanceMetricResponse($performanceMetrics, $fileName));
} catch (\Throwable $ex) {
$this->error(
'Impossible to retrieve performance metrics',
[
'host_id' => $request->hostId,
'service_id' => $request->serviceId,
'error_message' => $ex->__toString(),
]
);
$presenter->setResponseStatus(
new ErrorResponse('Impossible to retrieve performance metrics')
);
}
}
/**
* @param int $index
*
* @return string
*/
private function generateDownloadFileNameByIndex(int $index): string
{
$indexData = $this->indexDataRepository->findHostNameAndServiceDescriptionByIndex($index);
if (! ($indexData instanceof IndexData)) {
return (string) $index;
}
$hostName = $indexData->getHostName();
$serviceDescription = $indexData->getServiceDescription();
if ($hostName !== '' && $serviceDescription !== '') {
return sprintf('%s_%s', $hostName, $serviceDescription);
}
return (string) $index;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Metric/Application/UseCase/DownloadPerformanceMetrics/DownloadPerformanceMetricRequest.php | centreon/src/Core/Metric/Application/UseCase/DownloadPerformanceMetrics/DownloadPerformanceMetricRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Metric\Application\UseCase\DownloadPerformanceMetrics;
use DateTimeInterface;
final class DownloadPerformanceMetricRequest
{
/**
* @param int $hostId
* @param int $serviceId
* @param DateTimeInterface $startDate
* @param DateTimeInterface $endDate
*/
public function __construct(
public int $hostId,
public int $serviceId,
public DateTimeInterface $startDate,
public DateTimeInterface $endDate,
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Metric/Application/Exception/MetricException.php | centreon/src/Core/Metric/Application/Exception/MetricException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Metric\Application\Exception;
class MetricException extends \Exception
{
public static function missingPropertyInMetricInformation(string $property): self
{
return new self(sprintf(_('Missing property in the metric information: %s'), $property));
}
public static function metricsNotFound(): self
{
return new self(_('Metrics not found'));
}
public static function invalidMetricFormat(): self
{
return new self(_('Invalid metric format'));
}
public static function downloadNotAllowed(): self
{
return new self(_('Downloading the performance metrics is not allowed'));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Metric/Application/Repository/ReadMetricRepositoryInterface.php | centreon/src/Core/Metric/Application/Repository/ReadMetricRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Metric\Application\Repository;
use Centreon\Domain\Monitoring\Service;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Metric\Domain\Model\Metric;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
interface ReadMetricRepositoryInterface
{
/**
* @param int $indexId
*
* @return array<Metric>
*/
public function findMetricsByIndexId(int $indexId): array;
/**
* Find Service by Metric Names.
*
* @param string[] $metricNames
* @param RequestParametersInterface $requestParameters
*
* @return Service[]
*/
public function findServicesByMetricNamesAndRequestParameters(
array $metricNames,
RequestParametersInterface $requestParameters,
): array;
/**
* Find Service by Metric Names and Access Groups.
*
* @param string[] $metricNames
* @param AccessGroup[] $accessGroups
* @param RequestParametersInterface $requestParameters
*
* @return Service[]
*/
public function findServicesByMetricNamesAndAccessGroupsAndRequestParameters(
array $metricNames,
array $accessGroups,
RequestParametersInterface $requestParameters,
): array;
/**
* Find Metrics by their host and service id.
*
* @param int $hostId
* @param int $serviceId
* @param RequestParametersInterface $requestParameters
*
* @throws \Throwable
*
* @return Metric[]
*/
public function findByHostIdAndServiceId(
int $hostId,
int $serviceId,
RequestParametersInterface $requestParameters,
): array;
/**
* Find Metrics by their host, service id and user access groups.
*
* @param int $hostId
* @param int $serviceId
* @param AccessGroup[] $accessGroups
* @param RequestParametersInterface $requestParameters
* @param string|null $metricName
*
* @throws \Throwable
*
* @return Metric[]
*/
public function findByHostIdAndServiceIdAndAccessGroups(
int $hostId,
int $serviceId,
array $accessGroups,
RequestParametersInterface $requestParameters,
?string $metricName = null,
): array;
/**
* Retrieve a single metric value for a given host and service
*
* @param int $hostId
* @param int $serviceId
* @param string $metricName
* @param RequestParametersInterface $requestParameters
* @param AccessGroup[] $accessGroups
*
* @throws RepositoryException
*
* @return Metric|null
*/
public function findSingleMetricValue(
int $hostId,
int $serviceId,
string $metricName,
RequestParametersInterface $requestParameters,
array $accessGroups = [],
): Metric|null;
/**
* Retrieve a single metric value for a given metaService
*
* @param array<int> $service
* @param string $metricName
* @param RequestParametersInterface $requestParameters
* @param AccessGroup[] $accessGroups
*
* @throws RepositoryException
*
* @return Metric|null
*/
public function findSingleMetaMetricValue(
array $service,
string $metricName,
RequestParametersInterface $requestParameters,
array $accessGroups = [],
): Metric|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/Metric/Domain/Model/MetricValue.php | centreon/src/Core/Metric/Domain/Model/MetricValue.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Metric\Domain\Model;
class MetricValue
{
/**
* @param string $name
* @param float $value
*/
public function __construct(private string $name, private float $value)
{
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @return float
*/
public function getValue(): float
{
return $this->value;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Metric/Domain/Model/PerformanceMetric.php | centreon/src/Core/Metric/Domain/Model/PerformanceMetric.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Metric\Domain\Model;
use DateTimeInterface;
class PerformanceMetric
{
/**
* @param DateTimeInterface $dateValue
* @param MetricValue[] $metricValues
*/
public function __construct(
private DateTimeInterface $dateValue,
private array $metricValues = [],
) {
}
/**
* @param MetricValue $metricValue
*/
public function addMetricValue(MetricValue $metricValue): void
{
$this->metricValues[] = $metricValue;
}
/**
* @return MetricValue[]
*/
public function getMetricValues(): array
{
return $this->metricValues;
}
/**
* @return DateTimeInterface
*/
public function getDateValue(): DateTimeInterface
{
return $this->dateValue;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Metric/Domain/Model/Metric.php | centreon/src/Core/Metric/Domain/Model/Metric.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Metric\Domain\Model;
class Metric
{
private ?string $unit = null;
private ?float $currentValue = null;
private ?float $warningHighThreshold = null;
private ?float $warningLowThreshold = null;
private ?float $criticalHighThreshold = null;
private ?float $criticalLowThreshold = null;
/**
* @param int $id
* @param string $name
*/
public function __construct(private int $id, private string $name)
{
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
public function setUnit(?string $unit): self
{
$this->unit = $unit;
return $this;
}
public function getUnit(): ?string
{
return $this->unit;
}
public function setCurrentValue(?float $currentValue): self
{
$this->currentValue = $currentValue;
return $this;
}
public function getCurrentValue(): ?float
{
return $this->currentValue;
}
public function setWarningHighThreshold(?float $warningHighThreshold): self
{
$this->warningHighThreshold = $warningHighThreshold;
return $this;
}
public function getWarningHighThreshold(): ?float
{
return $this->warningHighThreshold;
}
public function setWarningLowThreshold(?float $warningLowThreshold): self
{
$this->warningLowThreshold = $warningLowThreshold;
return $this;
}
public function getWarningLowThreshold(): ?float
{
return $this->warningLowThreshold;
}
public function setCriticalHighThreshold(?float $criticalHighThreshold): self
{
$this->criticalHighThreshold = $criticalHighThreshold;
return $this;
}
public function getCriticalHighThreshold(): ?float
{
return $this->criticalHighThreshold;
}
public function setCriticalLowThreshold(?float $criticalLowThreshold): self
{
$this->criticalLowThreshold = $criticalLowThreshold;
return $this;
}
public function getCriticalLowThreshold(): ?float
{
return $this->criticalLowThreshold;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Metric/Domain/Model/MetricInformation/GeneralInformation.php | centreon/src/Core/Metric/Domain/Model/MetricInformation/GeneralInformation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Metric\Domain\Model\MetricInformation;
class GeneralInformation
{
public function __construct(
private readonly int $indexId,
private readonly int $id,
private readonly string $name,
private readonly string $alias,
private readonly string $unit,
private readonly bool $isHidden,
private readonly ?string $hostName,
private readonly ?string $serviceName,
private readonly string $legend,
private readonly bool $isVirtual,
private readonly bool $isStacked,
private readonly int $stackingOrder,
) {
}
public function getIndexId(): int
{
return $this->indexId;
}
public function getId(): int
{
return $this->id;
}
public function getName(): string
{
return $this->name;
}
public function getAlias(): string
{
return $this->alias;
}
public function getUnit(): string
{
return $this->unit;
}
public function isHidden(): bool
{
return $this->isHidden;
}
public function getHostName(): ?string
{
return $this->hostName;
}
public function getServiceName(): ?string
{
return $this->serviceName;
}
public function getLegend(): string
{
return $this->legend;
}
public function isVirtual(): bool
{
return $this->isVirtual;
}
public function isStacked(): bool
{
return $this->isStacked;
}
public function getStackingOrder(): int
{
return $this->stackingOrder;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Metric/Domain/Model/MetricInformation/MetricInformation.php | centreon/src/Core/Metric/Domain/Model/MetricInformation/MetricInformation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Metric\Domain\Model\MetricInformation;
class MetricInformation
{
public function __construct(
private readonly GeneralInformation $generalInformation,
private readonly DataSource $dataSource,
private readonly ThresholdInformation $thresholdInformation,
private readonly RealTimeDataInformation $realTimeDataInformation,
) {
}
public function getGeneralInformation(): GeneralInformation
{
return $this->generalInformation;
}
public function getDataSource(): DataSource
{
return $this->dataSource;
}
public function getThresholdInformation(): ThresholdInformation
{
return $this->thresholdInformation;
}
public function getRealTimeDataInformation(): RealTimeDataInformation
{
return $this->realTimeDataInformation;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Metric/Domain/Model/MetricInformation/ThresholdInformation.php | centreon/src/Core/Metric/Domain/Model/MetricInformation/ThresholdInformation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Metric\Domain\Model\MetricInformation;
class ThresholdInformation
{
public function __construct(
private readonly ?float $warningThreshold,
private readonly ?float $warningLowThreshold,
private readonly ?float $criticalThreshold,
private readonly ?float $criticalLowThreshold,
private readonly string $colorWarning,
private readonly string $colorCritical,
) {
}
public function getWarningThreshold(): ?float
{
return $this->warningThreshold;
}
public function getWarningLowThreshold(): ?float
{
return $this->warningLowThreshold;
}
public function getCriticalThreshold(): ?float
{
return $this->criticalThreshold;
}
public function getCriticalLowThreshold(): ?float
{
return $this->criticalLowThreshold;
}
public function getColorWarning(): string
{
return $this->colorWarning;
}
public function getColorCritical(): string
{
return $this->colorCritical;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Metric/Domain/Model/MetricInformation/DataSource.php | centreon/src/Core/Metric/Domain/Model/MetricInformation/DataSource.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Metric\Domain\Model\MetricInformation;
class DataSource
{
public function __construct(
private readonly ?int $minimum,
private readonly ?int $maximum,
private readonly ?int $minMax,
private readonly ?int $lastValue,
private readonly ?int $averageValue,
private readonly ?int $total,
private readonly ?float $transparency,
private readonly ?string $colorArea,
private readonly bool $isFilled,
private readonly bool $isInverted,
private readonly ?string $legend,
private readonly bool $isStacked,
private readonly ?int $order,
private readonly int $tickness,
private readonly int $colorMode,
private readonly string $lineColor,
) {
}
public function getMinimum(): ?int
{
return $this->minimum;
}
public function getMaximum(): ?int
{
return $this->maximum;
}
public function getMinMax(): ?int
{
return $this->minMax;
}
public function getLastValue(): ?int
{
return $this->lastValue;
}
public function getAverageValue(): ?int
{
return $this->averageValue;
}
public function getTotal(): ?int
{
return $this->total;
}
public function getTickness(): int
{
return $this->tickness;
}
public function getColorMode(): int
{
return $this->colorMode;
}
public function getLineColor(): string
{
return $this->lineColor;
}
public function getTransparency(): ?float
{
return $this->transparency;
}
public function getColorArea(): ?string
{
return $this->colorArea;
}
public function isFilled(): bool
{
return $this->isFilled;
}
public function isInverted(): bool
{
return $this->isInverted;
}
public function getLegend(): ?string
{
return $this->legend;
}
public function isStacked(): bool
{
return $this->isStacked;
}
public function getOrder(): ?int
{
return $this->order;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Metric/Domain/Model/MetricInformation/RealTimeDataInformation.php | centreon/src/Core/Metric/Domain/Model/MetricInformation/RealTimeDataInformation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Metric\Domain\Model\MetricInformation;
use Centreon\Domain\Common\Assertion\Assertion;
use Centreon\Domain\Common\Assertion\AssertionException;
class RealTimeDataInformation
{
/**
* @param array<float|null> $values
* @param array<array<string>> $labels
* @param float|null $minimumValueLimit
* @param float|null $maximumValueLimit
* @param float|null $minimumValue float handled as string to not lose decimals on *.O value
* @param float|null $maximumValue float handled as string to not lose decimals on *.O value
* @param float|null $lastValue
* @param float|null $averageValue
*
* @throws AssertionException
*/
public function __construct(
private readonly array $values,
private readonly array $labels,
private readonly ?float $minimumValueLimit,
private readonly ?float $maximumValueLimit,
private readonly ?float $minimumValue,
private readonly ?float $maximumValue,
private readonly ?float $lastValue,
private readonly ?float $averageValue,
) {
Assertion::arrayOfTypeOrNull('float', $values, 'values');
foreach ($labels as $label) {
Assertion::arrayOfTypeOrNull('string', $label, 'labels');
}
}
/**
* @return array<float|null>
*/
public function getValues(): array
{
return $this->values;
}
/**
* @return array<array<string>>
*/
public function getLabels(): array
{
return $this->labels;
}
public function getMinimumValueLimit(): ?float
{
return $this->minimumValueLimit;
}
public function getMaximumValueLimit(): ?float
{
return $this->maximumValueLimit;
}
public function getMinimumValue(): ?float
{
return $this->minimumValue;
}
public function getMaximumValue(): ?float
{
return $this->maximumValue;
}
public function getLastValue(): ?float
{
return $this->lastValue;
}
public function getAverageValue(): ?float
{
return $this->averageValue;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Metric/Infrastructure/Repository/DbMetricFactory.php | centreon/src/Core/Metric/Infrastructure/Repository/DbMetricFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Metric\Infrastructure\Repository;
use Core\Metric\Domain\Model\Metric;
class DbMetricFactory
{
/**
* @param array{
* id: int,
* name: string,
* unit_name: string,
* current_value: float|null,
* warn: float|null,
* warn_low: float|null,
* crit: float|null,
* crit_low: float|null
* } $record
*
* @return Metric
*/
public static function createFromRecord(array $record): Metric
{
return (new Metric($record['id'], $record['name']))
->setUnit($record['unit_name'])
->setCurrentValue($record['current_value'])
->setWarningHighThreshold($record['warn'])
->setWarningLowThreshold($record['warn_low'])
->setCriticalHighThreshold($record['crit'])
->setCriticalLowThreshold($record['crit_low']);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Metric/Infrastructure/Repository/DbReadMetricRepository.php | centreon/src/Core/Metric/Infrastructure/Repository/DbReadMetricRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Metric\Infrastructure\Repository;
use Centreon\Domain\Monitoring\Host;
use Centreon\Domain\Monitoring\Service;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Metric\Application\Repository\ReadMetricRepositoryInterface;
use Core\Metric\Domain\Model\Metric;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
class DbReadMetricRepository extends AbstractRepositoryDRB implements ReadMetricRepositoryInterface
{
/**
* @param DatabaseConnection $db
* @param array<
* string, array{
* request: string,
* bindValues: array<mixed>
* }
* > $subRequestsInformation
*/
public function __construct(DatabaseConnection $db, private array $subRequestsInformation = [])
{
$this->db = $db;
}
/**
* @param int $indexId
*
* @return array<Metric>
*/
public function findMetricsByIndexId(int $indexId): array
{
$query = 'SELECT DISTINCT metric_id as id, metric_name as name FROM `:dbstg`.metrics, `:dbstg`.index_data ';
$query .= ' WHERE metrics.index_id = index_data.id AND id = :index_id ORDER BY metric_id';
$statement = $this->db->prepare($this->translateDbName($query));
$statement->bindValue(':index_id', $indexId, \PDO::PARAM_INT);
$statement->execute();
$records = $statement->fetchAll();
if (! is_array($records) || $records === []) {
return [];
}
$metrics = [];
foreach ($records as $record) {
$metrics[] = new Metric((int) $record['id'], $record['name']);
}
return $metrics;
}
/**
* @inheritDoc
*/
public function findServicesByMetricNamesAndRequestParameters(
array $metricNames,
RequestParametersInterface $requestParameters,
): array {
if ($metricNames === []) {
return [];
}
$request = $this->buildQueryForFindServices($requestParameters, [], $metricNames);
$statement = $this->db->prepare($this->translateDbName($request));
$statement = $this->executeQueryForFindServices($statement, $metricNames);
$records = $statement->fetchAll();
$services = [];
foreach ($records as $record) {
$services[] = (new Service())
->setId($record['service_id'])
->setHost(
(new Host())
->setId($record['host_id'])
->setName($record['host_name'])
);
}
return $services;
}
/**
* @inheritDoc
*/
public function findByHostIdAndServiceId(int $hostId, int $serviceId, RequestParametersInterface $requestParameters): array
{
$query = $this->buildQueryForFindMetrics($requestParameters);
$statement = $this->executeQueryForFindMetrics($query, $hostId, $serviceId);
$records = $statement->fetchAll();
return $this->createMetricsFromRecords($records);
}
/**
* @inheritDoc
*/
public function findByHostIdAndServiceIdAndAccessGroups(
int $hostId,
int $serviceId,
array $accessGroups,
RequestParametersInterface $requestParameters,
?string $metricName = null,
): array {
$query = $this->buildQueryForFindMetrics($requestParameters, $accessGroups, $metricName);
$statement = $this->executeQueryForFindMetrics($query, $hostId, $serviceId, $metricName);
$records = $statement->fetchAll();
return $this->createMetricsFromRecords($records);
}
/**
* @inheritDoc
*/
public function findServicesByMetricNamesAndAccessGroupsAndRequestParameters(
array $metricNames,
array $accessGroups,
RequestParametersInterface $requestParameters,
): array {
if ($metricNames === []) {
return [];
}
$request = $this->buildQueryForFindServices($requestParameters, $accessGroups, $metricNames);
$statement = $this->db->prepare($this->translateDbName($request));
$statement = $this->executeQueryForFindServices($statement, $metricNames);
$records = $statement->fetchAll();
$services = [];
foreach ($records as $record) {
$services[] = (new Service())
->setId($record['service_id'])
->setHost(
(new Host())
->setId($record['host_id'])
->setName($record['host_name'])
);
}
return $services;
}
/**
* @inheritDoc
*/
public function findSingleMetricValue(
int $hostId,
int $serviceId,
string $metricName,
RequestParametersInterface $requestParameters,
array $accessGroups = [],
): Metric|null {
try {
$metrics = $this->findByHostIdAndServiceIdAndAccessGroups(
$hostId,
$serviceId,
$accessGroups,
$requestParameters,
$metricName
);
} catch (\Throwable $exception) {
throw new RepositoryException(
"Error retrieving metric '{$metricName}' for host {$hostId}, service {$serviceId}",
[
'metricName' => $metricName,
'hostId' => $hostId,
'serviceId' => $serviceId,
],
$exception
);
}
if ($metrics !== []) {
return $metrics[0];
}
return null;
}
/**
* @inheritDoc
*/
public function findSingleMetaMetricValue(
array $service,
string $metricName,
RequestParametersInterface $requestParameters,
array $accessGroups = [],
): Metric|null {
return $this->findSingleMetricValue(
$service['host_id'],
$service['service_id'],
$metricName,
$requestParameters,
$accessGroups
);
}
/**
* Execute SQL Query to find Metrics.
*
* @param string $query
* @param int $hostId
* @param int $serviceId
* @param string|null $metricName
*
* @throws \Throwable
*
* @return \PDOStatement
*/
private function executeQueryForFindMetrics(string $query, int $hostId, int $serviceId, ?string $metricName = null): \PDOStatement
{
$statement = $this->db->prepare($this->translateDbName($query));
$statement->bindValue(':hostId', $hostId, \PDO::PARAM_INT);
$statement->bindValue(':serviceId', $serviceId, \PDO::PARAM_INT);
if ($metricName !== null) {
$statement->bindValue(':metricName', $metricName, \PDO::PARAM_STR);
}
$statement->execute();
return $statement;
}
/**
* Create Metrics Instances from database records.
*
* @param array<
* array{
* id: int,
* name: string,
* unit_name: string,
* current_value: float|null,
* warn: float|null,
* warn_low: float|null,
* crit: float|null,
* crit_low: float|null
* }
* > $records
*
* @return Metric[]
*/
private function createMetricsFromRecords(array $records): array
{
if ($records === []) {
return [];
}
$metrics = [];
foreach ($records as $record) {
$metrics[] = DbMetricFactory::createFromRecord($record);
}
return $metrics;
}
/**
* Build the SQL Query.
*
* @param RequestParametersInterface $requestParameters
* @param AccessGroup[] $accessGroups
* @param string[] $metricNames
*
* @return string
*/
private function buildQueryForFindServices(
RequestParametersInterface $requestParameters,
array $accessGroups,
array $metricNames,
): string {
$request = <<<'SQL'
SELECT DISTINCT id.`host_id`,
id.`host_name`,
id.`service_id`
FROM `:dbstg`.`index_data` AS id
INNER JOIN `:dbstg`.`metrics` AS m ON m.`index_id` = id.`id`
INNER JOIN `:dbstg`.`resources` AS r on r.`parent_id` = id.`host_id`
SQL;
$accessGroupIds = \array_map(
fn (AccessGroup $accessGroup): int => $accessGroup->getId(),
$accessGroups
);
if ($accessGroupIds !== []) {
$accessGroupIdsQuery = \implode(',', $accessGroupIds);
$request .= <<<SQL
INNER JOIN `:dbstg`.`centreon_acl` acl ON acl.`service_id` = id.`service_id`
AND acl.`group_id` IN ({$accessGroupIdsQuery})
SQL;
}
$search = $requestParameters->getSearch();
if ($search !== [] && \array_key_exists('$and', $search)) {
$this->subRequestsInformation = $this->getSubRequestsInformation($search);
$request .= $this->buildSubRequestForTags($this->subRequestsInformation);
}
if ($this->subRequestsInformation !== []) {
$request .= $this->subRequestsInformation['service']['request'] ?? '';
$request .= $this->subRequestsInformation['metaservice']['request'] ?? '';
$request .= $this->subRequestsInformation['host']['request'] ?? '';
}
$bindValues = [];
foreach ($metricNames as $index => $metricName) {
$bindValues[':metric_name_' . $index] = $metricName;
}
$metricNamesQuery = implode(', ', \array_keys($bindValues));
$request .= <<<SQL
WHERE m.metric_name IN ({$metricNamesQuery})
AND r.enabled = 1
SQL;
return $request;
}
/**
* Build Query For Find Metrics.
*
* @param RequestParametersInterface $requestParameters
* @param AccessGroup[] $accessGroups
* @param string|null $metricName
*
* @throws \Throwable
*
* @return string
*/
private function buildQueryForFindMetrics(RequestParametersInterface $requestParameters, array $accessGroups = [], ?string $metricName = null): string
{
$query = <<<'SQL'
SELECT DISTINCT metric_id as id, metric_name as name, unit_name, current_value, warn,
warn_low, crit, crit_low
FROM `:dbstg`.metrics m
INNER JOIN `:dbstg`.index_data id ON m.index_id = id.id
SQL;
$accessGroupIds = \array_map(
fn (AccessGroup $accessGroup): int => $accessGroup->getId(),
$accessGroups
);
if ($accessGroupIds !== []) {
$accessGroupIdsQuery = \implode(',', $accessGroupIds);
$query .= <<<SQL
INNER JOIN `:dbstg`.`centreon_acl` acl ON acl.`service_id` = id.`service_id`
AND acl.`group_id` IN ({$accessGroupIdsQuery})
SQL;
}
$metricNameCondition = $metricName !== null ? ' AND m.metric_name = :metricName' : '';
$query .= <<<'SQL'
WHERE id.host_id = :hostId
AND id.service_id = :serviceId
SQL;
$query .= $metricNameCondition;
$sqlTranslator = new SqlRequestParametersTranslator($requestParameters);
$query .= $sqlTranslator->translatePaginationToSql();
return $query;
}
/**
* Execute the SQL Query.
*
* @param \PDOStatement $statement
* @param string[] $metricNames
*
* @throws \Throwable
*
* @return \PDOStatement
*/
private function executeQueryForFindServices(\PDOStatement $statement, array $metricNames): \PDOStatement
{
$bindValues = [];
foreach ($metricNames as $index => $metricName) {
$bindValues[':metric_name_' . $index] = $metricName;
}
foreach ($bindValues as $bindToken => $bindValue) {
$statement->bindValue($bindToken, $bindValue, \PDO::PARAM_STR);
}
$boundValues = [];
if ($this->subRequestsInformation !== []) {
foreach ($this->subRequestsInformation as $subRequestInformation) {
$boundValues[] = $subRequestInformation['bindValues'];
}
$boundValues = \array_merge(...$boundValues);
}
foreach ($boundValues as $bindToken => $bindValueInformation) {
foreach ($bindValueInformation as $bindValue => $paramType) {
$statement->bindValue($bindToken, $bindValue, $paramType);
}
}
$statement->execute();
return $statement;
}
/**
* Get request and bind values information for each search filter.
*
* @phpstan-param array{
* '$and': array<
* array{
* 'service.name'?: array{'$in': non-empty-array<string>},
* 'metaservice.id'?: array{'$in': non-empty-array<int>},
* 'host.id'?: array{'$in': non-empty-array<int>},
* 'hostgroup.id'?: array{'$in': non-empty-array<int>},
* 'servicegroup.id'?: array{'$in': non-empty-array<int>},
* 'hostcategory.id'?: array{'$in': non-empty-array<int>},
* 'servicecategory.id'?: array{'$in': non-empty-array<int>},
* }
* >
* } $search
*
* @param array<mixed> $search
*
* @return array<
* string, array{
* request: string,
* bindValues: array<mixed>
* }
* >
*/
private function getSubRequestsInformation(array $search): array
{
$searchParameters = $search['$and'];
$subRequestsInformation = [];
foreach ($searchParameters as $searchParameter) {
if (
\array_key_exists('service.name', $searchParameter)
&& \array_key_exists('$in', $searchParameter['service.name'])
) {
$subRequestsInformation['service'] = $this->buildSubRequestForServiceFilter(
$searchParameter['service.name']['$in']
);
}
if (
\array_key_exists('metaservice.id', $searchParameter)
&& \array_key_exists('$in', $searchParameter['metaservice.id'])
) {
$subRequestsInformation['metaservice'] = $this->buildSubRequestForMetaserviceFilter(
$searchParameter['metaservice.id']['$in']
);
}
if (
\array_key_exists('host.id', $searchParameter)
&& \array_key_exists('$in', $searchParameter['host.id'])
) {
$subRequestsInformation['host'] = $this->buildSubRequestForHostFilter(
$searchParameter['host.id']['$in']
);
}
if (
\array_key_exists('hostgroup.id', $searchParameter)
&& \array_key_exists('$in', $searchParameter['hostgroup.id'])
) {
$subRequestsInformation['hostgroup'] = $this->buildSubRequestForHostGroupFilter(
$searchParameter['hostgroup.id']['$in']
);
}
if (
\array_key_exists('servicegroup.id', $searchParameter)
&& \array_key_exists('$in', $searchParameter['servicegroup.id'])
) {
$subRequestsInformation['servicegroup'] = $this->buildSubRequestForServiceGroupFilter(
$searchParameter['servicegroup.id']['$in']
);
}
if (
\array_key_exists('hostcategory.id', $searchParameter)
&& \array_key_exists('$in', $searchParameter['hostcategory.id'])
) {
$subRequestsInformation['hostcategory'] = $this->buildSubRequestForHostCategoryFilter(
$searchParameter['hostcategory.id']['$in']
);
}
if (
\array_key_exists('servicecategory.id', $searchParameter)
&& \array_key_exists('$in', $searchParameter['servicecategory.id'])
) {
$subRequestsInformation['servicecategory'] = $this->buildSubRequestForServiceCategoryFilter(
$searchParameter['servicecategory.id']['$in']
);
}
}
return $subRequestsInformation;
}
/**
* Build the sub request for service filter.
*
* @param non-empty-array<string> $serviceNames
*
* @return array{
* request: string,
* bindValues: array<mixed>
* }
*/
private function buildSubRequestForServiceFilter(array $serviceNames): array
{
foreach ($serviceNames as $key => $serviceName) {
$bindServiceNames[':service_name' . $key] = [$serviceName => \PDO::PARAM_STR];
}
$bindTokens = implode(', ', array_keys($bindServiceNames));
return [
'request' => <<<SQL
AND id.`service_description` IN ({$bindTokens})
SQL,
'bindValues' => $bindServiceNames,
];
}
/**
* Build the sub request for metaservice filter.
*
* @param non-empty-array<int> $metaserviceIds
*
* @return array{
* request: string,
* bindValues: array<mixed>
* }
*/
private function buildSubRequestForMetaserviceFilter(array $metaserviceIds): array
{
foreach ($metaserviceIds as $key => $metaserviceId) {
$bindMetaserviceNames[':metaservice_name' . $key] = ['meta_' . $metaserviceId => \PDO::PARAM_STR];
}
$bindTokens = implode(', ', array_keys($bindMetaserviceNames));
return [
'request' => <<<SQL
AND id.`service_description` IN ({$bindTokens})
SQL,
'bindValues' => $bindMetaserviceNames,
];
}
/**
* Build the sub request for host filter.
*
* @param non-empty-array<int> $hostIds
*
* @return array{
* request: string,
* bindValues: array<mixed>
* }
*/
private function buildSubRequestForHostFilter(array $hostIds): array
{
foreach ($hostIds as $hostId) {
$bindHostIds[':host_' . $hostId] = [$hostId => \PDO::PARAM_INT];
}
$bindTokens = implode(', ', array_keys($bindHostIds));
return [
'request' => <<<SQL
AND id.`host_id` IN ({$bindTokens})
SQL,
'bindValues' => $bindHostIds,
];
}
/**
* Build the sub request for host group filter.
*
* @param non-empty-array<int> $hostGroupIds
*
* @return array{
* request: string,
* bindValues: array<mixed>
* }
*/
private function buildSubRequestForHostGroupFilter(array $hostGroupIds): array
{
$bindValues = [];
foreach ($hostGroupIds as $hostGroupId) {
$bindValues[':hostgroup_' . $hostGroupId] = [$hostGroupId => \PDO::PARAM_INT];
}
$boundTokens = implode(', ', array_keys($bindValues));
return [
'request' => <<<SQL
SELECT r.`resource_id`,
r.`parent_id`
FROM `:dbstg`.`resources` r
LEFT JOIN `:dbstg`.`resources` pr ON pr.`id` = r.`parent_id`
LEFT JOIN `:dbstg`.`resources_tags` rtags ON rtags.`resource_id` = pr.`resource_id`
INNER JOIN `:dbstg`.tags ON tags.tag_id = rtags.tag_id
WHERE tags.id IN ({$boundTokens})
AND tags.type = 1
SQL,
'bindValues' => $bindValues,
];
}
/**
* Build the sub request for service group filter.
*
* @param non-empty-array<int> $serviceGroupIds
*
* @return array{
* request: string,
* bindValues: array<mixed>
* }
*/
private function buildSubRequestForServiceGroupFilter(array $serviceGroupIds): array
{
$bindValues = [];
foreach ($serviceGroupIds as $serviceGroupId) {
$bindValues[':servicegroup_' . $serviceGroupId] = [$serviceGroupId => \PDO::PARAM_INT];
}
$boundTokens = implode(', ', array_keys($bindValues));
return [
'request' => <<<SQL
SELECT rtags.`resource_id`,
r.`parent_id`
FROM `:dbstg`.`resources_tags` rtags
INNER JOIN `:dbstg`.`tags` ON tags.`tag_id` = rtags.`tag_id`
INNER JOIN `:dbstg`.`resources` r ON r.`resource_id` = rtags.`resource_id`
WHERE tags.id IN ({$boundTokens})
AND tags.type = 0
SQL,
'bindValues' => $bindValues,
];
}
/**
* Build the sub request for host category filter.
*
* @param non-empty-array<int> $hostCategoryIds
*
* @return array{
* request: string,
* bindValues: array<mixed>
* }
*/
private function buildSubRequestForHostCategoryFilter(array $hostCategoryIds): array
{
$bindValues = [];
foreach ($hostCategoryIds as $hostCategoryId) {
$bindValues[':hostcategory_' . $hostCategoryId] = [$hostCategoryId => \PDO::PARAM_INT];
}
$boundTokens = implode(', ', array_keys($bindValues));
return [
'request' => <<<SQL
SELECT r.`resource_id`,
r.`parent_id`
FROM `:dbstg`.`resources` r
LEFT JOIN `:dbstg`.`resources` pr ON pr.`id` = r.`parent_id`
LEFT JOIN `:dbstg`.`resources_tags` rtags ON rtags.`resource_id` = pr.`resource_id`
INNER JOIN `:dbstg`.`tags` ON tags.`tag_id` = rtags.`tag_id`
WHERE tags.id IN ({$boundTokens})
AND tags.type = 3
SQL,
'bindValues' => $bindValues,
];
}
/**
* Build the sub request for service category filter.
*
* @param non-empty-array<int> $serviceCategoryIds
*
* @return array{
* request: string,
* bindValues: array<mixed>
* }
*/
private function buildSubRequestForServiceCategoryFilter(array $serviceCategoryIds): array
{
$bindValues = [];
foreach ($serviceCategoryIds as $serviceCategoryId) {
$bindValues[':servicecategory_' . $serviceCategoryId] = [$serviceCategoryId => \PDO::PARAM_INT];
}
$boundTokens = implode(', ', array_keys($bindValues));
return [
'request' => <<<SQL
SELECT rtags.`resource_id`,
r.`parent_id`
FROM `:dbstg`.resources_tags AS rtags
INNER JOIN `:dbstg`.tags ON tags.tag_id = rtags.tag_id
INNER JOIN `:dbstg`.`resources` r ON r.`resource_id` = rtags.`resource_id`
WHERE tags.id IN ({$boundTokens})
AND tags.type = 2
SQL,
'bindValues' => $bindValues,
];
}
/**
* Build the subrequest for tags filter.
*
* @param array<
* string, array{
* request: string,
* bindValues: array<mixed>
* }
* > $subRequestInformation
*
* @return string
*/
private function buildSubRequestForTags(array $subRequestInformation): string
{
$request = '';
$subRequestForTags = \array_reduce(\array_keys($subRequestInformation), function ($acc, $item) use (
$subRequestInformation
) {
if ($item !== 'host' && $item !== 'service' && $item !== 'metric' && $item !== 'metaservice') {
$acc[] = $subRequestInformation[$item];
}
return $acc;
}, []);
if (! empty($subRequestForTags)) {
$subRequests = array_map(fn ($subRequestForTag) => $subRequestForTag['request'], $subRequestForTags);
$request .= ' INNER JOIN (';
$request .= implode(' INTERSECT ', $subRequests);
$request .= ') AS t ON t.`parent_id` = id.`host_id`';
}
return $request;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Metric/Infrastructure/API/FindMetricsByService/FindMetricsByServicePresenter.php | centreon/src/Core/Metric/Infrastructure/API/FindMetricsByService/FindMetricsByServicePresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Metric\Infrastructure\API\FindMetricsByService;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Metric\Application\UseCase\FindMetricsByService\FindMetricsByServicePresenterInterface;
use Core\Metric\Application\UseCase\FindMetricsByService\FindMetricsByServiceResponse;
use Core\Metric\Application\UseCase\FindMetricsByService\MetricDto;
final class FindMetricsByServicePresenter extends AbstractPresenter implements FindMetricsByServicePresenterInterface
{
public function __construct(protected PresenterFormatterInterface $presenterFormatter)
{
parent::__construct($presenterFormatter);
}
public function presentResponse(FindMetricsByServiceResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
$this->present(array_map(fn (MetricDto $metric) => [
'id' => $metric->id,
'name' => $metric->name,
'unit' => $metric->unit,
'current_value' => $metric->currentValue,
'warning_high_threshold' => $metric->warningHighThreshold,
'warning_low_threshold' => $metric->warningLowThreshold,
'critical_high_threshold' => $metric->criticalHighThreshold,
'critical_low_threshold' => $metric->criticalLowThreshold,
], $response->metricsDto));
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Metric/Infrastructure/API/FindMetricsByService/FindMetricsByServiceController.php | centreon/src/Core/Metric/Infrastructure/API/FindMetricsByService/FindMetricsByServiceController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Metric\Infrastructure\API\FindMetricsByService;
use Centreon\Application\Controller\AbstractController;
use Core\Metric\Application\UseCase\FindMetricsByService\{FindMetricsByService};
use Symfony\Component\HttpFoundation\Response;
final class FindMetricsByServiceController extends AbstractController
{
/**
* @param int $hostId
* @param int $serviceId
* @param FindMetricsByService $useCase
* @param FindMetricsByServicePresenter $presenter
*/
public function __invoke(
int $hostId,
int $serviceId,
FindMetricsByService $useCase,
FindMetricsByServicePresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiRealtime();
$useCase($hostId, $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/Metric/Infrastructure/API/DownloadPerformanceMetrics/DownloadPerformanceMetricsPresenter.php | centreon/src/Core/Metric/Infrastructure/API/DownloadPerformanceMetrics/DownloadPerformanceMetricsPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Metric\Infrastructure\API\DownloadPerformanceMetrics;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Metric\Application\UseCase\DownloadPerformanceMetrics\DownloadPerformanceMetricPresenterInterface;
use Core\Metric\Application\UseCase\DownloadPerformanceMetrics\DownloadPerformanceMetricResponse;
class DownloadPerformanceMetricsPresenter extends AbstractPresenter implements DownloadPerformanceMetricPresenterInterface
{
/**
* {@inheritDoc}
*
* @param DownloadPerformanceMetricResponse $data
*/
public function present(mixed $data): void
{
parent::present($data);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Metric/Infrastructure/API/DownloadPerformanceMetrics/DownloadPerformanceMetricsController.php | centreon/src/Core/Metric/Infrastructure/API/DownloadPerformanceMetrics/DownloadPerformanceMetricsController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Metric\Infrastructure\API\DownloadPerformanceMetrics;
use Centreon\Application\Controller\AbstractController;
use Core\Metric\Application\UseCase\DownloadPerformanceMetrics\DownloadPerformanceMetricRequest;
use Core\Metric\Application\UseCase\DownloadPerformanceMetrics\DownloadPerformanceMetrics;
use DateTimeImmutable;
use DateTimeInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
final class DownloadPerformanceMetricsController extends AbstractController
{
private const START_DATE_PARAMETER_NAME = 'start_date';
private const END_DATE_PARAMETER_NAME = 'end_date';
private DateTimeInterface $startDate;
private DateTimeInterface $endDate;
private Request $request;
private DownloadPerformanceMetricRequest $performanceMetricRequest;
public function __invoke(
int $hostId,
int $serviceId,
DownloadPerformanceMetrics $useCase,
Request $request,
DownloadPerformanceMetricsPresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiRealtime();
$this->request = $request;
$this->createPerformanceMetricRequest($hostId, $serviceId);
$useCase($this->performanceMetricRequest, $presenter);
return $presenter->show();
}
/**
* Creates a performance metric request depending request parameters.
*
* @param int $hostId
* @param int $serviceId
*
* @throws \Exception
*/
private function createPerformanceMetricRequest(int $hostId, int $serviceId): void
{
$this->findStartDate();
$this->findEndDate();
$this->performanceMetricRequest = new DownloadPerformanceMetricRequest(
$hostId,
$serviceId,
$this->startDate,
$this->endDate
);
}
/**
* Populates startDate attribute with start_date parameter value from http request.
*
* @throws \Exception
*/
private function findStartDate(): void
{
$this->startDate = $this->findDateInRequest(self::START_DATE_PARAMETER_NAME);
}
/**
* Populates endDate attribute with end_date parameter value from http request.
*
* @throws \Exception
*/
private function findEndDate(): void
{
$this->endDate = $this->findDateInRequest(self::END_DATE_PARAMETER_NAME);
}
/**
* Retrieves date attribute from http request parameter identified by $parameterName.
*
* @param string $parameterName
*
* @throws \Exception
*
* @return DateTimeImmutable
*/
private function findDateInRequest(string $parameterName): DateTimeImmutable
{
$dateParameter = $this->request->query->get($parameterName);
if (is_null($dateParameter)) {
$errorMessage = 'Unable to find date parameter ' . $parameterName . ' into the http request';
throw new \InvalidArgumentException($errorMessage);
}
return new DateTimeImmutable((string) $dateParameter);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Module/Application/Repository/ModuleInformationRepositoryInterface.php | centreon/src/Core/Module/Application/Repository/ModuleInformationRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Module\Application\Repository;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Module\Domain\Model\ModuleInformation;
interface ModuleInformationRepositoryInterface
{
/**
* Find module information by its name.
*
* @param string $name
*
* @throws RepositoryException
*
* @return null|ModuleInformation
*/
public function findByName(string $name): ?ModuleInformation;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Module/Domain/Model/ModuleInformation.php | centreon/src/Core/Module/Domain/Model/ModuleInformation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Module\Domain\Model;
final readonly class ModuleInformation
{
public function __construct(
public string $packageName,
public string $displayName,
public string $version,
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Module/Infrastructure/ModuleInstallationVerifier.php | centreon/src/Core/Module/Infrastructure/ModuleInstallationVerifier.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Module\Infrastructure;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Module\Application\Repository\ModuleInformationRepositoryInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\DependencyInjection\Attribute\Lazy;
/**
* This class needs to be lazy because it is used in routing loading and it uses services that are not always available depending
* on the state of the application (installed or not).
*/
#[Lazy]
class ModuleInstallationVerifier
{
public function __construct(
#[Autowire(param: 'kernel.project_dir')]
private string $projectDir,
private ModuleInformationRepositoryInterface $repository,
) {
}
/**
* @param string $moduleName
*
* @throws \RuntimeException|RepositoryException
* @return bool
*/
public function isInstallComplete(string $moduleName): bool
{
$moduleInformation = $this->repository->findByName($moduleName);
if (! $moduleInformation) {
throw new \RuntimeException($moduleName . ' is not installed');
}
// @TODO Find a way to inject configuration through the container instead of requiring the file.
$getConfigFileVersion = function () use ($moduleName): string {
/** @var array<string, array{mod_release: string}> $module_conf */
$module_conf = [];
require $this->projectDir . "/www/modules/{$moduleName}/conf.php";
return $module_conf[$moduleName]['mod_release'];
};
return version_compare($getConfigFileVersion(), $moduleInformation->version, '=');
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Module/Infrastructure/Repository/DbReadModuleInformationRepository.php | centreon/src/Core/Module/Infrastructure/Repository/DbReadModuleInformationRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Module\Infrastructure\Repository;
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Adaptation\Database\QueryBuilder\Exception\QueryBuilderException;
use Centreon\Domain\Log\LoggerTrait;
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\Module\Application\Repository\ModuleInformationRepositoryInterface;
use Core\Module\Domain\Model\ModuleInformation;
/**
* @phpstan-type _ModuleInformation array{
* name: string,
* rname: string,
* mod_release: string,
* }
*/
final class DbReadModuleInformationRepository extends DatabaseRepository implements ModuleInformationRepositoryInterface
{
use LoggerTrait;
/**
* {@inheritDoc}
*/
public function findByName(string $name): ?ModuleInformation
{
try {
$query = $this->connection->createQueryBuilder()
->select('name', 'rname', 'mod_release')
->from('modules_informations')
->where('name = :name')
->getQuery();
$queryParameters = QueryParameters::create([QueryParameter::string('name', $name)]);
/** @var _ModuleInformation|false $result */
$result = $this->connection->fetchAssociative($query, $queryParameters);
if (! $result) {
return null;
}
/** @var _ModuleInformation $result */
return new ModuleInformation(
packageName: $result['name'],
displayName: $result['rname'],
version: $result['mod_release']
);
} catch (QueryBuilderException|ValueObjectException|CollectionException|ConnectionException $exception) {
throw new RepositoryException(
"Find module name failed : {$exception->getMessage()}",
['module_name' => $name],
$exception
);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceGroup/Application/UseCase/FindServiceGroups/FindServiceGroupsResponse.php | centreon/src/Core/ServiceGroup/Application/UseCase/FindServiceGroups/FindServiceGroupsResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceGroup\Application\UseCase\FindServiceGroups;
final class FindServiceGroupsResponse
{
/** @var array<
* array{
* id: int,
* name: string,
* alias: string,
* geoCoords: ?string,
* comment: string,
* isActivated: bool
* }
* >
*/
public array $servicegroups = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceGroup/Application/UseCase/FindServiceGroups/FindServiceGroups.php | centreon/src/Core/ServiceGroup/Application/UseCase/FindServiceGroups/FindServiceGroups.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceGroup\Application\UseCase\FindServiceGroups;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\PresenterInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Core\ServiceGroup\Application\Exception\ServiceGroupException;
use Core\ServiceGroup\Application\Repository\ReadServiceGroupRepositoryInterface;
use Core\ServiceGroup\Domain\Model\ServiceGroup;
use Core\ServiceGroup\Infrastructure\API\FindServiceGroups\FindServiceGroupsPresenter;
final class FindServiceGroups
{
use LoggerTrait;
public const AUTHORIZED_ACL_GROUPS = ['customer_admin_acl'];
/**
* @param ReadServiceGroupRepositoryInterface $readServiceGroupRepository
* @param ReadAccessGroupRepositoryInterface $readAccessGroupRepository
* @param RequestParametersInterface $requestParameters
* @param ContactInterface $contact
* @param bool $isCloudPlatform
*/
public function __construct(
private readonly ReadServiceGroupRepositoryInterface $readServiceGroupRepository,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly RequestParametersInterface $requestParameters,
private readonly ContactInterface $contact,
private readonly bool $isCloudPlatform,
) {
}
/**
* @param FindServiceGroupsPresenter $presenter
*/
public function __invoke(PresenterInterface $presenter): void
{
try {
if ($this->isUserAdmin()) {
$this->info(
'Find service groups as admin',
['request' => $this->requestParameters->toArray()]
);
$presenter->present($this->findServiceGroupAsAdmin());
} elseif ($this->contactCanExecuteThisUseCase()) {
$this->info(
'Find service groups as user',
[
'user' => $this->contact->getName(),
'request' => $this->requestParameters->toArray(),
]
);
$presenter->present($this->findServiceGroupAsContact());
} else {
$this->error(
"User doesn't have sufficient rights to see service groups",
['user_id' => $this->contact->getId()]
);
$presenter->setResponseStatus(
new ForbiddenResponse(ServiceGroupException::accessNotAllowed())
);
}
} catch (\Throwable $ex) {
$presenter->setResponseStatus(new ErrorResponse(ServiceGroupException::errorWhileSearching()));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
}
}
/**
* Indicates if the current user is admin or not (cloud + onPremise context).
*
* @return bool
*/
private function isUserAdmin(): bool
{
if ($this->contact->isAdmin()) {
return true;
}
$userAccessGroupNames = array_map(
static fn (AccessGroup $accessGroup): string => $accessGroup->getName(),
$this->readAccessGroupRepository->findByContact($this->contact)
);
return ! empty(array_intersect($userAccessGroupNames, self::AUTHORIZED_ACL_GROUPS))
&& $this->isCloudPlatform;
}
/**
* @throws \Throwable
*
* @return FindServiceGroupsResponse
*/
private function findServiceGroupAsAdmin(): FindServiceGroupsResponse
{
$serviceGroups = $this->readServiceGroupRepository->findAll($this->requestParameters);
return $this->createResponse($serviceGroups);
}
/**
* @throws \Throwable
*
* @return FindServiceGroupsResponse
*/
private function findServiceGroupAsContact(): FindServiceGroupsResponse
{
$serviceGroups = [];
$accessGroupIds = array_map(
fn (AccessGroup $accessGroup): int => $accessGroup->getId(),
$this->readAccessGroupRepository->findByContact($this->contact)
);
if ($accessGroupIds === []) {
return $this->createResponse($serviceGroups);
}
if ($this->readServiceGroupRepository->hasAccessToAllServiceGroups($accessGroupIds)) {
$this->debug(
'ACL configuration for user gives access to all service groups',
['user' => $this->contact->getName()]
);
$serviceGroups = $this->readServiceGroupRepository->findAll($this->requestParameters);
} else {
$this->debug(
'Using users ACL configured on service groups',
['user' => $this->contact->getName()]
);
$serviceGroups = $this->readServiceGroupRepository->findAllByAccessGroupIds(
$this->requestParameters,
$accessGroupIds
);
}
return $this->createResponse($serviceGroups);
}
/**
* @return bool
*/
private function contactCanExecuteThisUseCase(): bool
{
return $this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_SERVICES_SERVICE_GROUPS_READ)
|| $this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_SERVICES_SERVICE_GROUPS_READ_WRITE);
}
/**
* @param iterable<ServiceGroup> $serviceGroups
*
* @return FindServiceGroupsResponse
*/
private function createResponse(iterable $serviceGroups): FindServiceGroupsResponse
{
$response = new FindServiceGroupsResponse();
foreach ($serviceGroups as $serviceGroup) {
$response->servicegroups[] = [
'id' => $serviceGroup->getId(),
'name' => $serviceGroup->getName(),
'alias' => $serviceGroup->getAlias(),
'geoCoords' => $serviceGroup->getGeoCoords()?->__toString(),
'comment' => $serviceGroup->getComment(),
'isActivated' => $serviceGroup->isActivated(),
];
}
return $response;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceGroup/Application/UseCase/AddServiceGroup/AddServiceGroup.php | centreon/src/Core/ServiceGroup/Application/UseCase/AddServiceGroup/AddServiceGroup.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceGroup\Application\UseCase\AddServiceGroup;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Core\Application\Common\UseCase\ConflictResponse;
use Core\Application\Common\UseCase\CreatedResponse;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Application\Common\UseCase\PresenterInterface;
use Core\Domain\Common\GeoCoords;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\WriteAccessGroupRepositoryInterface;
use Core\ServiceGroup\Application\Exception\ServiceGroupException;
use Core\ServiceGroup\Application\Repository\ReadServiceGroupRepositoryInterface;
use Core\ServiceGroup\Application\Repository\WriteServiceGroupRepositoryInterface;
use Core\ServiceGroup\Domain\Model\NewServiceGroup;
use Core\ServiceGroup\Domain\Model\ServiceGroup;
use Core\ServiceGroup\Infrastructure\API\AddServiceGroup\AddServiceGroupPresenter;
final class AddServiceGroup
{
use LoggerTrait;
public function __construct(
private readonly ReadServiceGroupRepositoryInterface $readServiceGroupRepository,
private readonly WriteServiceGroupRepositoryInterface $writeServiceGroupRepository,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly WriteAccessGroupRepositoryInterface $writeAccessGroupRepository,
private readonly DataStorageEngineInterface $dataStorageEngine,
private readonly ContactInterface $contact,
) {
}
/**
* @param AddServiceGroupRequest $request
* @param AddServiceGroupPresenter $presenter
*/
public function __invoke(
AddServiceGroupRequest $request,
PresenterInterface $presenter,
): void {
try {
if ($this->contact->isAdmin()) {
$presenter->present($this->addServiceGroupAsAdmin($request));
$this->info('Add service group', ['request' => $request]);
} elseif ($this->contactCanPerformWriteOperations()) {
$presenter->present($this->addServiceGroupAsContact($request));
$this->info('Add service group', ['request' => $request]);
} else {
$this->error(
"User doesn't have sufficient rights to add service groups",
['user_id' => $this->contact->getId()]
);
$presenter->setResponseStatus(
new ForbiddenResponse(ServiceGroupException::accessNotAllowedForWriting())
);
}
} catch (AssertionFailedException $ex) {
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (ServiceGroupException $ex) {
$presenter->setResponseStatus(
match ($ex->getCode()) {
ServiceGroupException::CODE_CONFLICT => new ConflictResponse($ex),
default => new ErrorResponse($ex),
}
);
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (\Throwable $ex) {
$presenter->setResponseStatus(new ErrorResponse(ServiceGroupException::errorWhileAdding()));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
}
}
/**
* @param AddServiceGroupRequest $request
*
* @throws ServiceGroupException
* @throws \Throwable
*
* @return CreatedResponse<int, AddServiceGroupResponse>
*/
private function addServiceGroupAsAdmin(AddServiceGroupRequest $request): CreatedResponse
{
$this->assertNameDoesNotAlreadyExists($request);
$newServiceGroup = $this->createNewServiceGroup($request);
$newServiceGroupId = $this->writeServiceGroupRepository->add($newServiceGroup);
$serviceGroup = $this->readServiceGroupRepository->findOne($newServiceGroupId)
?? throw ServiceGroupException::errorWhileRetrievingJustCreated();
return $this->createResponse($serviceGroup);
}
/**
* @param AddServiceGroupRequest $request
*
* @throws ServiceGroupException
* @throws \Throwable
*
* @return CreatedResponse<int, AddServiceGroupResponse>
*/
private function addServiceGroupAsContact(AddServiceGroupRequest $request): CreatedResponse
{
$this->assertNameDoesNotAlreadyExists($request);
$accessGroups = $this->readAccessGroupRepository->findByContact($this->contact);
$newServiceGroup = $this->createNewServiceGroup($request);
try {
// As a contact, we must run into ONE transaction TWO operations.
$this->dataStorageEngine->startTransaction();
// 1. Add the service group.
$newServiceGroupId = $this->writeServiceGroupRepository->add($newServiceGroup);
// 2. Create all related ACL links to be able to retrieve it later.
$this->writeAccessGroupRepository->addLinksBetweenServiceGroupAndAccessGroups(
$newServiceGroupId,
$accessGroups
);
$this->dataStorageEngine->commitTransaction();
} catch (\Throwable $ex) {
$this->error("Rollback of 'Add Service Group' transaction for a contact.");
$this->dataStorageEngine->rollbackTransaction();
throw $ex;
}
// Retrieve the Service Group for the response.
$serviceGroup = $this->readServiceGroupRepository->findOneByAccessGroups($newServiceGroupId, $accessGroups)
?? throw ServiceGroupException::errorWhileRetrievingJustCreated();
return $this->createResponse($serviceGroup);
}
/**
* @param AddServiceGroupRequest $request
*
* @throws ServiceGroupException
* @throws \Throwable
*/
private function assertNameDoesNotAlreadyExists(AddServiceGroupRequest $request): void
{
if ($this->readServiceGroupRepository->nameAlreadyExists($request->name)) {
$this->error('Service group name already exists', ['name' => $request->name]);
throw ServiceGroupException::nameAlreadyExists($request->name);
}
}
/**
* @return bool
*/
private function contactCanPerformWriteOperations(): bool
{
return $this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_SERVICES_SERVICE_GROUPS_READ_WRITE);
}
/**
* @param AddServiceGroupRequest $request
*
* @throws \Core\Domain\Exception\InvalidGeoCoordException
* @throws AssertionFailedException
*
* @return NewServiceGroup
*/
private function createNewServiceGroup(AddServiceGroupRequest $request): NewServiceGroup
{
return new NewServiceGroup(
$request->name,
$request->alias,
match ($request->geoCoords) {
null, '' => null,
default => GeoCoords::fromString($request->geoCoords),
},
$request->comment,
$request->isActivated,
);
}
/**
* @param ServiceGroup $serviceGroup
*
* @return CreatedResponse<int, AddServiceGroupResponse>
*/
private function createResponse(ServiceGroup $serviceGroup): CreatedResponse
{
$response = new AddServiceGroupResponse();
$response->id = $serviceGroup->getId();
$response->name = $serviceGroup->getName();
$response->alias = $serviceGroup->getAlias();
$response->geoCoords = $serviceGroup->getGeoCoords()?->__toString();
$response->comment = $serviceGroup->getComment();
$response->isActivated = $serviceGroup->isActivated();
return new CreatedResponse($response->id, $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/ServiceGroup/Application/UseCase/AddServiceGroup/AddServiceGroupResponse.php | centreon/src/Core/ServiceGroup/Application/UseCase/AddServiceGroup/AddServiceGroupResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceGroup\Application\UseCase\AddServiceGroup;
final class AddServiceGroupResponse
{
public int $id = 0;
public string $name = '';
public string $alias = '';
public ?string $geoCoords = null;
public string $comment = '';
public bool $isActivated = true;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceGroup/Application/UseCase/AddServiceGroup/AddServiceGroupRequest.php | centreon/src/Core/ServiceGroup/Application/UseCase/AddServiceGroup/AddServiceGroupRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceGroup\Application\UseCase\AddServiceGroup;
final class AddServiceGroupRequest
{
public string $name = '';
public string $alias = '';
public ?string $geoCoords = null;
public string $comment = '';
public bool $isActivated = true;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceGroup/Application/UseCase/DeleteServiceGroup/DeleteServiceGroup.php | centreon/src/Core/ServiceGroup/Application/UseCase/DeleteServiceGroup/DeleteServiceGroup.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceGroup\Application\UseCase\DeleteServiceGroup;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Application\Common\UseCase\PresenterInterface;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\ServiceGroup\Application\Exception\ServiceGroupException;
use Core\ServiceGroup\Application\Repository\ReadServiceGroupRepositoryInterface;
use Core\ServiceGroup\Application\Repository\WriteServiceGroupRepositoryInterface;
use Throwable;
final class DeleteServiceGroup
{
use LoggerTrait;
public function __construct(
private readonly ReadServiceGroupRepositoryInterface $readServiceGroupRepository,
private readonly WriteServiceGroupRepositoryInterface $writeServiceGroupRepository,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly ContactInterface $contact,
) {
}
public function __invoke(int $serviceGroupId, PresenterInterface $presenter): void
{
try {
if ($this->contact->isAdmin()) {
$presenter->setResponseStatus($this->deleteServiceGroupAsAdmin($serviceGroupId));
} elseif ($this->contactCanExecuteThisUseCase()) {
$presenter->setResponseStatus($this->deleteServiceGroupAsContact($serviceGroupId));
} else {
$this->error(
"User doesn't have sufficient rights to see service groups",
['user_id' => $this->contact->getId()]
);
$presenter->setResponseStatus(
new ForbiddenResponse(ServiceGroupException::accessNotAllowedForWriting())
);
}
} catch (Throwable $ex) {
$presenter->setResponseStatus(new ErrorResponse(ServiceGroupException::errorWhileDeleting()));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
}
}
/**
* @param int $serviceGroupId
*
* @throws Throwable
*
* @return ResponseStatusInterface
*/
private function deleteServiceGroupAsAdmin(int $serviceGroupId): ResponseStatusInterface
{
if ($this->readServiceGroupRepository->existsOne($serviceGroupId)) {
$this->writeServiceGroupRepository->deleteServiceGroup($serviceGroupId);
return new NoContentResponse();
}
$this->warning('Service group (%s) not found', ['id' => $serviceGroupId]);
return new NotFoundResponse('Service group');
}
/**
* @param int $serviceGroupId
*
* @throws Throwable
*
* @return ResponseStatusInterface
*/
private function deleteServiceGroupAsContact(int $serviceGroupId): ResponseStatusInterface
{
$accessGroups = $this->readAccessGroupRepository->findByContact($this->contact);
if ($this->readServiceGroupRepository->existsOneByAccessGroups($serviceGroupId, $accessGroups)) {
$this->writeServiceGroupRepository->deleteServiceGroup($serviceGroupId);
return new NoContentResponse();
}
$this->warning('Service group (%s) not found', ['id' => $serviceGroupId]);
return new NotFoundResponse('Service group');
}
/**
* @return bool
*/
private function contactCanExecuteThisUseCase(): bool
{
return $this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_SERVICES_SERVICE_GROUPS_READ_WRITE);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceGroup/Application/Exception/ServiceGroupException.php | centreon/src/Core/ServiceGroup/Application/Exception/ServiceGroupException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceGroup\Application\Exception;
class ServiceGroupException extends \Exception
{
public const CODE_CONFLICT = 1;
/**
* @return self
*/
public static function accessNotAllowed(): self
{
return new self(_('You are not allowed to access service groups'));
}
/**
* @return self
*/
public static function accessNotAllowedForWriting(): self
{
return new self(_('You are not allowed to perform write operations on service groups'));
}
/**
* @return self
*/
public static function errorWhileSearching(): self
{
return new self(_('Error while searching for service groups'));
}
/**
* @return self
*/
public static function errorWhileDeleting(): self
{
return new self(_('Error while deleting a service group'));
}
/**
* @return self
*/
public static function errorWhileAdding(): self
{
return new self(_('Error while adding a service group'));
}
/**
* @return self
*/
public static function errorWhileRetrievingJustCreated(): self
{
return new self(_('Error while retrieving newly created service group'));
}
/**
* @param string $serviceGroupName
*
* @return self
*/
public static function nameAlreadyExists(string $serviceGroupName): self
{
return new self(sprintf(_("The service group name '%s' already exists"), $serviceGroupName), self::CODE_CONFLICT);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceGroup/Application/Repository/WriteServiceGroupRepositoryInterface.php | centreon/src/Core/ServiceGroup/Application/Repository/WriteServiceGroupRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceGroup\Application\Repository;
use Core\ServiceGroup\Domain\Model\NewServiceGroup;
use Core\ServiceGroup\Domain\Model\ServiceGroupRelation;
interface WriteServiceGroupRepositoryInterface
{
/**
* Delete a service group.
*
* @param int $serviceGroupId
*/
public function deleteServiceGroup(int $serviceGroupId): void;
/**
* @param NewServiceGroup $newServiceGroup
*
* @throws \Throwable
*
* @return int
*/
public function add(NewServiceGroup $newServiceGroup): int;
/**
* Create serviceGroup relation(s).
*
* @param ServiceGroupRelation[] $serviceGroupRelations
*
* @throws \Throwable
*/
public function link(array $serviceGroupRelations): void;
/**
* Remove serviceGroup relation(s).
*
* @param ServiceGroupRelation[] $serviceGroupRelations
*
* @throws \Throwable
*/
public function unlink(array $serviceGroupRelations): 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/ServiceGroup/Application/Repository/ReadServiceGroupRepositoryInterface.php | centreon/src/Core/ServiceGroup/Application/Repository/ReadServiceGroupRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceGroup\Application\Repository;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Core\ServiceGroup\Domain\Model\ServiceGroup;
use Core\ServiceGroup\Domain\Model\ServiceGroupNamesById;
use Core\ServiceGroup\Domain\Model\ServiceGroupRelation;
interface ReadServiceGroupRepositoryInterface
{
/**
* Find All service groups without acl.
*
* @param RequestParametersInterface|null $requestParameters
*
* @throws \Throwable
*
* @return \Traversable<int, ServiceGroup>&\Countable
*/
public function findAll(?RequestParametersInterface $requestParameters): \Traversable&\Countable;
/**
* Find All service groups with access groups.
*
* @param RequestParametersInterface|null $requestParameters
* @param int[] $accessGroupIds
*
* @throws \Throwable
*
* @return \Traversable<int, ServiceGroup>&\Countable
*/
public function findAllByAccessGroupIds(?RequestParametersInterface $requestParameters, array $accessGroupIds): \Traversable&\Countable;
/**
* Find service groups by their ID.
*
* @param int ...$serviceGroupIds
*
* @throws \Throwable
*
* @return list<ServiceGroup>
*/
public function findByIds(int ...$serviceGroupIds): array;
/**
* Find one service group without acl.
*
* @param int $serviceGroupId
*
* @throws \Throwable
*
* @return ServiceGroup|null
*/
public function findOne(int $serviceGroupId): ?ServiceGroup;
/**
* Find one service group with access groups.
*
* @param int $serviceGroupId
* @param AccessGroup[] $accessGroups
*
* @throws \Throwable
*
* @return ServiceGroup|null
*/
public function findOneByAccessGroups(int $serviceGroupId, array $accessGroups): ?ServiceGroup;
/**
* Tells whether the service group exists.
*
* @param int $serviceGroupId
*
* @throws \Throwable
*
* @return bool
*/
public function existsOne(int $serviceGroupId): bool;
/**
* Tells whether the service group exists but with access groups.
*
* @param int $serviceGroupId
* @param AccessGroup[] $accessGroups
*
* @throws \Throwable
*
* @return bool
*/
public function existsOneByAccessGroups(int $serviceGroupId, array $accessGroups): bool;
/**
* Tells whether the service group name already exists.
* This method does not need an acl version of it.
*
* @param string $serviceGroupName
*
* @throws \Throwable
*
* @return bool
*/
public function nameAlreadyExists(string $serviceGroupName): bool;
/**
* Find all existing service groups ids.
*
* @param list<int> $serviceGroupIds
*
* @throws \Throwable
*
* @return list<int>
*/
public function exist(array $serviceGroupIds): array;
/**
* Find all existing service groups ids and according to access groups.
*
* @param list<int> $serviceGroupIds
* @param AccessGroup[] $accessGroups
*
* @throws \Throwable
*
* @return list<int>
*/
public function existByAccessGroups(array $serviceGroupIds, array $accessGroups): array;
/**
* Find all service groups linked to a service.
*
* @param int $serviceId
*
* @throws \Throwable
*
* @return array<array{relation:ServiceGroupRelation,serviceGroup:ServiceGroup}>
*/
public function findByService(int $serviceId): array;
/**
* Find all service groups linked to a service and according to access groups.
*
* @param int $serviceId
* @param AccessGroup[] $accessGroups
*
* @throws \Throwable
*
* @return array<array{relation:ServiceGroupRelation,serviceGroup:ServiceGroup}>
*/
public function findByServiceAndAccessGroups(int $serviceId, array $accessGroups): array;
/**
* Find service group names by their IDs.
*
* @param int[] $serviceGroupIds
*
* @throws \Throwable
*
* @return ServiceGroupNamesById
*/
public function findNames(array $serviceGroupIds): ServiceGroupNamesById;
/**
* Determine if accessGroups give access to all serviceGroups
* true: all service groups are accessible
* false: all service groups are NOT accessible.
*
* @param int[] $accessGroupIds
*
* @return bool
*/
public function hasAccessToAllServiceGroups(array $accessGroupIds): bool;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceGroup/Domain/Model/ServiceGroupRelation.php | centreon/src/Core/ServiceGroup/Domain/Model/ServiceGroupRelation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceGroup\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
class ServiceGroupRelation
{
/**
* @param int $serviceGroupId
* @param int $serviceId (service ID or service template ID)
* @param null|int $hostId
* @param null|int $hostGroupId
*
* @throws AssertionFailedException
*/
public function __construct(
private int $serviceGroupId,
private int $serviceId,
private ?int $hostId = null,
private ?int $hostGroupId = null,
) {
Assertion::positiveInt($serviceGroupId, 'ServiceGroupRelation::serviceGroupId');
Assertion::positiveInt($serviceId, 'ServiceGroupRelation::serviceId');
if ($hostId !== null) {
Assertion::positiveInt($hostId, 'ServiceGroupRelation::hostId');
}
if ($hostGroupId !== null) {
Assertion::positiveInt($hostGroupId, 'ServiceGroupRelation::hostGroupId');
}
}
/**
* @return int
*/
public function getServiceGroupId(): int
{
return $this->serviceGroupId;
}
/**
* @return int
*/
public function getServiceId(): int
{
return $this->serviceId;
}
/**
* @return int
*/
public function getHostId(): ?int
{
return $this->hostId;
}
/**
* @return int|null
*/
public function getHostGroupId(): ?int
{
return $this->hostGroupId;
}
/**
* Extract all host IDs from an array of ServiceGroupRelation.
*
* @param ServiceGroupRelation[] $sgRelations
*
* @return int[]
*/
public static function getHostIds(array $sgRelations): array
{
$hostIds = [];
foreach ($sgRelations as $sgRel) {
if ($sgRel->getHostId() !== null) {
$hostIds[] = $sgRel->getHostId();
}
}
return $hostIds;
}
/**
* Extract all serviceGroup IDs from an array of ServiceGroupRelation.
*
* @param ServiceGroupRelation[] $sgRelations
*
* @return int[]
*/
public static function getServiceGroupIds(array $sgRelations): array
{
return array_map(fn (ServiceGroupRelation $sgRel) => $sgRel->getServiceGroupId(), $sgRelations);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceGroup/Domain/Model/ServiceGroupNamesById.php | centreon/src/Core/ServiceGroup/Domain/Model/ServiceGroupNamesById.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceGroup\Domain\Model;
use Core\Common\Domain\TrimmedString;
class ServiceGroupNamesById
{
/** @var array<int,TrimmedString> */
private array $names = [];
public function __construct()
{
}
/**
* @param int $groupId
* @param TrimmedString $groupName
*/
public function addName(int $groupId, TrimmedString $groupName): void
{
$this->names[$groupId] = $groupName;
}
/**
* @param int $groupId
*
* @return null|string
*/
public function getName(int $groupId): ?string
{
return isset($this->names[$groupId]) ? $this->names[$groupId]->value : null;
}
/**
* @return array<int,TrimmedString>
*/
public function getNames(): array
{
return $this->names;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceGroup/Domain/Model/NewServiceGroup.php | centreon/src/Core/ServiceGroup/Domain/Model/NewServiceGroup.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceGroup\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Core\Domain\Common\GeoCoords;
class NewServiceGroup
{
public const MAX_NAME_LENGTH = 200;
public const MIN_NAME_LENGTH = 1;
public const MAX_ALIAS_LENGTH = 200;
public const MIN_ALIAS_LENGTH = 1;
public const MAX_COMMENT_LENGTH = 65535;
/**
* @param string $name
* @param string $alias
* @param GeoCoords|null $geoCoords
* @param string $comment
* @param bool $isActivated
*
* @throws AssertionFailedException
*/
public function __construct(
protected string $name,
protected string $alias,
protected null|GeoCoords $geoCoords = null,
protected string $comment = '',
protected bool $isActivated = true,
) {
$shortName = (new \ReflectionClass($this))->getShortName();
$this->name = trim($this->name);
Assertion::minLength($this->name, self::MIN_NAME_LENGTH, "{$shortName}::name");
Assertion::maxLength($this->name, self::MAX_NAME_LENGTH, "{$shortName}::name");
$this->alias = trim($this->alias);
Assertion::maxLength($this->alias, self::MAX_ALIAS_LENGTH, "{$shortName}::alias");
Assertion::minLength($this->name, self::MIN_ALIAS_LENGTH, "{$shortName}::name");
$this->comment = trim($this->comment);
Assertion::maxLength($this->comment, self::MAX_COMMENT_LENGTH, "{$shortName}::comment");
}
public function getName(): string
{
return $this->name;
}
public function getAlias(): string
{
return $this->alias;
}
public function getComment(): string
{
return $this->comment;
}
public function isActivated(): bool
{
return $this->isActivated;
}
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/ServiceGroup/Domain/Model/ServiceGroup.php | centreon/src/Core/ServiceGroup/Domain/Model/ServiceGroup.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceGroup\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Core\Common\Domain\Comparable;
use Core\Common\Domain\Identifiable;
use Core\Domain\Common\GeoCoords;
class ServiceGroup extends NewServiceGroup implements Comparable, Identifiable
{
private int $id;
/**
* @param int $id
* @param string $name
* @param string $alias
* @param GeoCoords|null $geoCoords
* @param string $comment
* @param bool $isActivated
*
* @throws AssertionFailedException
*/
public function __construct(
int $id,
string $name,
string $alias,
null|GeoCoords $geoCoords,
string $comment,
bool $isActivated,
) {
Assertion::positiveInt($id, 'ServiceGroup::id');
$this->id = $id;
parent::__construct(
$name,
$alias,
$geoCoords,
$comment,
$isActivated,
);
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
public function isEqual(object $object): bool
{
return $object instanceof self && $object->getEqualityHash() === $this->getEqualityHash();
}
public function getEqualityHash(): string
{
return md5($this->name);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceGroup/Infrastructure/Repository/ApiReadServiceGroupRepository.php | centreon/src/Core/ServiceGroup/Infrastructure/Repository/ApiReadServiceGroupRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceGroup\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\ServiceGroup\Application\Repository\ReadServiceGroupRepositoryInterface;
use Core\ServiceGroup\Domain\Model\ServiceGroup;
use Core\ServiceGroup\Domain\Model\ServiceGroupNamesById;
use Psr\Log\LoggerInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class ApiReadServiceGroupRepository implements ReadServiceGroupRepositoryInterface
{
use ApiResponseTrait;
use ApiRepositoryTrait;
public function __construct(
private readonly HttpClientInterface $httpClient,
private readonly RouterInterface $router,
private readonly LoggerInterface $logger,
) {
}
/**
* @inheritDoc
*/
public function findAll(?RequestParametersInterface $requestParameters): \Traversable&\Countable
{
$apiEndpoint = $this->router->generate('FindServiceGroups');
$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 service groups using proxy');
}
$debugOptions = $options;
unset($debugOptions['headers'][0]);
$this->logger->debug('Connexion configuration', [
'url' => $apiEndpoint,
'options' => $debugOptions,
]);
return new ApiCallIterator(
$this->httpClient,
$this->url . $apiEndpoint,
$options,
$this->maxItemsByRequest,
ServiceGroupFactory::createFromApi(...),
$this->logger
);
}
/**
* @inheritDoc
*/
public function findAllByAccessGroupIds(?RequestParametersInterface $requestParameters, array $accessGroupIds): \Traversable&\Countable
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function findByIds(int ...$serviceGroupIds): array
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function findOne(int $serviceGroupId): ?ServiceGroup
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function findOneByAccessGroups(int $serviceGroupId, array $accessGroups): ?ServiceGroup
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function existsOne(int $serviceGroupId): bool
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function existsOneByAccessGroups(int $serviceGroupId, array $accessGroups): bool
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function nameAlreadyExists(string $serviceGroupName): bool
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function exist(array $serviceGroupIds): array
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function existByAccessGroups(array $serviceGroupIds, array $accessGroups): array
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function findByService(int $serviceId): array
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function findByServiceAndAccessGroups(int $serviceId, array $accessGroups): array
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function findNames(array $serviceGroupIds): ServiceGroupNamesById
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function hasAccessToAllServiceGroups(array $accessGroupIds): bool
{
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/ServiceGroup/Infrastructure/Repository/DbWriteServiceGroupRepository.php | centreon/src/Core/ServiceGroup/Infrastructure/Repository/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\ServiceGroup\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\RequestParameters\Normalizer\BoolToEnumNormalizer;
use Core\ServiceGroup\Application\Repository\WriteServiceGroupRepositoryInterface;
use Core\ServiceGroup\Domain\Model\NewServiceGroup;
use Core\ServiceGroup\Domain\Model\ServiceGroup;
class DbWriteServiceGroupRepository extends AbstractRepositoryRDB implements WriteServiceGroupRepositoryInterface
{
use RepositoryTrait;
use LoggerTrait;
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @param int $serviceGroupId
*
* @throws \PDOException
*/
public function deleteServiceGroup(int $serviceGroupId): void
{
$this->info('Delete service group', ['id' => $serviceGroupId]);
$query = <<<'SQL'
DELETE FROM `:db`.`servicegroup`
WHERE sg_id = :servicegroup_id
SQL;
$statement = $this->db->prepare($this->translateDbName($query));
$statement->bindValue(':servicegroup_id', $serviceGroupId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @inheritDoc
*/
public function add(NewServiceGroup $newServiceGroup): int
{
$insert = <<<'SQL'
INSERT INTO `:db`.`servicegroup`
(
sg_name,
sg_alias,
geo_coords,
sg_comment,
sg_activate
)
VALUES
(
:name,
:alias,
:geo_coords,
:comment,
:activate
)
SQL;
$statement = $this->db->prepare($this->translateDbName($insert));
$this->bindValueOfServiceGroup($statement, $newServiceGroup);
$statement->execute();
return (int) $this->db->lastInsertId();
}
/**
* @inheritDoc
*/
public function link(array $serviceGroupRelations): void
{
if ($serviceGroupRelations === []) {
return;
}
$request = <<<'SQL'
INSERT INTO `:db`.servicegroup_relation
(host_host_id, service_service_id, servicegroup_sg_id, hostgroup_hg_id)
VALUES (:host_id, :service_id, :servicegroup_id, :hostgroup_id)
SQL;
$alreadyInTransaction = $this->db->inTransaction();
try {
if (! $alreadyInTransaction) {
$this->db->beginTransaction();
}
$statement = $this->db->prepare($this->translateDbName($request));
$serviceId = null;
$serviceGroupId = null;
$hostId = null;
$hostGroupId = null;
$statement->bindParam(':service_id', $serviceId, \PDO::PARAM_INT);
$statement->bindParam(':servicegroup_id', $serviceGroupId, \PDO::PARAM_INT);
$statement->bindParam(':host_id', $hostId, \PDO::PARAM_INT);
$statement->bindParam(':hostgroup_id', $hostGroupId, \PDO::PARAM_INT);
foreach ($serviceGroupRelations as $serviceGroupRelation) {
$serviceId = $serviceGroupRelation->getServiceId();
$serviceGroupId = $serviceGroupRelation->getServiceGroupId();
$hostId = $serviceGroupRelation->getHostId();
$hostGroupId = $serviceGroupRelation->getHostGroupId();
$statement->execute();
}
if (! $alreadyInTransaction) {
$this->db->commit();
}
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
if (! $alreadyInTransaction) {
$this->db->rollBack();
}
throw $ex;
}
}
/**
* @inheritDoc
*/
public function unlink(array $serviceGroupRelations): void
{
if ($serviceGroupRelations === []) {
return;
}
$request = <<<'SQL'
DELETE FROM `:db`.servicegroup_relation
WHERE host_host_id = :host_id
AND service_service_id = :service_id
AND servicegroup_sg_id = :servicegroup_id
AND hostgroup_hg_id IS NULL
SQL;
$alreadyInTransaction = $this->db->inTransaction();
try {
if (! $alreadyInTransaction) {
$this->db->beginTransaction();
}
$statement = $this->db->prepare($this->translateDbName($request));
$serviceId = null;
$serviceGroupId = null;
$hostId = null;
$statement->bindParam(':service_id', $serviceId, \PDO::PARAM_INT);
$statement->bindParam(':servicegroup_id', $serviceGroupId, \PDO::PARAM_INT);
$statement->bindParam(':host_id', $hostId, \PDO::PARAM_INT);
foreach ($serviceGroupRelations as $serviceGroupRelation) {
$serviceId = $serviceGroupRelation->getServiceId();
$serviceGroupId = $serviceGroupRelation->getServiceGroupId();
$hostId = $serviceGroupRelation->getHostId();
$statement->execute();
}
if (! $alreadyInTransaction) {
$this->db->commit();
}
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
if (! $alreadyInTransaction) {
$this->db->rollBack();
}
throw $ex;
}
}
/**
* @param \PDOStatement $statement
* @param ServiceGroup|NewServiceGroup $newServiceGroup
*/
private function bindValueOfServiceGroup(\PDOStatement $statement, ServiceGroup|NewServiceGroup $newServiceGroup): void
{
$statement->bindValue(':name', $newServiceGroup->getName());
$statement->bindValue(':alias', $this->emptyStringAsNull($newServiceGroup->getAlias()));
$statement->bindValue(':geo_coords', $newServiceGroup->getGeoCoords()?->__toString());
$statement->bindValue(':comment', $this->emptyStringAsNull($newServiceGroup->getComment()));
$statement->bindValue(':activate', (new BoolToEnumNormalizer())->normalize($newServiceGroup->isActivated()));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceGroup/Infrastructure/Repository/DbReadServiceGroupRepository.php | centreon/src/Core/ServiceGroup/Infrastructure/Repository/DbReadServiceGroupRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceGroup\Infrastructure\Repository;
use Assert\AssertionFailedException;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use Core\Common\Domain\TrimmedString;
use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait;
use Core\Common\Infrastructure\RequestParameters\Normalizer\BoolToEnumNormalizer;
use Core\Domain\Exception\InvalidGeoCoordException;
use Core\Host\Infrastructure\Repository\HostRepositoryTrait;
use Core\HostCategory\Infrastructure\Repository\HostCategoryRepositoryTrait;
use Core\HostGroup\Infrastructure\Repository\HostGroupRepositoryTrait;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Core\ServiceCategory\Infrastructure\Repository\ServiceCategoryRepositoryTrait;
use Core\ServiceGroup\Application\Repository\ReadServiceGroupRepositoryInterface;
use Core\ServiceGroup\Domain\Model\ServiceGroup;
use Core\ServiceGroup\Domain\Model\ServiceGroupNamesById;
use Core\ServiceGroup\Domain\Model\ServiceGroupRelation;
use Utility\SqlConcatenator;
/**
* @phpstan-type ServiceGroupResultSet array{
* sg_id: int,
* sg_name: string,
* sg_alias: string,
* geo_coords: ?string,
* sg_comment: ?string,
* sg_activate: '0'|'1'
* }
*/
class DbReadServiceGroupRepository extends AbstractRepositoryDRB implements ReadServiceGroupRepositoryInterface
{
use SqlMultipleBindTrait;
use HostRepositoryTrait;
use HostGroupRepositoryTrait;
use ServiceCategoryRepositoryTrait;
use HostCategoryRepositoryTrait;
use ServiceGroupRepositoryTrait;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function findAll(?RequestParametersInterface $requestParameters): \Traversable&\Countable
{
$request = <<<'SQL'
SELECT
sg.sg_id,
sg.sg_name,
sg.sg_alias,
sg.geo_coords,
sg.sg_comment,
sg.sg_activate
FROM `:db`.servicegroup sg
SQL;
// Handle the request parameters if those are set
$sqlTranslator = $requestParameters ? new SqlRequestParametersTranslator($requestParameters) : null;
$sqlTranslator?->setConcordanceArray([
'id' => 'sg.sg_id',
'alias' => 'sg.sg_alias',
'name' => 'sg.sg_name',
'is_activated' => 'sg.sg_activate',
'host.id' => 'h.host_id',
'host.name' => 'h.host_name',
'hostgroup.id' => 'hg.hg_id',
'hostgroup.name' => 'hg.hg_name',
'hostcategory.id' => 'hc.hc_id',
'hostcategory.name' => 'hc.hc_name',
'servicecategory.id' => 'sc.sc_id',
'servicecategory.name' => 'sc.sc_name',
]);
$sqlTranslator?->addNormalizer('is_activated', new BoolToEnumNormalizer());
// Update the SQL string builder with the RequestParameters through SqlRequestParametersTranslator
$searchRequest = $sqlTranslator?->translateSearchParameterToSql();
if ($searchRequest !== null) {
$request .= <<<SQL
LEFT JOIN `:db`.servicegroup_relation sgr
ON sgr.servicegroup_sg_id = sg.sg_id
LEFT JOIN `:db`.host h
ON h.host_id = sgr.host_host_id
LEFT JOIN `:db`.service s
ON s.service_id = sgr.service_service_id
OR s.service_template_model_stm_id = sgr.service_service_id
LEFT JOIN `:db`.service_categories_relation scr
ON scr.service_service_id = s.service_id
LEFT JOIN `:db`.service_categories sc
ON sc.sc_id = scr.sc_id
LEFT JOIN `:db`.hostcategories_relation hcr
ON hcr.host_host_id = sgr.host_host_id
LEFT JOIN `:db`.hostcategories hc
ON hc.hc_id = hcr.hostcategories_hc_id
LEFT JOIN `:db`.hostgroup_relation hgr
ON hgr.hostgroup_hg_id = sgr.hostgroup_hg_id
LEFT JOIN `:db`.hostgroup hg
ON hg.hg_id = hgr.hostgroup_hg_id
{$searchRequest}
SQL;
}
// handle sort
$sortRequest = $sqlTranslator?->translateSortParameterToSql();
$request .= $sortRequest ?? ' ORDER BY sg.sg_name ASC';
// handle pagination
$request .= $sqlTranslator?->translatePaginationToSql();
// Prepare SQL + bind values
$statement = $this->db->prepare($this->translateDbName($request));
$sqlTranslator?->bindSearchValues($statement);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
// Calculate the number of rows for the pagination.
$sqlTranslator?->calculateNumberOfRows($this->db);
// Retrieve data
$serviceGroups = [];
foreach ($statement as $result) {
/** @var ServiceGroupResultSet $result */
$serviceGroups[] = ServiceGroupFactory::createFromDb($result);
}
return new \ArrayIterator($serviceGroups);
}
/**
* @inheritDoc
*/
public function findAllByAccessGroupIds(?RequestParametersInterface $requestParameters, array $accessGroupIds): \Traversable&\Countable
{
if ($accessGroupIds === []) {
return new \ArrayIterator([]);
}
$sqlTranslator = $requestParameters ? new SqlRequestParametersTranslator($requestParameters) : null;
[$bindValues, $bindQuery] = $this->createMultipleBindQuery($accessGroupIds, ':access_group_id_');
$request = <<<'SQL'
SELECT
sg.sg_id,
sg.sg_name,
sg.sg_alias,
sg.geo_coords,
sg.sg_comment,
sg.sg_activate
FROM `:db`.servicegroup sg
SQL;
$sqlTranslator?->setConcordanceArray([
'id' => 'sg.sg_id',
'alias' => 'sg.sg_alias',
'name' => 'sg.sg_name',
'is_activated' => 'sg.sg_activate',
'host.id' => 'h.host_id',
'host.name' => 'h.host_name',
'hostgroup.id' => 'hg.hg_id',
'hostgroup.name' => 'hg.hg_name',
'hostcategory.id' => 'hc.hc_id',
'hostcategory.name' => 'hc.hc_name',
'servicecategory.id' => 'sc.sc_id',
'servicecategory.name' => 'sc.sc_name',
]);
$sqlTranslator?->addNormalizer('is_activated', new BoolToEnumNormalizer());
$searchRequest = $sqlTranslator?->translateSearchParameterToSql();
// Do not join tables if no search provided...
if ($searchRequest !== null) {
$hostAcl = $this->generateHostAclSubRequest($accessGroupIds);
$serviceCategoryAcl = $this->generateServiceCategoryAclSubRequest($accessGroupIds);
$hostGroupAcl = $this->generateHostGroupAclSubRequest($accessGroupIds);
$hostCategoryAcl = $this->generateHostCategoryAclSubRequest($accessGroupIds);
$request .= <<<SQL
LEFT JOIN `:db`.servicegroup_relation sgr
ON sgr.servicegroup_sg_id = sg.sg_id
LEFT JOIN `:db`.host h
ON h.host_id = sgr.host_host_id
AND sgr.host_host_id IN ({$hostAcl})
LEFT JOIN `:db`.service_categories_relation scr
ON scr.service_service_id = sgr.service_service_id
LEFT JOIN `:db`.service_categories sc
ON sc.sc_id = scr.sc_id
AND scr.sc_id IN ({$serviceCategoryAcl})
LEFT JOIN `:db`.hostcategories_relation hcr
ON hcr.host_host_id = sgr.host_host_id
LEFT JOIN `:db`.hostcategories hc
ON hc.hc_id = hcr.hostcategories_hc_id
AND hcr.hostcategories_hc_id IN ({$hostCategoryAcl})
LEFT JOIN `:db`.hostgroup_relation hgr
ON hgr.hostgroup_hg_id = sgr.hostgroup_hg_id
LEFT JOIN `:db`.hostgroup hg
ON hg.hg_id = hgr.hostgroup_hg_id
AND hgr.hostgroup_hg_id IN ({$hostGroupAcl})
SQL;
}
$request .= <<<'SQL'
INNER JOIN `:db`.acl_resources_sg_relations arsr
ON sg.sg_id = arsr.sg_id
INNER JOIN `:db`.acl_resources res
ON arsr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_res_group_relations argr
ON res.acl_res_id = argr.acl_res_id
INNER JOIN `:db`.acl_groups ag
ON argr.acl_group_id = ag.acl_group_id
SQL;
$request .= $searchRequest ? $searchRequest . ' AND ' : ' WHERE ';
$request .= <<<SQL
ag.acl_group_id IN ({$bindQuery})
SQL;
// handle sort
$sortRequest = $sqlTranslator?->translateSortParameterToSql();
$request .= $sortRequest ?? ' ORDER BY sg.sg_name ASC';
// handle pagination
$request .= $sqlTranslator?->translatePaginationToSql();
// Prepare SQL + bind values
$statement = $this->db->prepare($this->translateDbName($request));
$sqlTranslator?->bindSearchValues($statement);
foreach ($bindValues as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
// Calculate the number of rows for the pagination.
$sqlTranslator?->calculateNumberOfRows($this->db);
// Retrieve data
$serviceGroups = [];
foreach ($statement as $result) {
/** @var ServiceGroupResultSet $result */
$serviceGroups[] = ServiceGroupFactory::createFromDb($result);
}
return new \ArrayIterator($serviceGroups);
}
/**
* @inheritDoc
*/
public function findOne(int $serviceGroupId): ?ServiceGroup
{
$concatenator = $this->getFindServiceGroupConcatenator();
return $this->retrieveServiceGroup($concatenator, $serviceGroupId);
}
/**
* @inheritDoc
*/
public function findOneByAccessGroups(int $serviceGroupId, array $accessGroups): ?ServiceGroup
{
if ($accessGroups === []) {
return null;
}
$accessGroupIds = $this->accessGroupsToIds($accessGroups);
if ($this->hasAccessToAllServiceGroups($accessGroupIds)) {
return $this->findOne($serviceGroupId);
}
$concatenator = $this->getFindServiceGroupConcatenator($accessGroupIds);
return $this->retrieveServiceGroup($concatenator, $serviceGroupId);
}
/**
* @inheritDoc
*/
public function existsOne(int $serviceGroupId): bool
{
$concatenator = $this->getFindServiceGroupConcatenator();
return $this->existsServiceGroup($concatenator, $serviceGroupId);
}
/**
* @inheritDoc
*/
public function existsOneByAccessGroups(int $serviceGroupId, array $accessGroups): bool
{
if ($accessGroups === []) {
return false;
}
$accessGroupIds = $this->accessGroupsToIds($accessGroups);
if ($this->hasAccessToAllServiceGroups($accessGroupIds)) {
return $this->existsOne($serviceGroupId);
}
$concatenator = $this->getFindServiceGroupConcatenator($accessGroupIds);
return $this->existsServiceGroup($concatenator, $serviceGroupId);
}
/**
* @inheritDoc
*/
public function nameAlreadyExists(string $serviceGroupName): bool
{
$statement = $this->db->prepare(
$this->translateDbName(
<<<'SQL'
SELECT 1 FROM `:db`.`servicegroup` WHERE sg_name = :name
SQL
)
);
$statement->bindValue(':name', $serviceGroupName);
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* @inheritDoc
*/
public function exist(array $serviceGroupIds): array
{
$concatenator = $this->getFindServiceGroupConcatenator();
return $this->existServiceGroup($concatenator, $serviceGroupIds);
}
/**
* @inheritDoc
*/
public function existByAccessGroups(array $serviceGroupIds, array $accessGroups): array
{
if ($accessGroups === []) {
return [];
}
$accessGroupIds = $this->accessGroupsToIds($accessGroups);
if ($this->hasAccessToAllServiceGroups($accessGroupIds)) {
return $this->exist($serviceGroupIds);
}
$concatenator = $this->getFindServiceGroupConcatenator($accessGroupIds);
return $this->existServiceGroup($concatenator, $serviceGroupIds);
}
/**
* @inheritDoc
*/
public function findByService(int $serviceId): array
{
$concatenator = $this->getFindServiceGroupConcatenator();
return $this->retrieveServiceGroupsByService($concatenator, $serviceId);
}
/**
* @inheritDoc
*/
public function findByServiceAndAccessGroups(int $serviceId, array $accessGroups): array
{
if ($accessGroups === []) {
return [];
}
$accessGroupIds = $this->accessGroupsToIds($accessGroups);
if ($this->hasAccessToAllServiceGroups($accessGroupIds)) {
return $this->findByService($serviceId);
}
$concatenator = $this->getFindServiceGroupConcatenator($accessGroupIds);
return $this->retrieveServiceGroupsByService($concatenator, $serviceId);
}
/**
* @inheritDoc
*/
public function findNames(array $serviceGroupIds): ServiceGroupNamesById
{
$concatenator = new SqlConcatenator();
$serviceGroupIds = array_unique($serviceGroupIds);
$concatenator->defineSelect(
<<<'SQL'
SELECT sg.sg_id, sg.sg_name
FROM `:db`.servicegroup sg
WHERE sg.sg_id IN (:serviceGroupIds)
SQL
);
$concatenator->storeBindValueMultiple(':serviceGroupIds', $serviceGroupIds, \PDO::PARAM_INT);
$statement = $this->db->prepare($this->translateDbName($concatenator->__toString()));
$concatenator->bindValuesToStatement($statement);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
$groupNames = new ServiceGroupNamesById();
foreach ($statement as $result) {
/** @var array{sg_id:int,sg_name:string} $result */
$groupNames->addName(
$result['sg_id'],
new TrimmedString($result['sg_name'])
);
}
return $groupNames;
}
/**
* @inheritDoc
*/
public function findByIds(int ...$serviceGroupIds): array
{
if ($serviceGroupIds === []) {
return [];
}
[$bindValues, $serviceGroupIdsQuery] = $this->createMultipleBindQuery($serviceGroupIds, ':id_');
$request = <<<SQL
SELECT
sg_id,
sg_name,
sg_alias,
geo_coords,
sg_comment,
sg_activate
FROM `:db`.`servicegroup`
WHERE sg_id IN ({$serviceGroupIdsQuery})
ORDER BY sg_id
SQL;
$statement = $this->db->prepare($this->translateDbName($request));
foreach ($bindValues as $bindKey => $serviceGroupId) {
$statement->bindValue($bindKey, $serviceGroupId, \PDO::PARAM_INT);
}
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
$serviceGroups = [];
/** @var ServiceGroupResultSet $result */
foreach ($statement as $result) {
$serviceGroups[] = ServiceGroupFactory::createFromDb($result);
}
return $serviceGroups;
}
/**
* @param list<int> $accessGroupIds
*
* @return SqlConcatenator
*/
private function getFindServiceGroupConcatenator(array $accessGroupIds = []): SqlConcatenator
{
$concatenator = (new SqlConcatenator())
->defineSelect(
<<<'SQL'
SELECT
sg.sg_id,
sg.sg_name,
sg.sg_alias,
sg.geo_coords,
sg.sg_comment,
sg.sg_activate
SQL
)
->defineFrom(
<<<'SQL'
FROM
`:db`.`servicegroup` sg
SQL
)
->defineOrderBy(
<<<'SQL'
ORDER BY sg.sg_name ASC
SQL
);
if ($accessGroupIds !== []) {
$concatenator
->appendJoins(
<<<'SQL'
INNER JOIN `:db`.acl_resources_sg_relations arsr
ON sg.sg_id = arsr.sg_id
INNER JOIN `:db`.acl_resources res
ON arsr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_res_group_relations argr
ON res.acl_res_id = argr.acl_res_id
INNER JOIN `:db`.acl_groups ag
ON argr.acl_group_id = ag.acl_group_id
SQL
)
->appendWhere(
<<<'SQL'
WHERE ag.acl_group_id IN (:ids)
SQL
)
->storeBindValueMultiple(':ids', $accessGroupIds, \PDO::PARAM_INT);
}
return $concatenator;
}
/**
* @param non-empty-list<AccessGroup> $accessGroups
*
* @return non-empty-list<int>
*/
private function accessGroupsToIds(array $accessGroups): array
{
return array_map(
static fn (AccessGroup $accessGroup) => $accessGroup->getId(),
$accessGroups
);
}
/**
* @param SqlConcatenator $concatenator
* @param int $serviceGroupId
*
* @throws \PDOException
*
* @return bool
*/
private function existsServiceGroup(SqlConcatenator $concatenator, int $serviceGroupId): bool
{
$concatenator
// We override the select because we just need to get the ID to check the existence.
->defineSelect(
<<<'SQL'
SELECT 1
SQL
)
// We add the filtering by service group id.
->appendWhere(
<<<'SQL'
WHERE sg.sg_id = :servicegroup_id
SQL
)
->storeBindValue(':servicegroup_id', $serviceGroupId, \PDO::PARAM_INT);
// Prepare SQL + bind values
$statement = $this->db->prepare($this->translateDbName($concatenator->concatAll()));
$concatenator->bindValuesToStatement($statement);
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* @param SqlConcatenator $concatenator
* @param int[] $serviceGroupIds
*
* @throws \PDOException
*
* @return int[]
*/
private function existServiceGroup(SqlConcatenator $concatenator, array $serviceGroupIds): array
{
$concatenator
->defineSelect(
<<<'SQL'
SELECT sg.sg_id
SQL
)
->appendWhere(
<<<'SQL'
WHERE sg.sg_id IN (:servicegroup_ids)
SQL
)
->storeBindValueMultiple(':servicegroup_ids', $serviceGroupIds, \PDO::PARAM_INT);
$statement = $this->db->prepare($this->translateDbName($concatenator->concatAll()));
$concatenator->bindValuesToStatement($statement);
$statement->execute();
return $statement->fetchAll(\PDO::FETCH_COLUMN);
}
/**
* @param SqlConcatenator $concatenator
* @param int $serviceGroupId
*
* @throws InvalidGeoCoordException
* @throws \PDOException
* @throws AssertionFailedException
*
* @return ServiceGroup|null
*/
private function retrieveServiceGroup(SqlConcatenator $concatenator, int $serviceGroupId): ?ServiceGroup
{
// We add the filtering by service group id.
$concatenator
->appendWhere(
<<<'SQL'
WHERE sg.sg_id = :servicegroup_id
SQL
)
->storeBindValue(':servicegroup_id', $serviceGroupId, \PDO::PARAM_INT);
// Prepare SQL + bind values
$statement = $this->db->prepare($this->translateDbName($concatenator->concatAll()));
$concatenator->bindValuesToStatement($statement);
$statement->execute();
// Retrieve the first row
/** @var null|false|ServiceGroupResultSet $data */
$data = $statement->fetch(\PDO::FETCH_ASSOC);
return $data ? ServiceGroupFactory::createFromDb($data) : null;
}
/**
* @param SqlConcatenator $concatenator
* @param int $serviceId
*
* @throws InvalidGeoCoordException
* @throws \PDOException
* @throws AssertionFailedException
*
* @return array<array{relation:ServiceGroupRelation,serviceGroup:ServiceGroup}>
*/
private function retrieveServiceGroupsByService(SqlConcatenator $concatenator, int $serviceId): array
{
$concatenator
->appendSelect(
<<<'SQL'
sgr.host_host_id
SQL
)
->appendJoins(
<<<'SQL'
INNER JOIN `:db`.servicegroup_relation sgr
ON sgr.servicegroup_sg_id = sg.sg_id
SQL
)
->appendWhere(
<<<'SQL'
WHERE sgr.service_service_id = :service_id
SQL
)
->storeBindValue(':service_id', $serviceId, \PDO::PARAM_INT);
$statement = $this->db->prepare($this->translateDbName($concatenator->concatAll()));
$concatenator->bindValuesToStatement($statement);
$statement->execute();
$serviceGroups = [];
while (is_array($result = $statement->fetch(\PDO::FETCH_ASSOC))) {
/** @var array{
* sg_id:int,
* sg_name:string,
* sg_alias:string,
* geo_coords:string|null,
* sg_comment:string|null,
* sg_activate:'0'|'1',
* host_host_id:int
* } $result */
$serviceGroups[] = [
'relation' => new ServiceGroupRelation(
serviceGroupId: $result['sg_id'],
serviceId: $serviceId,
hostId: $result['host_host_id'],
),
'serviceGroup' => ServiceGroupFactory::createFromDb($result),
];
}
return $serviceGroups;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceGroup/Infrastructure/Repository/ServiceGroupFactory.php | centreon/src/Core/ServiceGroup/Infrastructure/Repository/ServiceGroupFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceGroup\Infrastructure\Repository;
use Assert\AssertionFailedException;
use Core\Domain\Common\GeoCoords;
use Core\ServiceGroup\Domain\Model\ServiceGroup;
/**
* @phpstan-import-type ServiceGroupResultSet from DbReadServiceGroupRepository
*/
class ServiceGroupFactory
{
/**
* @param ServiceGroupResultSet $data
*
* @throws AssertionFailedException
*
* @return ServiceGroup
*/
public static function createFromDb(array $data): ServiceGroup
{
return new ServiceGroup(
$data['sg_id'],
$data['sg_name'],
$data['sg_alias'],
match ($geoCoords = $data['geo_coords']) {
null, '' => null,
default => GeoCoords::fromString($geoCoords),
},
(string) $data['sg_comment'],
(bool) $data['sg_activate'],
);
}
/**
* @param array{
* id: int,
* name: string,
* alias: string,
* geo_coords: string|null,
* comment: string|null,
* is_activated: bool
* } $data
*
* @throws AssertionFailedException
*
* @return ServiceGroup
*/
public static function createFromApi(array $data): ServiceGroup
{
return new ServiceGroup(
$data['id'],
$data['name'],
$data['alias'],
match ($geoCoords = $data['geo_coords']) {
null, '' => null,
default => GeoCoords::fromString($geoCoords),
},
(string) $data['comment'],
(bool) $data['is_activated'],
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceGroup/Infrastructure/Repository/ServiceGroupRepositoryTrait.php | centreon/src/Core/ServiceGroup/Infrastructure/Repository/ServiceGroupRepositoryTrait.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceGroup\Infrastructure\Repository;
trait ServiceGroupRepositoryTrait
{
/**
* Determine if accessGroups give access to all serviceGroups
* true: all service groups are accessible
* false: all service groups are NOT accessible.
*
* @param int[] $accessGroupIds
*
* @return bool
*/
public function hasAccessToAllServiceGroups(array $accessGroupIds): bool
{
if ($accessGroupIds === []) {
return false;
}
[$bindValues, $bindQuery] = $this->createMultipleBindQuery($accessGroupIds, ':access_group_id_');
$request = <<<SQL
SELECT res.all_servicegroups
FROM `:db`.acl_resources res
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 res.acl_res_activate = '1' AND ag.acl_group_id IN ({$bindQuery})
SQL;
$statement = $this->db->prepare($this->translateDbName($request));
foreach ($bindValues as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->execute();
while (false !== ($hasAccessToAll = $statement->fetchColumn())) {
if ((bool) $hasAccessToAll === true) {
return true;
}
}
return 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/ServiceGroup/Infrastructure/API/FindServiceGroups/FindServiceGroupsController.php | centreon/src/Core/ServiceGroup/Infrastructure/API/FindServiceGroups/FindServiceGroupsController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceGroup\Infrastructure\API\FindServiceGroups;
use Centreon\Application\Controller\AbstractController;
use Core\ServiceGroup\Application\UseCase\FindServiceGroups\FindServiceGroups;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class FindServiceGroupsController extends AbstractController
{
/**
* @param FindServiceGroups $useCase
* @param FindServiceGroupsPresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
FindServiceGroups $useCase,
FindServiceGroupsPresenter $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/ServiceGroup/Infrastructure/API/FindServiceGroups/FindServiceGroupsPresenter.php | centreon/src/Core/ServiceGroup/Infrastructure/API/FindServiceGroups/FindServiceGroupsPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceGroup\Infrastructure\API\FindServiceGroups;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Infrastructure\Common\Presenter\PresenterTrait;
use Core\ServiceGroup\Application\UseCase\FindServiceGroups\FindServiceGroupsResponse;
class FindServiceGroupsPresenter extends AbstractPresenter
{
use PresenterTrait;
public function __construct(
protected RequestParametersInterface $requestParameters,
protected PresenterFormatterInterface $presenterFormatter,
) {
parent::__construct($presenterFormatter);
}
/**
* {@inheritDoc}
*
* @param FindServiceGroupsResponse $data
*/
public function present(mixed $data): void
{
$result = [];
foreach ($data->servicegroups as $servicegroup) {
$result[] = [
'id' => $servicegroup['id'],
'name' => $servicegroup['name'],
'alias' => $servicegroup['alias'],
'geo_coords' => $servicegroup['geoCoords'],
'comment' => $this->emptyStringAsNull($servicegroup['comment']),
'is_activated' => $servicegroup['isActivated'],
];
}
parent::present([
'result' => $result,
'meta' => $this->requestParameters->toArray(),
]);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceGroup/Infrastructure/API/AddServiceGroup/AddServiceGroupController.php | centreon/src/Core/ServiceGroup/Infrastructure/API/AddServiceGroup/AddServiceGroupController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceGroup\Infrastructure\API\AddServiceGroup;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\ServiceGroup\Application\UseCase\AddServiceGroup\AddServiceGroup;
use Core\ServiceGroup\Application\UseCase\AddServiceGroup\AddServiceGroupRequest;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class AddServiceGroupController extends AbstractController
{
use LoggerTrait;
/**
* @param Request $request
* @param AddServiceGroup $useCase
* @param AddServiceGroupPresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
Request $request,
AddServiceGroup $useCase,
AddServiceGroupPresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForAPIConfiguration();
try {
/** @var array{
* name: string,
* alias: string,
* geo_coords?: ?string,
* comment?: ?string,
* is_activated?: bool
* } $dataSent
*/
$dataSent = $this->validateAndRetrieveDataSent($request, __DIR__ . '/AddServiceGroupSchema.json');
$dto = new AddServiceGroupRequest();
$dto->name = $dataSent['name'];
$dto->alias = $dataSent['alias'];
$dto->geoCoords = $dataSent['geo_coords'] ?? null;
$dto->comment = $dataSent['comment'] ?? '';
$dto->isActivated = $dataSent['is_activated'] ?? true;
$useCase($dto, $presenter);
} catch (\InvalidArgumentException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
}
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/ServiceGroup/Infrastructure/API/AddServiceGroup/AddServiceGroupPresenter.php | centreon/src/Core/ServiceGroup/Infrastructure/API/AddServiceGroup/AddServiceGroupPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceGroup\Infrastructure\API\AddServiceGroup;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\CreatedResponse;
use Core\Infrastructure\Common\Presenter\PresenterTrait;
use Core\ServiceGroup\Application\UseCase\AddServiceGroup\AddServiceGroupResponse;
class AddServiceGroupPresenter extends AbstractPresenter
{
use PresenterTrait;
use LoggerTrait;
/**
* {@inheritDoc}
*/
public function present(mixed $data): void
{
if (
$data instanceof CreatedResponse
&& ($payload = $data->getPayload()) instanceof AddServiceGroupResponse
) {
parent::present($this->presentCreatedPayload($data, $payload));
} else {
parent::present($data);
}
}
/**
* @param CreatedResponse<int, AddServiceGroupResponse> $createdResponse
* @param AddServiceGroupResponse $addServiceGroupResponse
*
* @return CreatedResponse<int, array{
* id: int,
* name: string,
* alias: string|null,
* geo_coords: string|null,
* comment: string|null,
* is_activated: bool,
* }>
*/
private function presentCreatedPayload(
CreatedResponse $createdResponse,
AddServiceGroupResponse $addServiceGroupResponse,
): CreatedResponse {
return $createdResponse->withPayload(
[
'id' => $addServiceGroupResponse->id,
'name' => $addServiceGroupResponse->name,
'alias' => $this->emptyStringAsNull($addServiceGroupResponse->alias),
'geo_coords' => $addServiceGroupResponse->geoCoords,
'comment' => $this->emptyStringAsNull($addServiceGroupResponse->comment),
'is_activated' => $addServiceGroupResponse->isActivated,
]
);
// 👉️ We SHOULD send a valid header 'Location: <url>'.
// But the GET api is not available at the time this UseCase was written.
// This is nonsense to send something not usable.
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ServiceGroup/Infrastructure/API/DeleteServiceGroup/DeleteServiceGroupController.php | centreon/src/Core/ServiceGroup/Infrastructure/API/DeleteServiceGroup/DeleteServiceGroupController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\ServiceGroup\Infrastructure\API\DeleteServiceGroup;
use Centreon\Application\Controller\AbstractController;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\ServiceGroup\Application\UseCase\DeleteServiceGroup\DeleteServiceGroup;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class DeleteServiceGroupController extends AbstractController
{
/**
* @param int $serviceGroupId
* @param DeleteServiceGroup $useCase
* @param DefaultPresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
int $serviceGroupId,
DeleteServiceGroup $useCase,
DefaultPresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForAPIConfiguration();
$useCase($serviceGroupId, $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/Connector/Application/UseCase/FindConnectors/ConnectorDto.php | centreon/src/Core/Connector/Application/UseCase/FindConnectors/ConnectorDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Connector\Application\UseCase\FindConnectors;
use Core\Command\Domain\Model\CommandType;
class ConnectorDto
{
public int $id = 0;
public string $name = '';
public string $commandLine = '';
public string $description = '';
public bool $isActivated = true;
/** @var array<array{id:int,name:string,type:CommandType}> */
public array $commands = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Connector/Application/UseCase/FindConnectors/FindConnectorsResponse.php | centreon/src/Core/Connector/Application/UseCase/FindConnectors/FindConnectorsResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Connector\Application\UseCase\FindConnectors;
final class FindConnectorsResponse
{
/** @var ConnectorDto[] */
public array $connectors = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Connector/Application/UseCase/FindConnectors/FindConnectors.php | centreon/src/Core/Connector/Application/UseCase/FindConnectors/FindConnectors.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Connector\Application\UseCase\FindConnectors;
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\Command\Application\Repository\ReadCommandRepositoryInterface;
use Core\Command\Domain\Model\Command;
use Core\Command\Domain\Model\CommandType;
use Core\Connector\Application\Exception\ConnectorException;
use Core\Connector\Application\Repository\ReadConnectorRepositoryInterface;
use Core\Connector\Domain\Model\Connector;
final class FindConnectors
{
use LoggerTrait;
public function __construct(
private readonly RequestParametersInterface $requestParameters,
private readonly ReadConnectorRepositoryInterface $readConnectorRepository,
private readonly ReadCommandRepositoryInterface $readCommandRepository,
private readonly ContactInterface $contact,
) {
}
/**
* @param FindConnectorsPresenterInterface $presenter
*/
public function __invoke(FindConnectorsPresenterInterface $presenter): void
{
try {
if (
! $this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_CONNECTORS_RW)
&& ! $this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_CONNECTORS_R)
) {
$this->error(
"User doesn't have sufficient rights to see connectors",
['user_id' => $this->contact->getId()]
);
$presenter->presentResponse(
new ForbiddenResponse(ConnectorException::accessNotAllowed())
);
return;
}
$connectors = $this->readConnectorRepository->findByRequestParametersAndCommandTypes(
$this->requestParameters,
$this->retrieveConnectorTypesBasedOnContactRights(),
);
$commandIds = [];
foreach ($connectors as $connector) {
array_push($commandIds, ...$connector->getCommandIds());
}
$commands = [];
if ($commandIds !== []) {
$commands = $this->readCommandRepository->findByIds($commandIds);
}
$presenter->presentResponse($this->createResponse($connectors, $commands));
} catch (RequestParametersTranslatorException $ex) {
$presenter->presentResponse(new ErrorResponse($ex->getMessage()));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (\Throwable $ex) {
$presenter->presentResponse(new ErrorResponse(ConnectorException::errorWhileSearching($ex)));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
}
}
/**
* @param Connector[] $connectors
* @param Command[] $commands
*
* @return FindConnectorsResponse
*/
private function createResponse(array $connectors, array $commands): FindConnectorsResponse
{
$response = new FindConnectorsResponse();
foreach ($connectors as $connector) {
$connectorDto = new ConnectorDto();
$connectorDto->id = $connector->getId();
$connectorDto->name = $connector->getName();
$connectorDto->commandLine = $connector->getCommandLine();
$connectorDto->description = $connector->getDescription();
$connectorDto->isActivated = $connector->isActivated();
$connectorDto->commands = array_map(
fn (int $commandId) => [
'id' => $commands[$commandId]->getId(),
'name' => $commands[$commandId]->getName(),
'type' => $commands[$commandId]->getType(),
],
$connector->getCommandIds()
);
$response->connectors[] = $connectorDto;
}
return $response;
}
/**
* @return CommandType[]
*/
private function retrieveConnectorTypesBasedOnContactRights(): array
{
if ($this->contact->isAdmin()) {
return [
CommandType::Notification,
CommandType::Check,
CommandType::Miscellaneous,
CommandType::Discovery,
];
}
$commandsTypes = [];
if (
$this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_COMMANDS_CHECKS_R)
|| $this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_COMMANDS_CHECKS_RW)
) {
$commandsTypes[] = CommandType::Check;
}
if (
$this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_COMMANDS_NOTIFICATIONS_R)
|| $this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_COMMANDS_NOTIFICATIONS_RW)
) {
$commandsTypes[] = CommandType::Notification;
}
if (
$this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_COMMANDS_MISCELLANEOUS_R)
|| $this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_COMMANDS_MISCELLANEOUS_RW)
) {
$commandsTypes[] = CommandType::Miscellaneous;
}
if (
$this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_COMMANDS_DISCOVERY_R)
|| $this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_COMMANDS_DISCOVERY_RW)
) {
$commandsTypes[] = CommandType::Discovery;
}
return $commandsTypes;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Connector/Application/UseCase/FindConnectors/FindConnectorsPresenterInterface.php | centreon/src/Core/Connector/Application/UseCase/FindConnectors/FindConnectorsPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Connector\Application\UseCase\FindConnectors;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface FindConnectorsPresenterInterface
{
public function presentResponse(FindConnectorsResponse|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/Connector/Application/Exception/ConnectorException.php | centreon/src/Core/Connector/Application/Exception/ConnectorException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Connector\Application\Exception;
final class ConnectorException extends \Exception
{
/**
* @return self
*/
public static function accessNotAllowed(): self
{
return new self(_('You are not allowed to access connectors'));
}
/**
* @param \Throwable $ex
*
* @return self
*/
public static function errorWhileSearching(\Throwable $ex): self
{
return new self(_('Error while searching for connectors'), 0, $ex);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Connector/Application/Repository/ReadConnectorRepositoryInterface.php | centreon/src/Core/Connector/Application/Repository/ReadConnectorRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Connector\Application\Repository;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Command\Domain\Model\CommandType;
use Core\Connector\Domain\Model\Connector;
interface ReadConnectorRepositoryInterface
{
/**
* Determine if a connector exists by its ID.
*
* @param int $id
*
* @throws \Throwable
*
* @return bool
*/
public function exists(int $id): bool;
/**
* Search for all connectors based on request parameters and filter their commands on command types.
*
* @param RequestParametersInterface $requestParameters
* @param CommandType[] $commandTypes
*
* @throws \Throwable
*
* @return Connector[]
*/
public function findByRequestParametersAndCommandTypes(
RequestParametersInterface $requestParameters,
array $commandTypes,
): array;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Connector/Domain/Model/Connector.php | centreon/src/Core/Connector/Domain/Model/Connector.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Connector\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
class Connector
{
public const COMMAND_MAX_LENGTH = 512;
public const NAME_MAX_LENGTH = 255;
public const DESCRIPTION_MAX_LENGTH = 255;
/**
* Summary of __construct.
*
* @param int $id
* @param string $name
* @param string $commandLine
* @param string $description
* @param int[] $commandIds
* @param bool $isActivated
*
* @throws AssertionFailedException
*/
public function __construct(
private readonly int $id,
private string $name,
private string $commandLine,
private string $description = '',
private array $commandIds = [],
private bool $isActivated = true,
) {
Assertion::positiveInt($id, 'Connector::id');
$this->name = trim($name);
Assertion::notEmptyString($this->name, 'Connector::name');
Assertion::maxLength($this->name, self::NAME_MAX_LENGTH, 'Connector::name');
$this->commandLine = trim($commandLine);
Assertion::notEmptyString($this->commandLine, 'Connector::commandLine');
Assertion::maxLength($this->commandLine, self::COMMAND_MAX_LENGTH, 'Connector::commandLine');
$this->description = trim($description);
Assertion::maxLength($this->description, self::DESCRIPTION_MAX_LENGTH, 'Connector::description');
}
public function getId(): int
{
return $this->id;
}
public function getName(): string
{
return $this->name;
}
public function getCommandLine(): string
{
return $this->commandLine;
}
public function getDescription(): string
{
return $this->description;
}
public function isActivated(): bool
{
return $this->isActivated;
}
/**
* @return int[]
*/
public function getCommandIds(): array
{
return $this->commandIds;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Connector/Infrastructure/Repository/DbReadConnectorRepository.php | centreon/src/Core/Connector/Infrastructure/Repository/DbReadConnectorRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Connector\Infrastructure\Repository;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use Core\Command\Domain\Model\CommandType;
use Core\Command\Infrastructure\Model\CommandTypeConverter;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Connector\Application\Repository\ReadConnectorRepositoryInterface;
use Core\Connector\Domain\Model\Connector;
use Utility\SqlConcatenator;
/**
* @phpstan-type _Connector array{
* id: int,
* name: string,
* command_line: string,
* description: string|null,
* enabled: int,
* command_ids:string|null
* }
*/
class DbReadConnectorRepository extends AbstractRepositoryRDB implements ReadConnectorRepositoryInterface
{
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function exists(int $id): bool
{
$request = $this->translateDbName(
<<<'SQL'
SELECT 1
FROM `:db`.connector
WHERE id = :id
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':id', $id, \PDO::PARAM_INT);
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* @inheritDoc
*/
public function findByRequestParametersAndCommandTypes(
RequestParametersInterface $requestParameters,
array $commandTypes,
): array {
$sqlTranslator = new SqlRequestParametersTranslator($requestParameters);
$sqlTranslator->getRequestParameters()->setConcordanceStrictMode(RequestParameters::CONCORDANCE_MODE_STRICT);
$sqlTranslator->setConcordanceArray([
'id' => 'connector.id',
'name' => 'connector.name',
'command.id' => 'command.command_id',
'command.name' => 'command.command_name',
]);
$commandTypeFilter = '';
if ($commandTypes !== []) {
$commandTypeFilter = <<<'SQL'
AND `command`.command_type IN (:command_type)
SQL;
}
$request = <<<SQL
SELECT
`connector`.id,
`connector`.name,
`connector`.command_line,
`connector`.description,
`connector`.enabled,
GROUP_CONCAT(DISTINCT `command`.command_id) AS command_ids
FROM `:db`.`connector`
LEFT JOIN `:db`.`command`
ON `command`.connector_id = `connector`.id
{$commandTypeFilter}
SQL;
$sqlConcatenator = new SqlConcatenator();
$sqlConcatenator->defineSelect($request);
$sqlConcatenator->appendGroupBy(
<<<'SQL'
GROUP BY `connector`.id
SQL
);
if ($commandTypes !== []) {
$sqlConcatenator->storeBindValueMultiple(
':command_type',
array_map(
fn (CommandType $commandType): int => CommandTypeConverter::toInt($commandType),
$commandTypes
),
\PDO::PARAM_INT
);
}
$sqlTranslator->translateForConcatenator($sqlConcatenator);
$statement = $this->db->prepare($this->translateDbName((string) $sqlConcatenator));
$sqlTranslator->bindSearchValues($statement);
$sqlConcatenator->bindValuesToStatement($statement);
$statement->execute();
$sqlTranslator->calculateNumberOfRows($this->db);
$connectors = [];
while ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
/** @var _Connector $result */
$connectors[] = new Connector(
id: $result['id'],
name: $result['name'],
commandLine: $result['command_line'],
description: $result['description'] ?? '',
isActivated: (bool) $result['enabled'],
commandIds: $result['command_ids']
? array_map(fn (string $commandId) => (int) $commandId, explode(',', $result['command_ids']))
: []
);
}
return $connectors;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Connector/Infrastructure/API/FindConnectors/FindConnectorsPresenter.php | centreon/src/Core/Connector/Infrastructure/API/FindConnectors/FindConnectorsPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Connector\Infrastructure\API\FindConnectors;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Command\Infrastructure\Model\CommandTypeConverter;
use Core\Connector\Application\UseCase\FindConnectors\FindConnectorsPresenterInterface;
use Core\Connector\Application\UseCase\FindConnectors\FindConnectorsResponse;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Infrastructure\Common\Presenter\PresenterTrait;
class FindConnectorsPresenter extends AbstractPresenter implements FindConnectorsPresenterInterface
{
use PresenterTrait;
public function __construct(
private readonly RequestParametersInterface $requestParameters,
protected PresenterFormatterInterface $presenterFormatter,
) {
parent::__construct($presenterFormatter);
}
public function presentResponse(ResponseStatusInterface|FindConnectorsResponse $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
$result = [];
foreach ($response->connectors as $connector) {
$result[] = [
'id' => $connector->id,
'name' => $connector->name,
'command_line' => $connector->commandLine,
'description' => $this->emptyStringAsNull($connector->description),
'commands' => array_map(
fn (array $command) => [
'id' => $command['id'],
'type' => CommandTypeConverter::toInt($command['type']),
'name' => $command['name'],
],
$connector->commands
),
'is_activated' => $connector->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/Connector/Infrastructure/API/FindConnectors/FindConnectorsController.php | centreon/src/Core/Connector/Infrastructure/API/FindConnectors/FindConnectorsController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Connector\Infrastructure\API\FindConnectors;
use Centreon\Application\Controller\AbstractController;
use Core\Connector\Application\UseCase\FindConnectors\FindConnectors;
use Core\Connector\Application\UseCase\FindConnectors\FindConnectorsPresenterInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class FindConnectorsController extends AbstractController
{
/**
* @param FindConnectors $useCase
* @param FindConnectorsPresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(FindConnectors $useCase, FindConnectorsPresenterInterface $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/Domain/RealTime/ResourceTypeInterface.php | centreon/src/Core/Domain/RealTime/ResourceTypeInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\RealTime;
interface ResourceTypeInterface
{
/**
* @return int
*/
public function getId(): int;
/**
* @return string
*/
public function getName(): string;
/**
* @param string $typeName
*
* @return bool
*/
public function isValidForTypeName(string $typeName): bool;
/**
* @param int $typeId
*
* @return bool
*/
public function isValidForTypeId(int $typeId): bool;
/**
* @return bool
*/
public function hasParent(): bool;
/**
* @return bool
*/
public function hasInternalId(): bool;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Domain/RealTime/Model/IndexData.php | centreon/src/Core/Domain/RealTime/Model/IndexData.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\RealTime\Model;
class IndexData
{
/**
* @param string $hostName
* @param string $serviceDescription
*/
public function __construct(private string $hostName, private string $serviceDescription)
{
}
/**
* @return string
*/
public function getHostName(): string
{
return $this->hostName;
}
/**
* @return string
*/
public function getServiceDescription(): string
{
return $this->serviceDescription;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Domain/RealTime/Model/Icon.php | centreon/src/Core/Domain/RealTime/Model/Icon.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\RealTime\Model;
class Icon
{
/** @var int|null */
private $id;
/** @var string|null */
private $name;
/** @var string|null */
private $url;
/**
* @return string|null
*/
public function getName(): ?string
{
return $this->name;
}
/**
* @param string|null $name
*
* @return self
*/
public function setName(?string $name): self
{
$this->name = $name;
return $this;
}
/**
* @return string|null
*/
public function getUrl(): ?string
{
return $this->url;
}
/**
* @param string|null $url
*
* @return self
*/
public function setUrl(?string $url): self
{
$this->url = $url;
return $this;
}
/**
* @param int|null $id
*
* @return self
*/
public function setId(?int $id): self
{
$this->id = $id;
return $this;
}
/**
* @return int|null
*/
public function getId(): ?int
{
return $this->id;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Domain/RealTime/Model/Servicegroup.php | centreon/src/Core/Domain/RealTime/Model/Servicegroup.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\RealTime\Model;
class Servicegroup
{
/**
* @param int $id
* @param string $name
*/
public function __construct(
private int $id,
private string $name,
) {
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Domain/RealTime/Model/Acknowledgement.php | centreon/src/Core/Domain/RealTime/Model/Acknowledgement.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\RealTime\Model;
class Acknowledgement
{
// Types
public const TYPE_HOST_ACKNOWLEDGEMENT = 0;
public const TYPE_SERVICE_ACKNOWLEDGEMENT = 1;
/** @var int|null */
private $instanceId;
/** @var int|null */
private $authorId;
/** @var string|null */
private $authorName;
/** @var string|null */
private $comment;
/** @var \DateTime|null */
private $deletionTime;
/** @var bool */
private $isNotifyContacts = true;
/** @var bool */
private $isPersistentComment = true;
/** @var bool */
private $isSticky = true;
/** @var int|null */
private $state;
/** @var int|null */
private $type;
/** @var bool */
private $withServices = false;
public function __construct(
private int $id,
private int $hostId,
private int $serviceId,
private \DateTime $entryTime,
) {
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @return int|null
*/
public function getInstanceId(): ?int
{
return $this->instanceId;
}
/**
* @param int $instanceId
*
* @return self
*/
public function setInstanceId(int $instanceId): self
{
$this->instanceId = $instanceId;
return $this;
}
/**
* @return int
*/
public function getHostId(): int
{
return $this->hostId;
}
/**
* @return int
*/
public function getServiceId(): int
{
return $this->serviceId;
}
/**
* @return int|null
*/
public function getAuthorId(): ?int
{
return $this->authorId;
}
/**
* @param int|null $authorId
*
* @return self
*/
public function setAuthorId(?int $authorId): self
{
$this->authorId = $authorId;
return $this;
}
/**
* @return string|null
*/
public function getAuthorName(): ?string
{
return $this->authorName;
}
/**
* @param string|null $authorName
*
* @return self
*/
public function setAuthorName(?string $authorName): self
{
$this->authorName = $authorName;
return $this;
}
/**
* @return string|null
*/
public function getComment(): ?string
{
return $this->comment;
}
/**
* @param string|null $comment
*
* @return self
*/
public function setComment(?string $comment): self
{
$this->comment = $comment;
return $this;
}
/**
* @return \DateTime|null
*/
public function getDeletionTime(): ?\DateTime
{
return $this->deletionTime;
}
/**
* @param \DateTime|null $deletionTime
*
* @return self
*/
public function setDeletionTime(?\DateTime $deletionTime): self
{
$this->deletionTime = $deletionTime;
return $this;
}
/**
* @return \DateTime
*/
public function getEntryTime(): \DateTime
{
return $this->entryTime;
}
/**
* @return bool
*/
public function isNotifyContacts(): bool
{
return $this->isNotifyContacts;
}
/**
* @param bool $isNotifyContacts
*
* @return self
*/
public function setNotifyContacts(bool $isNotifyContacts): self
{
$this->isNotifyContacts = $isNotifyContacts;
return $this;
}
/**
* @return bool
*/
public function isPersistentComment(): bool
{
return $this->isPersistentComment;
}
/**
* @param bool $isPersistentComment
*
* @return self
*/
public function setPersistentComment(bool $isPersistentComment): self
{
$this->isPersistentComment = $isPersistentComment;
return $this;
}
/**
* @return bool
*/
public function isSticky(): bool
{
return $this->isSticky;
}
/**
* @param bool $isSticky
*
* @return self
*/
public function setSticky(bool $isSticky): self
{
$this->isSticky = $isSticky;
return $this;
}
/**
* @return int|null
*/
public function getState(): ?int
{
return $this->state;
}
/**
* @param int|null $state
*
* @return self
*/
public function setState(?int $state): self
{
$this->state = $state;
return $this;
}
/**
* @return int|null
*/
public function getType(): ?int
{
return $this->type;
}
/**
* @param int|null $type
*
* @return self
*/
public function setType(?int $type): self
{
$this->type = $type;
return $this;
}
/**
* @return bool
*/
public function isWithServices(): bool
{
return $this->withServices;
}
/**
* @param bool $withServices
*
* @return self
*/
public function setWithServices(bool $withServices): self
{
$this->withServices = $withServices;
return $this;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Domain/RealTime/Model/HostStatus.php | centreon/src/Core/Domain/RealTime/Model/HostStatus.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\RealTime\Model;
class HostStatus extends Status
{
public const STATUS_NAME_UP = 'UP';
public const STATUS_NAME_DOWN = 'DOWN';
public const STATUS_NAME_UNREACHABLE = 'UNREACHABLE';
public const STATUS_CODE_UP = 0;
public const STATUS_CODE_DOWN = 1;
public const STATUS_CODE_UNREACHABLE = 2;
public const STATUS_ORDER_UP = parent::STATUS_ORDER_OK;
public const STATUS_ORDER_UNREACHABLE = parent::STATUS_ORDER_LOW;
public const STATUS_ORDER_DOWN = parent::STATUS_ORDER_HIGH;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Domain/RealTime/Model/MetaService.php | centreon/src/Core/Domain/RealTime/Model/MetaService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\RealTime\Model;
use Centreon\Domain\Common\Assertion\Assertion;
class MetaService
{
public const MAX_NAME_LENGTH = 255;
/** @var bool */
private $isInDowntime = false;
/** @var bool */
private $isAcknowledged = false;
/** @var bool */
private $isNotificationEnabled = false;
/** @var int|null */
private $notificationNumber;
/** @var string|null */
private $commandLine;
/** @var string|null */
private $performanceData;
/** @var string|null */
private $output;
/** @var \DateTime|null */
private $lastStatusChange;
/** @var \DateTime|null */
private $lastNotification;
/** @var float|null */
private $latency;
/** @var float|null */
private $executionTime;
/** @var float|null */
private $statusChangePercentage;
/** @var \DateTime|null */
private $nextCheck;
/** @var \DateTime|null */
private $lastCheck;
/** @var bool */
private $activeChecks = true;
/** @var bool */
private $passiveChecks = false;
/** @var \DateTime|null */
private $lastTimeOk;
/** @var int|null */
private $maxCheckAttempts;
/** @var int|null */
private $checkAttempts;
/** @var bool */
private $isFlapping = false;
/** @var bool */
private $hasGraphData = false;
/**
* @param int $id
* @param int $hostId
* @param int $serviceId
* @param string $name
* @param ServiceStatus $status
* @param string $monitoringServerName
*
* @throws \Assert\AssertionFailedException
*/
public function __construct(
private int $id,
private int $hostId,
private int $serviceId,
private string $name,
private string $monitoringServerName,
private ServiceStatus $status,
) {
Assertion::maxLength($name, self::MAX_NAME_LENGTH, 'MetaService::name');
Assertion::notEmpty($name, 'MetaService::name');
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @return ServiceStatus
*/
public function getStatus(): ServiceStatus
{
return $this->status;
}
/**
* @return bool
*/
public function isFlapping(): bool
{
return $this->isFlapping;
}
/**
* @param bool $isFlapping
*
* @return self
*/
public function setIsFlapping(bool $isFlapping): self
{
$this->isFlapping = $isFlapping;
return $this;
}
/**
* @return bool
*/
public function isAcknowledged(): bool
{
return $this->isAcknowledged;
}
/**
* @param bool $isAcknowledged
*
* @return self
*/
public function setIsAcknowledged(bool $isAcknowledged): self
{
$this->isAcknowledged = $isAcknowledged;
return $this;
}
/**
* @param bool $isInDowntime
*
* @return self
*/
public function setIsInDowntime(bool $isInDowntime): self
{
$this->isInDowntime = $isInDowntime;
return $this;
}
/**
* @return bool
*/
public function isInDowntime(): bool
{
return $this->isInDowntime;
}
/**
* @return string|null
*/
public function getOutput(): ?string
{
return $this->output;
}
/**
* @param string|null $output
*
* @return self
*/
public function setOutput(?string $output): self
{
$this->output = $output;
return $this;
}
/**
* @param string|null $performanceData
*
* @return self
*/
public function setPerformanceData(?string $performanceData): self
{
$this->performanceData = $performanceData;
return $this;
}
/**
* @return string|null
*/
public function getPerformanceData(): ?string
{
return $this->performanceData;
}
/**
* @return string|null
*/
public function getCommandLine(): ?string
{
return $this->commandLine;
}
/**
* @param string|null $commandLine
*
* @return self
*/
public function setCommandLine(?string $commandLine): self
{
$this->commandLine = $commandLine;
return $this;
}
/**
* @return bool
*/
public function isNotificationEnabled(): bool
{
return $this->isNotificationEnabled;
}
/**
* @param bool $isNotificationEnabled
*
* @return self
*/
public function setNotificationEnabled(bool $isNotificationEnabled): self
{
$this->isNotificationEnabled = $isNotificationEnabled;
return $this;
}
/**
* @return int|null
*/
public function getNotificationNumber(): ?int
{
return $this->notificationNumber;
}
/**
* @param int|null $notificationNumber
*
* @return self
*/
public function setNotificationNumber(?int $notificationNumber): self
{
$this->notificationNumber = $notificationNumber;
return $this;
}
/**
* @return \DateTime|null
*/
public function getLastStatusChange(): ?\DateTime
{
return $this->lastStatusChange;
}
/**
* @param \DateTime|null $lastStatusChange
*
* @return self
*/
public function setLastStatusChange(?\DateTime $lastStatusChange): self
{
$this->lastStatusChange = $lastStatusChange;
return $this;
}
/**
* @return \DateTime|null
*/
public function getLastNotification(): ?\DateTime
{
return $this->lastNotification;
}
/**
* @param \DateTime|null $lastNotification
*
* @return self
*/
public function setLastNotification(?\DateTime $lastNotification): self
{
$this->lastNotification = $lastNotification;
return $this;
}
/**
* @return float|null
*/
public function getLatency(): ?float
{
return $this->latency;
}
/**
* @param float|null $latency
*
* @return self
*/
public function setLatency(?float $latency): self
{
$this->latency = $latency;
return $this;
}
/**
* @param float|null $executionTime
*
* @return self
*/
public function setExecutionTime(?float $executionTime): self
{
$this->executionTime = $executionTime;
return $this;
}
/**
* @return float|null
*/
public function getExecutionTime(): ?float
{
return $this->executionTime;
}
/**
* @param float|null $statusChangePercentage
*
* @return self
*/
public function setStatusChangePercentage(?float $statusChangePercentage): self
{
$this->statusChangePercentage = $statusChangePercentage;
return $this;
}
/**
* @return float|null
*/
public function getStatusChangePercentage(): ?float
{
return $this->statusChangePercentage;
}
/**
* @return \DateTime|null
*/
public function getNextCheck(): ?\DateTime
{
return $this->nextCheck;
}
/**
* @param \DateTime|null $nextCheck
*
* @return self
*/
public function setNextCheck(?\DateTime $nextCheck): self
{
$this->nextCheck = $nextCheck;
return $this;
}
/**
* @return \DateTime|null
*/
public function getLastCheck(): ?\DateTime
{
return $this->lastCheck;
}
/**
* @param \DateTime|null $lastCheck
*
* @return self
*/
public function setLastCheck(?\DateTime $lastCheck): self
{
$this->lastCheck = $lastCheck;
return $this;
}
/**
* @param bool $activeChecks
*
* @return self
*/
public function setActiveChecks(bool $activeChecks): self
{
$this->activeChecks = $activeChecks;
return $this;
}
/**
* @return bool
*/
public function hasActiveChecks(): bool
{
return $this->activeChecks;
}
/**
* @param bool $passiveChecks
*
* @return self
*/
public function setPassiveChecks(bool $passiveChecks): self
{
$this->passiveChecks = $passiveChecks;
return $this;
}
/**
* @return bool
*/
public function hasPassiveChecks(): bool
{
return $this->passiveChecks;
}
/**
* @param \DateTime|null $lastTimeOk
*
* @return self
*/
public function setLastTimeOk(?\DateTime $lastTimeOk): self
{
$this->lastTimeOk = $lastTimeOk;
return $this;
}
/**
* @return \DateTime|null
*/
public function getLastTimeOk(): ?\DateTime
{
return $this->lastTimeOk;
}
/**
* @return int|null
*/
public function getMaxCheckAttempts(): ?int
{
return $this->maxCheckAttempts;
}
/**
* @param int|null $maxCheckAttempts
*
* @return self
*/
public function setMaxCheckAttempts(?int $maxCheckAttempts): self
{
$this->maxCheckAttempts = $maxCheckAttempts;
return $this;
}
/**
* @param int|null $checkAttempts
*
* @return self
*/
public function setCheckAttempts(?int $checkAttempts): self
{
$this->checkAttempts = $checkAttempts;
return $this;
}
/**
* @return int|null
*/
public function getCheckAttempts(): ?int
{
return $this->checkAttempts;
}
/**
* @return int
*/
public function getHostId(): int
{
return $this->hostId;
}
/**
* @return int
*/
public function getServiceId(): int
{
return $this->serviceId;
}
/**
* @return string
*/
public function getMonitoringServerName(): string
{
return $this->monitoringServerName;
}
/**
* @return bool
*/
public function hasGraphData(): bool
{
return $this->hasGraphData;
}
/**
* @param bool $hasGraphData
*
* @return self
*/
public function setHasGraphData(bool $hasGraphData): self
{
$this->hasGraphData = $hasGraphData;
return $this;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Domain/RealTime/Model/Service.php | centreon/src/Core/Domain/RealTime/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\Domain\RealTime\Model;
use Centreon\Domain\Common\Assertion\Assertion;
use Core\Severity\RealTime\Domain\Model\Severity;
use Core\Tag\RealTime\Domain\Model\Tag;
class Service
{
public const MAX_NAME_LENGTH = 255;
/** @var Servicegroup[] */
private array $groups = [];
/** @var bool */
private $isInDowntime = false;
/** @var bool */
private $isAcknowledged = false;
/** @var bool */
private $isNotificationEnabled = false;
/** @var int|null */
private $notificationNumber;
/** @var string|null */
private $commandLine;
/** @var string|null */
private $performanceData;
/** @var string|null */
private $output;
/** @var \DateTime|null */
private $lastStatusChange;
/** @var \DateTime|null */
private $lastNotification;
/** @var float|null */
private $latency;
/** @var float|null */
private $executionTime;
/** @var float|null */
private $statusChangePercentage;
/** @var \DateTime|null */
private $nextCheck;
/** @var \DateTime|null */
private $lastCheck;
/** @var bool */
private $activeChecks = true;
/** @var bool */
private $passiveChecks = false;
/** @var \DateTime|null */
private $lastTimeOk;
/** @var Icon|null */
private $icon;
/** @var int|null */
private $maxCheckAttempts;
/** @var int|null */
private $checkAttempts;
/** @var bool */
private $isFlapping = false;
/** @var bool */
private $hasGraphData = false;
/** @var Tag[] */
private array $categories = [];
/** @var Severity|null */
private ?Severity $severity = null;
/**
* @param int $id
* @param int $hostId
* @param string $name
* @param ServiceStatus $status
*
* @throws \Assert\AssertionFailedException
*/
public function __construct(
private int $id,
private int $hostId,
private string $name,
private ServiceStatus $status,
) {
Assertion::maxLength($name, self::MAX_NAME_LENGTH, 'Service::name');
Assertion::notEmpty($name, 'Service::name');
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @return Servicegroup[]
*/
public function getGroups(): array
{
return $this->groups;
}
/**
* @param Servicegroup $group
*
* @return self
*/
public function addGroup(Servicegroup $group): self
{
$this->groups[] = $group;
return $this;
}
/**
* @return ServiceStatus
*/
public function getStatus(): ServiceStatus
{
return $this->status;
}
/**
* @return bool
*/
public function isFlapping(): bool
{
return $this->isFlapping;
}
/**
* @param bool $isFlapping
*
* @return self
*/
public function setIsFlapping(bool $isFlapping): self
{
$this->isFlapping = $isFlapping;
return $this;
}
/**
* @return bool
*/
public function isAcknowledged(): bool
{
return $this->isAcknowledged;
}
/**
* @param bool $isAcknowledged
*
* @return self
*/
public function setIsAcknowledged(bool $isAcknowledged): self
{
$this->isAcknowledged = $isAcknowledged;
return $this;
}
/**
* @param bool $isInDowntime
*
* @return self
*/
public function setIsInDowntime(bool $isInDowntime): self
{
$this->isInDowntime = $isInDowntime;
return $this;
}
/**
* @return bool
*/
public function isInDowntime(): bool
{
return $this->isInDowntime;
}
/**
* @return string|null
*/
public function getOutput(): ?string
{
return $this->output;
}
/**
* @param string|null $output
*
* @return self
*/
public function setOutput(?string $output): self
{
$this->output = $output;
return $this;
}
/**
* @param string|null $performanceData
*
* @return self
*/
public function setPerformanceData(?string $performanceData): self
{
$this->performanceData = $performanceData;
return $this;
}
/**
* @return string|null
*/
public function getPerformanceData(): ?string
{
return $this->performanceData;
}
/**
* @return string|null
*/
public function getCommandLine(): ?string
{
return $this->commandLine;
}
/**
* @param string|null $commandLine
*
* @return self
*/
public function setCommandLine(?string $commandLine): self
{
$this->commandLine = $commandLine;
return $this;
}
/**
* @return int|null
*/
public function getNotificationNumber(): ?int
{
return $this->notificationNumber;
}
/**
* @param int|null $notificationNumber
*
* @return self
*/
public function setNotificationNumber(?int $notificationNumber): self
{
$this->notificationNumber = $notificationNumber;
return $this;
}
/**
* @return bool
*/
public function isNotificationEnabled(): bool
{
return $this->isNotificationEnabled;
}
/**
* @param bool $isNotificationEnabled
*
* @return self
*/
public function setNotificationEnabled(bool $isNotificationEnabled): self
{
$this->isNotificationEnabled = $isNotificationEnabled;
return $this;
}
/**
* @return \DateTime|null
*/
public function getLastStatusChange(): ?\DateTime
{
return $this->lastStatusChange;
}
/**
* @param \DateTime|null $lastStatusChange
*
* @return self
*/
public function setLastStatusChange(?\DateTime $lastStatusChange): self
{
$this->lastStatusChange = $lastStatusChange;
return $this;
}
/**
* @return \DateTime|null
*/
public function getLastNotification(): ?\DateTime
{
return $this->lastNotification;
}
/**
* @param \DateTime|null $lastNotification
*
* @return self
*/
public function setLastNotification(?\DateTime $lastNotification): self
{
$this->lastNotification = $lastNotification;
return $this;
}
/**
* @return float|null
*/
public function getLatency(): ?float
{
return $this->latency;
}
/**
* @param float|null $latency
*
* @return self
*/
public function setLatency(?float $latency): self
{
$this->latency = $latency;
return $this;
}
/**
* @param float|null $executionTime
*
* @return self
*/
public function setExecutionTime(?float $executionTime): self
{
$this->executionTime = $executionTime;
return $this;
}
/**
* @return float|null
*/
public function getExecutionTime(): ?float
{
return $this->executionTime;
}
/**
* @param float|null $statusChangePercentage
*
* @return self
*/
public function setStatusChangePercentage(?float $statusChangePercentage): self
{
$this->statusChangePercentage = $statusChangePercentage;
return $this;
}
/**
* @return float|null
*/
public function getStatusChangePercentage(): ?float
{
return $this->statusChangePercentage;
}
/**
* @return \DateTime|null
*/
public function getNextCheck(): ?\DateTime
{
return $this->nextCheck;
}
/**
* @param \DateTime|null $nextCheck
*
* @return self
*/
public function setNextCheck(?\DateTime $nextCheck): self
{
$this->nextCheck = $nextCheck;
return $this;
}
/**
* @return \DateTime|null
*/
public function getLastCheck(): ?\DateTime
{
return $this->lastCheck;
}
/**
* @param \DateTime|null $lastCheck
*
* @return self
*/
public function setLastCheck(?\DateTime $lastCheck): self
{
$this->lastCheck = $lastCheck;
return $this;
}
/**
* @param bool $activeChecks
*
* @return self
*/
public function setActiveChecks(bool $activeChecks): self
{
$this->activeChecks = $activeChecks;
return $this;
}
/**
* @return bool
*/
public function hasActiveChecks(): bool
{
return $this->activeChecks;
}
/**
* @param bool $passiveChecks
*
* @return self
*/
public function setPassiveChecks(bool $passiveChecks): self
{
$this->passiveChecks = $passiveChecks;
return $this;
}
/**
* @return bool
*/
public function hasPassiveChecks(): bool
{
return $this->passiveChecks;
}
/**
* @param \DateTime|null $lastTimeOk
*
* @return self
*/
public function setLastTimeOk(?\DateTime $lastTimeOk): self
{
$this->lastTimeOk = $lastTimeOk;
return $this;
}
/**
* @return \DateTime|null
*/
public function getLastTimeOk(): ?\DateTime
{
return $this->lastTimeOk;
}
/**
* @param ?Icon $icon
*
* @return self
*/
public function setIcon(?Icon $icon): self
{
$this->icon = $icon;
return $this;
}
/**
* @return Icon|null
*/
public function getIcon(): ?Icon
{
return $this->icon;
}
/**
* @return int|null
*/
public function getMaxCheckAttempts(): ?int
{
return $this->maxCheckAttempts;
}
/**
* @param int|null $maxCheckAttempts
*
* @return self
*/
public function setMaxCheckAttempts(?int $maxCheckAttempts): self
{
$this->maxCheckAttempts = $maxCheckAttempts;
return $this;
}
/**
* @param int|null $checkAttempts
*
* @return self
*/
public function setCheckAttempts(?int $checkAttempts): self
{
$this->checkAttempts = $checkAttempts;
return $this;
}
/**
* @return int|null
*/
public function getCheckAttempts(): ?int
{
return $this->checkAttempts;
}
/**
* @return int
*/
public function getHostId(): int
{
return $this->hostId;
}
/**
* @return bool
*/
public function hasGraphData(): bool
{
return $this->hasGraphData;
}
/**
* @param bool $hasGraphData
*
* @return self
*/
public function setHasGraphData(bool $hasGraphData): self
{
$this->hasGraphData = $hasGraphData;
return $this;
}
/**
* @return Tag[]
*/
public function getCategories(): array
{
return $this->categories;
}
/**
* @param Tag $category
*
* @return self
*/
public function addCategory(Tag $category): self
{
$this->categories[] = $category;
return $this;
}
/**
* @param Tag[] $categories
*
* @throws \TypeError
*
* @return self
*/
public function setCategories(array $categories): self
{
$this->categories = [];
foreach ($categories as $category) {
$this->addCategory($category);
}
return $this;
}
/**
* @param Servicegroup[] $groups
*
* @throws \TypeError
*
* @return self
*/
public function setGroups(array $groups): self
{
$this->groups = [];
foreach ($groups as $group) {
$this->addGroup($group);
}
return $this;
}
/**
* @param Severity|null $severity
*
* @throws \TypeError
*
* @return self
*/
public function setSeverity(?Severity $severity): self
{
$this->severity = $severity;
return $this;
}
/**
* @return Severity|null
*/
public function getSeverity(): ?Severity
{
return $this->severity;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Domain/RealTime/Model/ServiceStatus.php | centreon/src/Core/Domain/RealTime/Model/ServiceStatus.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\RealTime\Model;
class ServiceStatus extends Status
{
public const STATUS_NAME_OK = 'OK';
public const STATUS_NAME_WARNING = 'WARNING';
public const STATUS_NAME_CRITICAL = 'CRITICAL';
public const STATUS_NAME_UNKNOWN = 'UNKNOWN';
public const STATUS_CODE_OK = 0;
public const STATUS_CODE_WARNING = 1;
public const STATUS_CODE_CRITICAL = 2;
public const STATUS_CODE_UNKNOWN = 3;
public const STATUS_ORDER_OK = parent::STATUS_ORDER_OK;
public const STATUS_ORDER_WARNING = parent::STATUS_ORDER_MEDIUM;
public const STATUS_ORDER_CRITICAL = parent::STATUS_ORDER_HIGH;
public const STATUS_ORDER_UNKNOWN = parent::STATUS_ORDER_LOW;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Domain/RealTime/Model/Status.php | centreon/src/Core/Domain/RealTime/Model/Status.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\RealTime\Model;
abstract class Status
{
public const STATUS_ORDER_HIGH = 1;
public const STATUS_ORDER_MEDIUM = 2;
public const STATUS_ORDER_LOW = 3;
public const STATUS_ORDER_PENDING = 4;
public const STATUS_ORDER_OK = 5;
public const STATUS_NAME_PENDING = 'PENDING';
public const STATUS_CODE_PENDING = 4;
/** @var int|null */
protected $order;
/**
* @param string $name
* @param int $code
* @param int $type
*/
public function __construct(
private string $name,
private int $code,
private int $type,
) {
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @return int
*/
public function getCode(): int
{
return $this->code;
}
/**
* @return int
*/
public function getType(): int
{
return $this->type;
}
/**
* @param int|null $order
*
* @return static
*/
public function setOrder(?int $order): static
{
$this->order = $order;
return $this;
}
/**
* @return int|null
*/
public function getOrder(): ?int
{
return $this->order;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Domain/RealTime/Model/Hostgroup.php | centreon/src/Core/Domain/RealTime/Model/Hostgroup.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\RealTime\Model;
class Hostgroup
{
/**
* @param int $id
* @param string $name
*/
public function __construct(
private int $id,
private string $name,
) {
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Domain/RealTime/Model/Host.php | centreon/src/Core/Domain/RealTime/Model/Host.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\RealTime\Model;
use Centreon\Domain\Common\Assertion\Assertion;
use Core\Severity\RealTime\Domain\Model\Severity;
use Core\Tag\RealTime\Domain\Model\Tag;
/**
* Class representing a host entity in real time context.
*/
class Host
{
public const MAX_NAME_LENGTH = 255;
public const MAX_ADDRESS_LENGTH = 75;
public const MAX_ALIAS_LENTH = 100;
/** @var string|null */
private $alias;
/** @var string|null */
private $timezone;
/** @var bool */
private $isInDowntime = false;
/** @var bool */
private $isAcknowledged = false;
/** @var bool */
private $isFlapping = false;
/** @var bool */
private $isNotificationEnabled = false;
/** @var int|null */
private $notificationNumber;
/** @var string|null */
private $commandLine;
/** @var string|null */
private $performanceData;
/** @var string|null */
private $output;
/** @var \DateTime|null */
private $lastStatusChange;
/** @var \DateTime|null */
private $lastNotification;
/** @var float|null */
private $latency;
/** @var float|null */
private $executionTime;
/** @var float|null */
private $statusChangePercentage;
/** @var \DateTime|null */
private $nextCheck;
/** @var \DateTime|null */
private $lastCheck;
/** @var bool */
private $activeChecks = true;
/** @var bool */
private $passiveChecks = false;
/** @var \DateTime|null */
private $lastTimeUp;
/** @var Hostgroup[] */
private array $groups = [];
/** @var Icon|null */
private $icon;
/** @var int|null */
private $maxCheckAttempts;
/** @var int|null */
private $checkAttempts;
/** @var Tag[] */
private array $categories = [];
/** @var Severity|null */
private ?Severity $severity = null;
/**
* Host constructor.
*
* @param int $id
* @param string $name
* @param string $address
* @param string $monitoringServerName
* @param HostStatus $status
*
* @throws \Assert\AssertionFailedException
*/
public function __construct(
private int $id,
private string $name,
private string $address,
private string $monitoringServerName,
private HostStatus $status,
) {
Assertion::maxLength($name, self::MAX_NAME_LENGTH, 'Host::name');
Assertion::notEmpty($name, 'Host::name');
Assertion::maxLength($address, self::MAX_ADDRESS_LENGTH, 'Host::address');
Assertion::notEmpty($address, 'Host::address');
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @return string
*/
public function getAddress(): string
{
return $this->address;
}
/**
* @return string|null
*/
public function getAlias(): ?string
{
return $this->alias;
}
/**
* @param string|null $alias
*
* @throws \Assert\AssertionFailedException
*
* @return self
*/
public function setAlias(?string $alias): self
{
if ($alias !== null) {
Assertion::maxLength($alias, self::MAX_NAME_LENGTH, 'Host::name');
}
$this->alias = $alias;
return $this;
}
/**
* @return string
*/
public function getMonitoringServerName(): string
{
return $this->monitoringServerName;
}
/**
* @return string|null
*/
public function getTimezone(): ?string
{
return $this->timezone;
}
/**
* @param string|null $timezone
*
* @return self
*/
public function setTimezone(?string $timezone): self
{
$this->timezone = $timezone;
return $this;
}
/**
* @return bool
*/
public function isFlapping(): bool
{
return $this->isFlapping;
}
/**
* @param bool $isFlapping
*
* @return self
*/
public function setIsFlapping(bool $isFlapping): self
{
$this->isFlapping = $isFlapping;
return $this;
}
/**
* @return bool
*/
public function isAcknowledged(): bool
{
return $this->isAcknowledged;
}
/**
* @param bool $isAcknowledged
*
* @return self
*/
public function setIsAcknowledged(bool $isAcknowledged): self
{
$this->isAcknowledged = $isAcknowledged;
return $this;
}
/**
* @param bool $isInDowntime
*
* @return self
*/
public function setIsInDowntime(bool $isInDowntime): self
{
$this->isInDowntime = $isInDowntime;
return $this;
}
/**
* @return bool
*/
public function isInDowntime(): bool
{
return $this->isInDowntime;
}
/**
* @return string|null
*/
public function getOutput(): ?string
{
return $this->output;
}
/**
* @param string|null $output
*
* @return self
*/
public function setOutput(?string $output): self
{
$this->output = $output;
return $this;
}
/**
* @param string|null $performanceData
*
* @return self
*/
public function setPerformanceData(?string $performanceData): self
{
$this->performanceData = $performanceData;
return $this;
}
/**
* @return string|null
*/
public function getPerformanceData(): ?string
{
return $this->performanceData;
}
/**
* @return string|null
*/
public function getCommandLine(): ?string
{
return $this->commandLine;
}
/**
* @param string|null $commandLine
*
* @return self
*/
public function setCommandLine(?string $commandLine): self
{
$this->commandLine = $commandLine;
return $this;
}
/**
* @return bool
*/
public function isNotificationEnabled(): bool
{
return $this->isNotificationEnabled;
}
/**
* @param bool $isNotificationEnabled
*
* @return self
*/
public function setNotificationEnabled(bool $isNotificationEnabled): self
{
$this->isNotificationEnabled = $isNotificationEnabled;
return $this;
}
/**
* @return int|null
*/
public function getNotificationNumber(): ?int
{
return $this->notificationNumber;
}
/**
* @param int|null $notificationNumber
*
* @return self
*/
public function setNotificationNumber(?int $notificationNumber): self
{
$this->notificationNumber = $notificationNumber;
return $this;
}
/**
* @return \DateTime|null
*/
public function getLastStatusChange(): ?\DateTime
{
return $this->lastStatusChange;
}
/**
* @param \DateTime|null $lastStatusChange
*
* @return self
*/
public function setLastStatusChange(?\DateTime $lastStatusChange): self
{
$this->lastStatusChange = $lastStatusChange;
return $this;
}
/**
* @return \DateTime|null
*/
public function getLastNotification(): ?\DateTime
{
return $this->lastNotification;
}
/**
* @param \DateTime|null $lastNotification
*
* @return self
*/
public function setLastNotification(?\DateTime $lastNotification): self
{
$this->lastNotification = $lastNotification;
return $this;
}
/**
* @return float|null
*/
public function getLatency(): ?float
{
return $this->latency;
}
/**
* @param float|null $latency
*
* @return self
*/
public function setLatency(?float $latency): self
{
$this->latency = $latency;
return $this;
}
/**
* @param float|null $executionTime
*
* @return self
*/
public function setExecutionTime(?float $executionTime): self
{
$this->executionTime = $executionTime;
return $this;
}
/**
* @return float|null
*/
public function getExecutionTime(): ?float
{
return $this->executionTime;
}
/**
* @param float|null $statusChangePercentage
*
* @return self
*/
public function setStatusChangePercentage(?float $statusChangePercentage): self
{
$this->statusChangePercentage = $statusChangePercentage;
return $this;
}
/**
* @return float|null
*/
public function getStatusChangePercentage(): ?float
{
return $this->statusChangePercentage;
}
/**
* @return \DateTime|null
*/
public function getNextCheck(): ?\DateTime
{
return $this->nextCheck;
}
/**
* @param \DateTime|null $nextCheck
*
* @return self
*/
public function setNextCheck(?\DateTime $nextCheck): self
{
$this->nextCheck = $nextCheck;
return $this;
}
/**
* @return \DateTime|null
*/
public function getLastCheck(): ?\DateTime
{
return $this->lastCheck;
}
/**
* @param \DateTime|null $lastCheck
*
* @return self
*/
public function setLastCheck(?\DateTime $lastCheck): self
{
$this->lastCheck = $lastCheck;
return $this;
}
/**
* @param bool $activeChecks
*
* @return self
*/
public function setActiveChecks(bool $activeChecks): self
{
$this->activeChecks = $activeChecks;
return $this;
}
/**
* @return bool
*/
public function hasActiveChecks(): bool
{
return $this->activeChecks;
}
/**
* @param bool $passiveChecks
*
* @return self
*/
public function setPassiveChecks(bool $passiveChecks): self
{
$this->passiveChecks = $passiveChecks;
return $this;
}
/**
* @return bool
*/
public function hasPassiveChecks(): bool
{
return $this->passiveChecks;
}
/**
* @param \DateTime|null $lastTimeUp
*
* @return self
*/
public function setLastTimeUp(?\DateTime $lastTimeUp): self
{
$this->lastTimeUp = $lastTimeUp;
return $this;
}
/**
* @return \DateTime|null
*/
public function getLastTimeUp(): ?\DateTime
{
return $this->lastTimeUp;
}
/**
* @param Hostgroup $group
*
* @return self
*/
public function addGroup(Hostgroup $group): self
{
$this->groups[] = $group;
return $this;
}
/**
* @return Hostgroup[]
*/
public function getGroups(): array
{
return $this->groups;
}
/**
* @param ?Icon $icon
*
* @return self
*/
public function setIcon(?Icon $icon): self
{
$this->icon = $icon;
return $this;
}
/**
* @return Icon|null
*/
public function getIcon(): ?Icon
{
return $this->icon;
}
/**
* @return HostStatus
*/
public function getStatus(): HostStatus
{
return $this->status;
}
/**
* @return int|null
*/
public function getMaxCheckAttempts(): ?int
{
return $this->maxCheckAttempts;
}
/**
* @param int|null $maxCheckAttempts
*
* @return self
*/
public function setMaxCheckAttempts(?int $maxCheckAttempts): self
{
$this->maxCheckAttempts = $maxCheckAttempts;
return $this;
}
/**
* @param int|null $checkAttempts
*
* @return self
*/
public function setCheckAttempts(?int $checkAttempts): self
{
$this->checkAttempts = $checkAttempts;
return $this;
}
/**
* @return int|null
*/
public function getCheckAttempts(): ?int
{
return $this->checkAttempts;
}
/**
* @return Tag[]
*/
public function getCategories(): array
{
return $this->categories;
}
/**
* @param Tag $category
*
* @return self
*/
public function addCategory(Tag $category): self
{
$this->categories[] = $category;
return $this;
}
/**
* @param Tag[] $categories
*
* @throws \TypeError
*
* @return self
*/
public function setCategories(array $categories): self
{
$this->categories = [];
foreach ($categories as $category) {
$this->addCategory($category);
}
return $this;
}
/**
* @param Hostgroup[] $groups
*
* @throws \TypeError
*
* @return self
*/
public function setGroups(array $groups): self
{
$this->groups = [];
foreach ($groups as $group) {
$this->addGroup($group);
}
return $this;
}
/**
* @param Severity|null $severity
*
* @throws \TypeError
*
* @return self
*/
public function setSeverity(?Severity $severity): self
{
$this->severity = $severity;
return $this;
}
/**
* @return Severity|null
*/
public function getSeverity(): ?Severity
{
return $this->severity;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Domain/RealTime/Model/Downtime.php | centreon/src/Core/Domain/RealTime/Model/Downtime.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\RealTime\Model;
use Centreon\Domain\Common\Assertion\Assertion;
class Downtime
{
public const DOWNTIME_YEAR_MAX = 2100;
public const HOST_TYPE_DOWNTIME = 0;
public const SERVICE_TYPE_DOWNTIME = 1;
/** @var \DateTime|null */
private $entryTime;
/** @var int|null */
private $authorId;
/** @var string|null */
private $authorName;
/** @var bool */
private $isCancelled = false;
/** @var string|null */
private $comment;
/** @var \DateTime|null */
private $deletionTime;
/** @var int|null */
private $duration;
/** @var \DateTime|null */
private $endTime;
/** @var int|null */
private $engineDowntimeId;
/** @var bool */
private $isFixed = false;
/** @var int|null */
private $instanceId;
/** @var \DateTime|null */
private $startTime;
/** @var \DateTime|null */
private $actualStartTime;
/** @var \DateTime|null */
private $actualEndTime;
/** @var bool */
private $isStarted = false;
/** @var bool */
private $withServices = false;
/** @var \DateTime */
private $maxDate;
/**
* @param int $id
* @param int $hostId
* @param int $serviceId
*
* @throws \Exception
*/
public function __construct(
private int $id,
private int $hostId,
private int $serviceId,
) {
$this->maxDate = (new \DateTime('', new \DateTimeZone('UTC')))
->setDate(self::DOWNTIME_YEAR_MAX, 1, 1)
->setTime(0, 0)
->modify('- 1 minute');
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @return \DateTime|null
*/
public function getEntryTime(): ?\DateTime
{
return $this->entryTime;
}
/**
* @param \DateTime|null $entryTime
*
* @throws \Centreon\Domain\Common\Assertion\AssertionException
* @throws \Exception
*
* @return self
*/
public function setEntryTime(?\DateTime $entryTime): self
{
if ($entryTime !== null) {
Assertion::maxDate($entryTime, $this->maxDate, 'Downtime::entryTime');
}
$this->entryTime = $entryTime;
return $this;
}
/**
* @return int|null
*/
public function getAuthorId(): ?int
{
return $this->authorId;
}
/**
* @param int|null $authorId
*
* @return self
*/
public function setAuthorId(?int $authorId): self
{
$this->authorId = $authorId;
return $this;
}
/**
* @return string|null
*/
public function getAuthorName(): ?string
{
return $this->authorName;
}
/**
* @param string|null $authorName
*
* @return self
*/
public function setAuthorName(?string $authorName): self
{
$this->authorName = $authorName;
return $this;
}
/**
* @return int
*/
public function getHostId(): int
{
return $this->hostId;
}
/**
* @return int
*/
public function getServiceId(): int
{
return $this->serviceId;
}
/**
* @return bool
*/
public function isCancelled(): bool
{
return $this->isCancelled;
}
/**
* @param bool $isCancelled
*
* @return self
*/
public function setCancelled(bool $isCancelled): self
{
$this->isCancelled = $isCancelled;
return $this;
}
/**
* @return string|null
*/
public function getComment(): ?string
{
return $this->comment;
}
/**
* @param string|null $comment
*
* @return self
*/
public function setComment(?string $comment): self
{
$this->comment = $comment;
return $this;
}
/**
* @return \DateTime|null
*/
public function getDeletionTime(): ?\DateTime
{
return $this->deletionTime;
}
/**
* @param \DateTime|null $deletionTime
*
* @throws \Centreon\Domain\Common\Assertion\AssertionException
* @throws \Exception
*
* @return self
*/
public function setDeletionTime(?\DateTime $deletionTime): self
{
if ($deletionTime !== null) {
Assertion::maxDate($deletionTime, $this->maxDate, 'Downtime::deletionTime');
}
$this->deletionTime = $deletionTime;
return $this;
}
/**
* @return int|null
*/
public function getDuration(): ?int
{
return $this->duration;
}
/**
* @param int|null $duration
*
* @return self
*/
public function setDuration(?int $duration): self
{
$this->duration = $duration;
return $this;
}
/**
* @return \DateTime|null
*/
public function getEndTime(): ?\DateTime
{
return $this->endTime;
}
/**
* @param \DateTime|null $endTime
*
* @throws \Centreon\Domain\Common\Assertion\AssertionException
* @throws \Exception
*
* @return self
*/
public function setEndTime(?\DateTime $endTime): self
{
if ($endTime !== null) {
Assertion::maxDate($endTime, $this->maxDate, 'Downtime::endTime');
}
$this->endTime = $endTime;
return $this;
}
/**
* @return bool
*/
public function isFixed(): bool
{
return $this->isFixed;
}
/**
* @param bool $isFixed
*
* @return self
*/
public function setFixed(bool $isFixed): self
{
$this->isFixed = $isFixed;
return $this;
}
/**
* @return int|null
*/
public function getEngineDowntimeId(): ?int
{
return $this->engineDowntimeId;
}
/**
* @param int|null $engineDowntimeId
*
* @return self
*/
public function setEngineDowntimeId(?int $engineDowntimeId): self
{
$this->engineDowntimeId = $engineDowntimeId;
return $this;
}
/**
* @return int|null
*/
public function getInstanceId(): ?int
{
return $this->instanceId;
}
/**
* @param int|null $instanceId
*
* @return self
*/
public function setInstanceId(?int $instanceId): self
{
$this->instanceId = $instanceId;
return $this;
}
/**
* @return \DateTime|null
*/
public function getStartTime(): ?\DateTime
{
return $this->startTime;
}
/**
* @param \DateTime|null $startTime
*
* @throws \Centreon\Domain\Common\Assertion\AssertionException
* @throws \Exception
*
* @return self
*/
public function setStartTime(?\DateTime $startTime): self
{
if ($startTime !== null) {
Assertion::maxDate($startTime, $this->maxDate, 'Downtime::startTime');
}
$this->startTime = $startTime;
return $this;
}
/**
* @return \DateTime|null
*/
public function getActualStartTime(): ?\DateTime
{
return $this->actualStartTime;
}
/**
* @param \DateTime|null $actualStartTime
*
* @throws \Centreon\Domain\Common\Assertion\AssertionException
* @throws \Exception
*
* @return self
*/
public function setActualStartTime(?\DateTime $actualStartTime): self
{
if ($actualStartTime !== null) {
Assertion::maxDate($actualStartTime, $this->maxDate, 'Downtime::actualStartTime');
}
$this->actualStartTime = $actualStartTime;
return $this;
}
/**
* @return \DateTime|null
*/
public function getActualEndTime(): ?\DateTime
{
return $this->actualEndTime;
}
/**
* @param \DateTime|null $actualEndTime
*
* @throws \Centreon\Domain\Common\Assertion\AssertionException
* @throws \Exception
*
* @return self
*/
public function setActualEndTime(?\DateTime $actualEndTime): self
{
if ($actualEndTime !== null) {
Assertion::maxDate($actualEndTime, $this->maxDate, 'Downtime::actualEndTime');
}
$this->actualEndTime = $actualEndTime;
return $this;
}
/**
* @return bool
*/
public function isStarted(): bool
{
return $this->isStarted;
}
/**
* @param bool $isStarted
*
* @return self
*/
public function setStarted(bool $isStarted): self
{
$this->isStarted = $isStarted;
return $this;
}
/**
* @return bool
*/
public function isWithServices(): bool
{
return $this->withServices;
}
/**
* @param bool $withServices
*
* @return self
*/
public function setWithServices(bool $withServices): self
{
$this->withServices = $withServices;
return $this;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Domain/RealTime/Model/ResourceTypes/ServiceResourceType.php | centreon/src/Core/Domain/RealTime/Model/ResourceTypes/ServiceResourceType.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\RealTime\Model\ResourceTypes;
class ServiceResourceType extends AbstractResourceType
{
public const TYPE_NAME = 'service';
public const TYPE_ID = 0;
/** @var string */
protected string $name = self::TYPE_NAME;
/** @var int */
protected int $id = self::TYPE_ID;
/**
* @inheritDoc
*/
public function hasParent(): 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/Domain/RealTime/Model/ResourceTypes/HostResourceType.php | centreon/src/Core/Domain/RealTime/Model/ResourceTypes/HostResourceType.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\RealTime\Model\ResourceTypes;
class HostResourceType extends AbstractResourceType
{
public const TYPE_NAME = 'host';
public const TYPE_ID = 1;
/** @var string */
protected string $name = self::TYPE_NAME;
/** @var int */
protected int $id = self::TYPE_ID;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Domain/RealTime/Model/ResourceTypes/MetaServiceResourceType.php | centreon/src/Core/Domain/RealTime/Model/ResourceTypes/MetaServiceResourceType.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\RealTime\Model\ResourceTypes;
class MetaServiceResourceType extends AbstractResourceType
{
public const TYPE_NAME = 'metaservice';
public const TYPE_ID = 2;
/** @var string */
protected string $name = self::TYPE_NAME;
/** @var int */
protected int $id = self::TYPE_ID;
/**
* @inheritDoc
*/
public function hasInternalId(): 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/Domain/RealTime/Model/ResourceTypes/AbstractResourceType.php | centreon/src/Core/Domain/RealTime/Model/ResourceTypes/AbstractResourceType.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\RealTime\Model\ResourceTypes;
use Core\Domain\RealTime\ResourceTypeInterface;
abstract class AbstractResourceType implements ResourceTypeInterface
{
protected string $name = '';
protected int $id = -1;
/**
* @inheritDoc
*/
public function getId(): int
{
return $this->id;
}
/**
* @inheritDoc
*/
public function getName(): string
{
return $this->name;
}
/**
* @inheritDoc
*/
public function isValidForTypeName(string $typeName): bool
{
return $typeName === $this->name;
}
/**
* @inheritDoc
*/
public function isValidForTypeId(int $typeId): bool
{
return $typeId === $this->id;
}
/**
* @inheritDoc
*/
public function hasInternalId(): bool
{
return false;
}
/**
* @inheritDoc
*/
public function hasParent(): bool
{
return 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/Domain/Configuration/Model/MetaService.php | centreon/src/Core/Domain/Configuration/Model/MetaService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\Configuration\Model;
use Centreon\Domain\Common\Assertion\Assertion;
class MetaService
{
public const CALCULTATION_TYPE_AVERAGE = 'average';
public const CALCULTATION_TYPE_MINIMUM = 'minimum';
public const CALCULTATION_TYPE_MAXIMUM = 'maximum';
public const CALCULTATION_TYPE_SUM = 'sum';
public const AVAILABLE_CALCULATION_TYPES = [
self::CALCULTATION_TYPE_AVERAGE,
self::CALCULTATION_TYPE_MAXIMUM,
self::CALCULTATION_TYPE_MINIMUM,
self::CALCULTATION_TYPE_SUM,
];
public const DATA_SOURCE_GAUGE = 'gauge';
public const DATA_SOURCE_COUNTER = 'counter';
public const DATA_SOURCE_DERIVE = 'derive';
public const DATA_SOURCE_ABSOLUTE = 'absolute';
public const AVAILABLE_DATA_SOURCE_TYPES = [
self::DATA_SOURCE_ABSOLUTE,
self::DATA_SOURCE_COUNTER,
self::DATA_SOURCE_DERIVE,
self::DATA_SOURCE_GAUGE,
];
public const META_SELECT_MODE_LIST = 1;
public const META_SELECT_MODE_SQL_REGEXP = 2;
public const MAX_NAME_LENGTH = 254;
/** @var string|null */
private $output;
/** @var string|null Search string to be used in a SQL LIKE query for service selection */
private $regexpSearchServices;
/** @var string|null select the metric to measure for meta service status */
private $metric;
/** @var int|null absolute value for warning level (low threshold) */
private $warningThreshold;
/** @var int|null absolute value for critical level (high threshold) */
private $criticalThreshold;
/** @var bool Indicates whether this Meta Service is enabled or not (TRUE by default) */
private $isActivated = true;
/**
* @param int $id
* @param string $name
* @param string $calculationType
* @param int $metaSelectionMode Selection mode for services to be considered for this meta service.
* 0 - In service list mode, mark selected services in the options on meta service list.
* 1 - In SQL matching mode, specify a search string to be used in an SQL query.
* @param string $dataSourceType Define the data source type of the Meta Service
* 0 - GAUGE / 1 - COUNTER / 2 - DERIVE / 3 - ABSOLUTE
*/
public function __construct(
private int $id,
private string $name,
private string $calculationType,
private int $metaSelectionMode,
private string $dataSourceType,
) {
Assertion::maxLength($name, self::MAX_NAME_LENGTH, 'MetaService::name');
Assertion::notEmpty($name, 'MetaService::name');
Assertion::inArray($dataSourceType, self::AVAILABLE_DATA_SOURCE_TYPES, 'MetaService::dataSourceType');
Assertion::inArray($calculationType, self::AVAILABLE_CALCULATION_TYPES, 'MetaService::calculationType');
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @return string
*/
public function getCalculationType(): string
{
return $this->calculationType;
}
/**
* @return int
*/
public function getMetaSelectionMode(): int
{
return $this->metaSelectionMode;
}
/**
* @return string
*/
public function getDataSourceType(): string
{
return $this->dataSourceType;
}
/**
* @return string|null
*/
public function getOutput(): ?string
{
return $this->output;
}
/**
* @param string|null $output
*
* @return self
*/
public function setOutput(?string $output): self
{
$this->output = $output;
return $this;
}
/**
* @return string|null
*/
public function getRegexpSearchServices(): ?string
{
return $this->regexpSearchServices;
}
/**
* @param string|null $regexpSearchServices
*
* @return self
*/
public function setRegexpSearchServices(?string $regexpSearchServices): self
{
$this->regexpSearchServices = $regexpSearchServices;
return $this;
}
/**
* @return string|null
*/
public function getMetric(): ?string
{
return $this->metric;
}
/**
* @param string|null $metric
*
* @return self
*/
public function setMetric(?string $metric): self
{
$this->metric = $metric;
return $this;
}
/**
* @return int|null
*/
public function getWarningThreshold(): ?int
{
return $this->warningThreshold;
}
/**
* @param int|null $warningThreshold
*
* @return self
*/
public function setWarningThreshold(?int $warningThreshold): self
{
$this->warningThreshold = $warningThreshold;
return $this;
}
/**
* @return int|null
*/
public function getCriticalThreshold(): ?int
{
return $this->criticalThreshold;
}
/**
* @param int|null $criticalThreshold
*
* @return self
*/
public function setCriticalThreshold(?int $criticalThreshold): self
{
$this->criticalThreshold = $criticalThreshold;
return $this;
}
/**
* @return bool
*/
public function isActivated(): bool
{
return $this->isActivated;
}
/**
* @param bool $isActivated
*
* @return self
*/
public function setActivated(bool $isActivated): self
{
$this->isActivated = $isActivated;
return $this;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Domain/Configuration/Model/MetaServiceNamesById.php | centreon/src/Core/Domain/Configuration/Model/MetaServiceNamesById.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\Configuration\Model;
use Core\Common\Domain\TrimmedString;
class MetaServiceNamesById
{
/** @var array<int,TrimmedString> */
private array $names = [];
/**
* @param int $metaServiceId
* @param TrimmedString $metaServiceName
*/
public function addName(int $metaServiceId, TrimmedString $metaServiceName): void
{
$this->names[$metaServiceId] = $metaServiceName;
}
/**
* @param int $metaServiceId
*
* @return null|string
*/
public function getName(int $metaServiceId): ?string
{
return isset($this->names[$metaServiceId]) ? $this->names[$metaServiceId]->value : null;
}
/**
* @return array<int,TrimmedString>
*/
public function getNames(): array
{
return $this->names;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Domain/Configuration/Notification/Model/NotifiedContact.php | centreon/src/Core/Domain/Configuration/Notification/Model/NotifiedContact.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\Configuration\Notification\Model;
class NotifiedContact
{
/**
* @param int $id
* @param string $name
* @param string $alias
* @param string $email
* @param HostNotification|null $hostNotification
* @param ServiceNotification|null $serviceNotification
*/
public function __construct(
private int $id,
private string $name,
private string $alias,
private string $email,
private ?HostNotification $hostNotification,
private ?ServiceNotification $serviceNotification,
) {
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @return string
*/
public function getAlias(): string
{
return $this->alias;
}
/**
* @return string
*/
public function getEmail(): string
{
return $this->email;
}
/**
* @return HostNotification|null
*/
public function getHostNotification(): ?HostNotification
{
return $this->hostNotification;
}
/**
* @return ServiceNotification|null
*/
public function getServiceNotification(): ?ServiceNotification
{
return $this->serviceNotification;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Domain/Configuration/Notification/Model/ServiceNotification.php | centreon/src/Core/Domain/Configuration/Notification/Model/ServiceNotification.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\Configuration\Notification\Model;
use Core\Domain\Configuration\Notification\Exception\NotificationException;
use Core\Domain\Configuration\TimePeriod\Model\TimePeriod;
class ServiceNotification implements NotificationInterface
{
public const EVENT_SERVICE_RECOVERY = 'RECOVERY';
public const EVENT_SERVICE_SCHEDULED_DOWNTIME = 'SCHEDULED_DOWNTIME';
public const EVENT_SERVICE_FLAPPING = 'FLAPPING';
public const EVENT_SERVICE_WARNING = 'WARNING';
public const EVENT_SERVICE_UNKNOWN = 'UNKNOWN';
public const EVENT_SERVICE_CRITICAL = 'CRITICAL';
public const SERVICE_EVENTS = [
self::EVENT_SERVICE_RECOVERY,
self::EVENT_SERVICE_SCHEDULED_DOWNTIME,
self::EVENT_SERVICE_FLAPPING,
self::EVENT_SERVICE_WARNING,
self::EVENT_SERVICE_UNKNOWN,
self::EVENT_SERVICE_CRITICAL,
];
/** @var string[] */
private $events = [];
/**
* @param TimePeriod $timePeriod
*/
public function __construct(
private TimePeriod $timePeriod,
) {
}
/**
* @inheritDoc
*/
public function getEvents(): array
{
return $this->events;
}
/**
* @inheritDoc
*/
public function getTimePeriod(): TimePeriod
{
return $this->timePeriod;
}
/**
* @param string $event
*
* @throws NotificationException
*
* @return self
*/
public function addEvent(string $event): self
{
if (in_array($event, self::SERVICE_EVENTS, true) === false) {
throw NotificationException::badEvent($event);
}
$this->events[] = $event;
return $this;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Domain/Configuration/Notification/Model/NotifiedContactGroup.php | centreon/src/Core/Domain/Configuration/Notification/Model/NotifiedContactGroup.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\Configuration\Notification\Model;
class NotifiedContactGroup
{
/**
* @param int $id
* @param string $name
* @param string $alias
*/
public function __construct(
private int $id,
private string $name,
private string $alias,
) {
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @return string
*/
public function getAlias(): string
{
return $this->alias;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Domain/Configuration/Notification/Model/NotificationInterface.php | centreon/src/Core/Domain/Configuration/Notification/Model/NotificationInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\Configuration\Notification\Model;
use Core\Domain\Configuration\TimePeriod\Model\TimePeriod;
interface NotificationInterface
{
/**
* @return string[]
*/
public function getEvents(): array;
/**
* @return TimePeriod
*/
public function getTimePeriod(): TimePeriod;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Domain/Configuration/Notification/Model/HostNotification.php | centreon/src/Core/Domain/Configuration/Notification/Model/HostNotification.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\Configuration\Notification\Model;
use Core\Domain\Configuration\Notification\Exception\NotificationException;
use Core\Domain\Configuration\TimePeriod\Model\TimePeriod;
class HostNotification implements NotificationInterface
{
public const EVENT_HOST_RECOVERY = 'RECOVERY';
public const EVENT_HOST_SCHEDULED_DOWNTIME = 'SCHEDULED_DOWNTIME';
public const EVENT_HOST_FLAPPING = 'FLAPPING';
public const EVENT_HOST_DOWN = 'DOWN';
public const EVENT_HOST_UNREACHABLE = 'UNREACHABLE';
public const HOST_EVENTS = [
self::EVENT_HOST_DOWN,
self::EVENT_HOST_FLAPPING,
self::EVENT_HOST_RECOVERY,
self::EVENT_HOST_SCHEDULED_DOWNTIME,
self::EVENT_HOST_UNREACHABLE,
];
/** @var string[] */
private $events = [];
/**
* @param TimePeriod $timePeriod
*/
public function __construct(
private TimePeriod $timePeriod,
) {
}
/**
* @inheritDoc
*/
public function getEvents(): array
{
return $this->events;
}
/**
* @inheritDoc
*/
public function getTimePeriod(): TimePeriod
{
return $this->timePeriod;
}
/**
* @param string $event
*
* @throws NotificationException
*
* @return self
*/
public function addEvent(string $event): self
{
if (in_array($event, self::HOST_EVENTS, true) === false) {
throw NotificationException::badEvent($event);
}
$this->events[] = $event;
return $this;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Domain/Configuration/Notification/Exception/NotificationException.php | centreon/src/Core/Domain/Configuration/Notification/Exception/NotificationException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\Configuration\Notification\Exception;
class NotificationException extends \InvalidArgumentException
{
/**
* @param string $event
*
* @return self
*/
public static function badEvent(string $event): self
{
return new self(sprintf(_('Invalid event provided (%s)'), $event));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Domain/Configuration/User/Model/User.php | centreon/src/Core/Domain/Configuration/User/Model/User.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\Configuration\User\Model;
class User extends NewUser
{
public const MIN_ALIAS_LENGTH = 1;
public const MAX_ALIAS_LENGTH = 255;
public const MIN_NAME_LENGTH = 1;
public const MAX_NAME_LENGTH = 255;
public const MIN_EMAIL_LENGTH = 1;
public const MAX_EMAIL_LENGTH = 255;
public const MIN_THEME_LENGTH = 1;
public const MAX_THEME_LENGTH = 100;
public const THEME_LIGHT = 'light';
public const THEME_DARK = 'dark';
public const USER_INTERFACE_DENSITY_EXTENDED = 'extended';
public const USER_INTERFACE_DENSITY_COMPACT = 'compact';
/**
* @param int $id
* @param string $alias
* @param string $name
* @param string $email
* @param bool $isAdmin
* @param string $theme
* @param string $userInterfaceDensity
* @param bool $canReachFrontend
*
* @throws \Assert\AssertionFailedException
*/
public function __construct(
private int $id,
protected string $alias,
protected string $name,
protected string $email,
protected bool $isAdmin,
protected string $theme,
protected string $userInterfaceDensity,
protected bool $canReachFrontend,
) {
parent::__construct($alias, $name, $email);
$this->setTheme($theme);
$this->setUserInterfaceDensity($userInterfaceDensity);
$this->setCanReachFrontend($canReachFrontend);
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Domain/Configuration/User/Model/NewUser.php | centreon/src/Core/Domain/Configuration/User/Model/NewUser.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\Configuration\User\Model;
use Centreon\Domain\Common\Assertion\Assertion;
use Core\Contact\Domain\Model\ContactTemplate;
/**
* This class represent a User being created.
*/
class NewUser
{
public const MIN_ALIAS_LENGTH = 1;
public const MAX_ALIAS_LENGTH = 255;
public const MIN_NAME_LENGTH = 1;
public const MAX_NAME_LENGTH = 255;
public const MIN_EMAIL_LENGTH = 1;
public const MAX_EMAIL_LENGTH = 255;
public const MIN_THEME_LENGTH = 1;
public const MAX_THEME_LENGTH = 100;
public const MAX_USER_INTERFACE_DENSITY_LENGTH = 100;
public const THEME_LIGHT = 'light';
public const THEME_DARK = 'dark';
public const USER_INTERFACE_DENSITY_EXTENDED = 'extended';
public const USER_INTERFACE_DENSITY_COMPACT = 'compact';
/** @var bool */
protected bool $isActivate = true;
/** @var bool */
protected bool $isAdmin = false;
/** @var string */
protected string $theme = self::THEME_LIGHT;
/** @var ContactTemplate|null */
protected ?ContactTemplate $contactTemplate = null;
protected string $userInterfaceDensity = self::USER_INTERFACE_DENSITY_COMPACT;
protected bool $canReachFrontend = true;
protected bool $canReachRealtimeApi = false;
protected bool $canReachConfigurationApi = false;
/**
* @param string $alias
* @param string $name
* @param string $email
*
* @throws \Assert\AssertionFailedException
*/
public function __construct(
protected string $alias,
protected string $name,
protected string $email,
) {
$this->setAlias($alias);
$this->setName($name);
$this->setEmail($email);
}
/**
* @return string
*/
public function getAlias(): string
{
return $this->alias;
}
/**
* @param string $alias
*
* @throws \Assert\AssertionFailedException
*
* @return self
*/
public function setAlias(string $alias): self
{
Assertion::minLength($alias, self::MIN_ALIAS_LENGTH, 'User::alias');
Assertion::maxLength($alias, self::MAX_ALIAS_LENGTH, 'User::alias');
$this->alias = $alias;
return $this;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @param string $name
*
* @throws \Assert\AssertionFailedException
*
* @return self
*/
public function setName(string $name): self
{
Assertion::minLength($name, self::MIN_ALIAS_LENGTH, 'User::name');
Assertion::maxLength($name, self::MAX_ALIAS_LENGTH, 'User::name');
$this->name = $name;
return $this;
}
/**
* @return string
*/
public function getEmail(): string
{
return $this->email;
}
/**
* @param string $email
*
* @throws \Assert\AssertionFailedException
*
* @return self
*/
public function setEmail(string $email): self
{
// Email format validation cannot be done here until legacy form does not check it
Assertion::minLength($email, self::MIN_EMAIL_LENGTH, 'User::email');
Assertion::maxLength($email, self::MAX_EMAIL_LENGTH, 'User::email');
$this->email = $email;
return $this;
}
/**
* @return bool
*/
public function isAdmin(): bool
{
return $this->isAdmin;
}
/**
* @param bool $isAdmin
*
* @return self
*/
public function setAdmin(bool $isAdmin): self
{
$this->isAdmin = $isAdmin;
return $this;
}
/**
* @return string
*/
public function getTheme(): string
{
return $this->theme;
}
/**
* @param string $theme
*
* @throws \Assert\AssertionFailedException
*
* @return self
*/
public function setTheme(string $theme): self
{
Assertion::minLength($theme, self::MIN_THEME_LENGTH, 'User::theme');
Assertion::maxLength($theme, self::MAX_THEME_LENGTH, 'User::theme');
$this->theme = $theme;
return $this;
}
/**
* @return ContactTemplate|null
*/
public function getContactTemplate(): ?ContactTemplate
{
return $this->contactTemplate;
}
/**
* @param ContactTemplate|null $contactTemplate
*
* @return self
*/
public function setContactTemplate(?ContactTemplate $contactTemplate): self
{
$this->contactTemplate = $contactTemplate;
return $this;
}
/**
* @return bool
*/
public function isActivate(): bool
{
return $this->isActivate;
}
/**
* @param bool $isActivate
*
* @return self
*/
public function setActivate(bool $isActivate): self
{
$this->isActivate = $isActivate;
return $this;
}
/**
* @return string
*/
public function getUserInterfaceDensity(): string
{
return $this->userInterfaceDensity;
}
/**
* @param string $userInterfaceDensity
*
* @throws \Assert\AssertionFailedException
* @throws \InvalidArgumentException
*
* @return self
*/
public function setUserInterfaceDensity(string $userInterfaceDensity): self
{
Assertion::notEmptyString(
$userInterfaceDensity,
'User::userInterfaceViewMode'
);
Assertion::maxLength(
$userInterfaceDensity,
self::MAX_USER_INTERFACE_DENSITY_LENGTH,
'User::userInterfaceViewMode'
);
if (
$userInterfaceDensity !== self::USER_INTERFACE_DENSITY_EXTENDED
&& $userInterfaceDensity !== self::USER_INTERFACE_DENSITY_COMPACT
) {
throw new \InvalidArgumentException('User interface view mode provided not handled');
}
$this->userInterfaceDensity = $userInterfaceDensity;
return $this;
}
/**
* @return bool
*/
public function canReachFrontend(): bool
{
return $this->canReachFrontend;
}
/**
* @param bool $canReachFrontend
*
* @return self
*/
public function setCanReachFrontend(bool $canReachFrontend): self
{
$this->canReachFrontend = $canReachFrontend;
return $this;
}
/**
* @return bool
*/
public function canReachRealtimeApi(): bool
{
return $this->canReachRealtimeApi;
}
/**
* @param bool $canReachRealtimeApi
*
* @return self
*/
public function setCanReachRealtimeApi(bool $canReachRealtimeApi): self
{
$this->canReachRealtimeApi = $canReachRealtimeApi;
return $this;
}
/**
* @param bool $canReachConfigurationApi
*
* @return self
*/
public function setCanReachConfigurationApi(bool $canReachConfigurationApi): self
{
$this->canReachConfigurationApi = $canReachConfigurationApi;
return $this;
}
/**
* @return bool
*/
public function canReachConfigurationApi(): bool
{
return $this->canReachConfigurationApi;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Domain/Configuration/UserGroup/Model/UserGroup.php | centreon/src/Core/Domain/Configuration/UserGroup/Model/UserGroup.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\Configuration\UserGroup\Model;
use Centreon\Domain\Common\Assertion\Assertion;
class UserGroup
{
public const MAX_NAME_LENGTH = 200;
public const MAX_ALIAS_LENGTH = 200;
/**
* @param int $id
* @param string $name
* @param string $alias
*
* @throws \Assert\AssertionFailedException
*/
public function __construct(
private int $id,
private string $name,
private string $alias,
) {
Assertion::maxLength($name, self::MAX_NAME_LENGTH, 'UserGroup::name');
Assertion::notEmpty($name, 'UserGroup::name');
Assertion::maxLength($alias, self::MAX_ALIAS_LENGTH, 'UserGroup::alias');
Assertion::notEmpty($alias, 'UserGroup::alias');
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @return string
*/
public function getAlias(): string
{
return $this->alias;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Domain/Configuration/TimePeriod/Model/TimePeriod.php | centreon/src/Core/Domain/Configuration/TimePeriod/Model/TimePeriod.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\Configuration\TimePeriod\Model;
use Centreon\Domain\Common\Assertion\Assertion;
class TimePeriod
{
public const MAX_NAME_LENGTH = 200;
public const MAX_ALIAS_LENGTH = 200;
/**
* @param int $id
* @param string $name
* @param string $alias
*/
public function __construct(
private int $id,
private string $name,
private string $alias,
) {
Assertion::maxLength($name, self::MAX_NAME_LENGTH, 'TimePeriod::name');
Assertion::notEmpty($name, 'TimePeriod::name');
Assertion::maxLength($alias, self::MAX_ALIAS_LENGTH, 'TimePeriod::alias');
Assertion::notEmpty($alias, 'TimePeriod::alias');
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @return string
*/
public function getAlias(): string
{
return $this->alias;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Domain/Common/GeoCoords.php | centreon/src/Core/Domain/Common/GeoCoords.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Domain\Common;
use Core\Domain\Exception\InvalidGeoCoordException;
/**
* This a basic value object which represents a pair of latitude and longitude.
*/
class GeoCoords implements \Stringable
{
/** @var string -90.0 to +90.0 */
private const REGEX_LATITUDE = '[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?)';
/** @var string -180.0 to +180.0 */
private const REGEX_LONGITUDE = '[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)';
/** @var string Full lat,lng string */
private const REGEX_FULL = '/^' . self::REGEX_LATITUDE . ',\s*' . self::REGEX_LONGITUDE . '$/';
private const MAX_DECIMALS = 6;
/**
* @param numeric-string $latitude
* @param numeric-string $longitude
*
* @throws InvalidGeoCoordException
*/
public function __construct(
public readonly string $latitude,
public readonly string $longitude,
) {
if (
! preg_match(self::REGEX_FULL, $latitude . ',' . $longitude)
) {
throw InvalidGeoCoordException::invalidValues();
}
}
public function __toString(): string
{
return $this->latitude . ',' . $this->longitude;
}
/**
* @param string $coords
*
* @throws InvalidGeoCoordException
*
* @return self
*/
public static function fromString(string $coords): self
{
$parts = explode(',', $coords);
$parts = array_map('trim', $parts);
if (\count($parts) !== 2) {
throw InvalidGeoCoordException::invalidFormat();
}
if (! is_numeric($parts[0]) || ! is_numeric($parts[1])) {
throw InvalidGeoCoordException::invalidValues();
}
/** @var numeric-string $latitude */
$latitude = self::truncateDecimals($parts[0]);
/** @var numeric-string $longitude */
$longitude = self::truncateDecimals($parts[1]);
return new self($latitude, $longitude);
}
/**
* Truncate decimals count for a coordinate value to MAX_DECIMALS
*
* @param string $value
* @return string
*/
private static function truncateDecimals(string $value): string
{
if (! str_contains($value, '.')) {
return $value;
}
[$intPart, $decimalPart] = explode('.', $value, 2);
$decimalPart = mb_substr($decimalPart, 0, self::MAX_DECIMALS);
return $intPart . '.' . $decimalPart;
}
}
| 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.