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/Infrastructure/Configuration/User/Repository/DbUserFactory.php | centreon/src/Core/Infrastructure/Configuration/User/Repository/DbUserFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Infrastructure\Configuration\User\Repository;
use Core\Domain\Configuration\User\Model\User;
/**
* @phpstan-import-type _UserRecord from DbReadUserRepository
*/
class DbUserFactory
{
/**
* @param _UserRecord $user
*
* @throws \Assert\AssertionFailedException
*
* @return User
*/
public static function createFromRecord(array $user): User
{
return new User(
(int) $user['contact_id'],
$user['contact_alias'],
$user['contact_name'],
$user['contact_email'],
$user['contact_admin'] === '1',
$user['contact_theme'],
$user['user_interface_density'],
$user['user_can_reach_frontend'] === '1'
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/Configuration/User/Repository/DbWriteUserRepository.php | centreon/src/Core/Infrastructure/Configuration/User/Repository/DbWriteUserRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Infrastructure\Configuration\User\Repository;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Core\Application\Configuration\User\Repository\WriteUserRepositoryInterface;
use Core\Domain\Configuration\User\Model\NewUser;
use Core\Domain\Configuration\User\Model\User;
class DbWriteUserRepository extends AbstractRepositoryDRB implements WriteUserRepositoryInterface
{
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function update(User $user): void
{
$statement = $this->db->prepare(
$this->translateDbName(
'UPDATE `:db`.`contact`
SET contact_name = :name,
contact_alias = :alias,
contact_email = :email,
contact_admin = :is_admin,
contact_theme = :theme,
user_interface_density = :userInterfaceDensity,
contact_oreon = :userCanReachFrontend
WHERE contact_id = :id'
)
);
$statement->bindValue(':name', $user->getName(), \PDO::PARAM_STR);
$statement->bindValue(':alias', $user->getAlias(), \PDO::PARAM_STR);
$statement->bindValue(':email', $user->getEmail(), \PDO::PARAM_STR);
$statement->bindValue(':is_admin', $user->isAdmin() ? '1' : '0', \PDO::PARAM_STR);
$statement->bindValue(':theme', $user->getTheme(), \PDO::PARAM_STR);
$statement->bindValue(':userInterfaceDensity', $user->getUserInterfaceDensity(), \PDO::PARAM_STR);
$statement->bindValue(':userCanReachFrontend', $user->canReachFrontend() ? '1' : '0', \PDO::PARAM_STR);
$statement->bindValue(':id', $user->getId(), \PDO::PARAM_INT);
$statement->execute();
}
/**
* @inheritDoc
*/
public function create(NewUser $user): void
{
$statement = $this->db->prepare(
$this->translateDbName(
<<<'SQL'
INSERT INTO `:db`.contact
(
contact_name,
contact_alias,
contact_email,
contact_template_id,
contact_admin,
contact_theme,
user_interface_density,
contact_activate,
contact_oreon,
reach_api_rt,
reach_api
)
VALUES
(
:contactName,
:contactAlias,
:contactEmail,
:contactTemplateId,
:isAdmin,
:contactTheme,
:userInterfaceDensity,
:isActivate,
:userCanReachFrontend,
:userCanReachRealtimeApi,
:userCanReachConfigurationApi
)
SQL
)
);
$statement->bindValue(':contactName', $user->getName(), \PDO::PARAM_STR);
$statement->bindValue(':contactAlias', $user->getAlias(), \PDO::PARAM_STR);
$statement->bindValue(':contactEmail', $user->getEmail(), \PDO::PARAM_STR);
$statement->bindValue(':contactTemplateId', $user->getContactTemplate()?->getId(), \PDO::PARAM_INT);
$statement->bindValue(':isAdmin', $user->isAdmin() ? '1' : '0', \PDO::PARAM_STR);
$statement->bindValue(':contactTheme', $user->getTheme(), \PDO::PARAM_STR);
$statement->bindValue(':userInterfaceDensity', $user->getUserInterfaceDensity(), \PDO::PARAM_STR);
$statement->bindValue(':isActivate', $user->isActivate() ? '1' : '0', \PDO::PARAM_STR);
$statement->bindValue(':userCanReachFrontend', $user->canReachFrontend() ? '1' : '0', \PDO::PARAM_STR);
$statement->bindValue(':userCanReachRealtimeApi', $user->canReachRealtimeApi() ? 1 : 0, \PDO::PARAM_INT);
$statement->bindValue(':userCanReachConfigurationApi', $user->canReachConfigurationApi() ? 1 : 0, \PDO::PARAM_INT);
$statement->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/Configuration/User/Repository/DbReadUserRepository.php | centreon/src/Core/Infrastructure/Configuration/User/Repository/DbReadUserRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Infrastructure\Configuration\User\Repository;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use Core\Application\Configuration\User\Repository\ReadUserRepositoryInterface;
use Core\Domain\Configuration\User\Model\User;
/**
* @phpstan-type _UserRecord array{
* contact_id: int|string,
* contact_alias: string,
* contact_name: string,
* contact_email: string,
* contact_admin: string,
* contact_theme: string,
* user_interface_density: string,
* user_can_reach_frontend: string,
* }
*/
class DbReadUserRepository extends AbstractRepositoryDRB implements ReadUserRepositoryInterface
{
use LoggerTrait;
/**
* @param DatabaseConnection $db
* @param SqlRequestParametersTranslator $sqlRequestTranslator
*/
public function __construct(
DatabaseConnection $db,
private SqlRequestParametersTranslator $sqlRequestTranslator,
) {
$this->db = $db;
$this->sqlRequestTranslator->setConcordanceArray([
'id' => 'contact_id',
'alias' => 'contact_alias',
'name' => 'contact_name',
'email' => 'contact_email',
'provider_name' => 'contact_auth_type',
]);
}
/**
* @inheritDoc
*
* @throws AssertionFailedException
*/
public function findAllUsers(): array
{
$this->info('Fetching users from database');
$request = <<<'SQL_WRAP'
SELECT SQL_CALC_FOUND_ROWS
contact_id,
contact_alias,
contact_name,
contact_email,
contact_admin,
contact_theme,
user_interface_density,
contact_oreon AS `user_can_reach_frontend`
FROM `:db`.contact
SQL_WRAP;
// Search
$searchRequest = $this->sqlRequestTranslator->translateSearchParameterToSql();
$request .= $searchRequest !== null ? $searchRequest . ' AND ' : ' WHERE ';
$request .= 'contact_register = 1';
// Sort
$sortRequest = $this->sqlRequestTranslator->translateSortParameterToSql();
$request .= $sortRequest ?? ' ORDER BY contact_id ASC';
// Pagination
$request .= $this->sqlRequestTranslator->translatePaginationToSql();
$statement = $this->db->prepare(
$this->translateDbName($request)
);
foreach ($this->sqlRequestTranslator->getSearchValues() as $key => $data) {
if (is_array($data)) {
$type = (int) key($data);
$value = $data[$type];
$statement->bindValue($key, $value, $type);
}
}
$statement->execute();
// Set total
$result = $this->db->query('SELECT FOUND_ROWS()');
if ($result !== false && ($total = $result->fetchColumn()) !== false) {
$this->sqlRequestTranslator->getRequestParameters()->setTotal((int) $total);
}
$users = [];
while ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
/** @var _UserRecord $result */
$users[] = DbUserFactory::createFromRecord($result);
}
return $users;
}
/**
* @inheritDoc
*/
public function findByContactGroups(ContactInterface $contact): array
{
$request = <<<'SQL_WRAP'
SELECT SQL_CALC_FOUND_ROWS DISTINCT
contact_id,
contact_alias,
contact_name,
contact_email,
contact_admin,
contact_theme,
user_interface_density,
contact_oreon AS `user_can_reach_frontend`
FROM `:db`.contact
INNER JOIN `:db`.contactgroup_contact_relation AS cg
ON cg.contact_contact_id = contact.contact_id
SQL_WRAP;
// Search
$searchRequest = $this->sqlRequestTranslator->translateSearchParameterToSql();
$request .= $searchRequest !== null ? $searchRequest . ' AND ' : ' WHERE ';
$request .= 'cg.contactgroup_cg_id IN (SELECT contactgroup_cg_id FROM `:db`.contactgroup_contact_relation '
. 'WHERE contact_contact_id = :contactId) AND contact_register = 1';
// Sort
$sortRequest = $this->sqlRequestTranslator->translateSortParameterToSql();
$request .= $sortRequest ?? ' ORDER BY contact_id ASC';
// Pagination
$request .= $this->sqlRequestTranslator->translatePaginationToSql();
$statement = $this->db->prepare(
$this->translateDbName($request)
);
foreach ($this->sqlRequestTranslator->getSearchValues() as $key => $data) {
if (is_array($data)) {
$type = (int) key($data);
$value = $data[$type];
$statement->bindValue($key, $value, $type);
}
}
$statement->bindValue(':contactId', $contact->getId(), \PDO::PARAM_INT);
$statement->execute();
// Set total
$result = $this->db->query('SELECT FOUND_ROWS()');
if ($result !== false && ($total = $result->fetchColumn()) !== false) {
$this->sqlRequestTranslator->getRequestParameters()->setTotal((int) $total);
}
$users = [];
while ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
/** @var _UserRecord $result */
$users[] = DbUserFactory::createFromRecord($result);
}
return $users;
}
/**
* @inheritDoc
*/
public function findById(int $userId): ?User
{
$statement = $this->db->prepare(
$this->translateDbName(
<<<'SQL'
SELECT
contact_id,
contact_alias,
contact_name,
contact_email,
contact_admin,
contact_theme,
user_interface_density,
contact_oreon AS `user_can_reach_frontend`
FROM `:db`.contact
WHERE contact_id = :contact_id
SQL
)
);
$statement->bindValue(':contact_id', $userId, \PDO::PARAM_INT);
$statement->execute();
if ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
/** @var _UserRecord $result */
return DbUserFactory::createFromRecord($result);
}
return null;
}
/**
* @inheritDoc
*/
public function findUserIdsByAliases(array $userAliases): array
{
$userIds = [];
if ($userAliases === []) {
return $userIds;
}
$this->info('Fetching user ids from database');
$bindValues = [];
foreach ($userAliases as $key => $userAlias) {
$bindValues[':' . $key] = $userAlias;
}
$bindFields = implode(',', array_keys($bindValues));
$statement = $this->db->prepare(
$this->translateDbName(
<<<SQL
SELECT contact_id
FROM `:db`.contact
WHERE contact_alias IN ({$bindFields})
SQL
)
);
foreach ($bindValues as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_STR);
}
$statement->execute();
while ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
/**
* @var array{contact_id: int} $result
*/
$userIds[] = $result['contact_id'];
}
return $userIds;
}
/**
* @inheritDoc
*/
public function findAvailableThemes(): array
{
$statement = $this->db->query(
<<<'SQL'
SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'contact' AND COLUMN_NAME = 'contact_theme'
SQL
);
if ($statement !== false && $result = $statement->fetch(\PDO::FETCH_ASSOC)) {
/**
* @var array<string, string> $result
*/
if (preg_match_all("/'([^,]+)'/", $result['COLUMN_TYPE'], $match)) {
/**
* @var array<int, string[]> $match
*/
return $match[1];
}
}
return [];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/Configuration/UserGroup/Repository/DbReadUserGroupRepository.php | centreon/src/Core/Infrastructure/Configuration/UserGroup/Repository/DbReadUserGroupRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Infrastructure\Configuration\UserGroup\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\StatementCollector;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Core\Application\Configuration\UserGroup\Repository\ReadUserGroupRepositoryInterface;
class DbReadUserGroupRepository extends AbstractRepositoryDRB implements ReadUserGroupRepositoryInterface
{
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function findByIds(array $userGroupIds): array
{
$userGroups = [];
if ($userGroupIds === []) {
return $userGroups;
}
$collector = new StatementCollector();
$request = $this->translateDbName(
'SELECT
cg_id AS `id`,
cg_name AS `name`,
cg_alias AS `alias`,
cg_activate AS `activated`
FROM `:db`.contactgroup'
);
foreach ($userGroupIds as $index => $userGroupId) {
$key = ":userGroupId_{$index}";
$userGroupIdList[] = $key;
$collector->addValue($key, $userGroupId, \PDO::PARAM_INT);
}
$request .= ' WHERE cg_id IN (' . implode(', ', $userGroupIdList) . ')';
$statement = $this->db->prepare($request);
$collector->bind($statement);
$statement->execute();
$userGroups = [];
while (($row = $statement->fetch(\PDO::FETCH_ASSOC))) {
/** @var array<string,int|string|null> $row */
$userGroups[] = DbUserGroupFactory::createFromRecord($row);
}
return $userGroups;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/Configuration/UserGroup/Repository/DbUserGroupFactory.php | centreon/src/Core/Infrastructure/Configuration/UserGroup/Repository/DbUserGroupFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Infrastructure\Configuration\UserGroup\Repository;
use Core\Domain\Configuration\UserGroup\Model\UserGroup;
class DbUserGroupFactory
{
/**
* @param array<string,int|string|null> $data
*
* @return UserGroup
*/
public static function createFromRecord(array $data): UserGroup
{
return new UserGroup(
(int) $data['id'],
(string) $data['name'],
(string) $data['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/Infrastructure/Common/Presenter/PresenterFormatterInterface.php | centreon/src/Core/Infrastructure/Common/Presenter/PresenterFormatterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Infrastructure\Common\Presenter;
use Symfony\Component\HttpFoundation\Response;
interface PresenterFormatterInterface
{
/**
* @param mixed $data
* @param array<string, mixed> $headers
*
* @return Response
*/
public function format(mixed $data, array $headers): 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/Infrastructure/Common/Presenter/DownloadInterface.php | centreon/src/Core/Infrastructure/Common/Presenter/DownloadInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Infrastructure\Common\Presenter;
interface DownloadInterface
{
public function setDownloadFileName(string $fileName): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/Common/Presenter/DownloadPresenter.php | centreon/src/Core/Infrastructure/Common/Presenter/DownloadPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Infrastructure\Common\Presenter;
use Symfony\Component\HttpFoundation\Response;
class DownloadPresenter implements PresenterFormatterInterface
{
private const CSV_FILE_EXTENSION = 'csv';
private const JSON_FILE_EXTENSION = 'json';
public function __construct(readonly private PresenterFormatterInterface $formatter)
{
}
/**
* @inheritDoc
*/
public function format(mixed $data, array $headers): Response
{
$filename = $this->generateDownloadFileName($data->filename ?? 'export');
$headers['Content-Type'] = 'application/force-download';
$headers['Content-Disposition'] = 'attachment; filename="' . $filename . '"';
return $this->formatter->format($data->performanceMetrics, $headers);
}
/**
* Generates download file extension depending on presenter.
*
* @return string
*/
private function generateDownloadFileExtension(): string
{
return match ($this->formatter::class) {
CsvFormatter::class => self::CSV_FILE_EXTENSION,
JsonFormatter::class => self::JSON_FILE_EXTENSION,
default => '',
};
}
/**
* Generates download file name (name + extension depending on used presenter).
*
* @param string $filename
*
* @return string
*/
private function generateDownloadFileName(string $filename): string
{
$fileExtension = $this->generateDownloadFileExtension();
return $fileExtension === '' ? $filename : $filename . '.' . $fileExtension;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/Common/Presenter/JsonFormatter.php | centreon/src/Core/Infrastructure/Common/Presenter/JsonFormatter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Infrastructure\Common\Presenter;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\{
BodyResponseInterface,
ConflictResponse,
CreatedResponse,
ErrorResponse,
ForbiddenResponse,
InvalidArgumentResponse,
MultiStatusResponse,
NoContentResponse,
NotFoundResponse,
NotModifiedResponse,
PaymentRequiredResponse,
ResponseStatusInterface,
UnauthorizedResponse
};
use Symfony\Component\HttpFoundation\{JsonResponse, Response};
class JsonFormatter implements PresenterFormatterInterface
{
use LoggerTrait;
protected ?int $encodingOptions = null;
/**
* {@inheritDoc}
*
* @throws \InvalidArgumentException
* @throws \TypeError
*/
public function format(mixed $data, array $headers): JsonResponse
{
if (is_object($data)) {
switch (true) {
case $data instanceof NotFoundResponse:
$this->debug('Data not found. Generating a not found response');
return $this->generateJsonErrorResponse($data, Response::HTTP_NOT_FOUND, $headers);
case $data instanceof ErrorResponse:
$this->debug('Data error. Generating an error response');
return $this->generateJsonErrorResponse($data, Response::HTTP_INTERNAL_SERVER_ERROR, $headers);
case $data instanceof InvalidArgumentResponse:
$this->debug('Invalid argument. Generating an error response');
return $this->generateJsonErrorResponse($data, Response::HTTP_BAD_REQUEST, $headers);
case $data instanceof UnauthorizedResponse:
$this->debug('Unauthorized. Generating an error response');
return $this->generateJsonErrorResponse($data, Response::HTTP_UNAUTHORIZED, $headers);
case $data instanceof PaymentRequiredResponse:
$this->debug('Payment required. Generating an error response');
return $this->generateJsonErrorResponse($data, Response::HTTP_PAYMENT_REQUIRED, $headers);
case $data instanceof ForbiddenResponse:
$this->debug('Forbidden. Generating an error response');
return $this->generateJsonErrorResponse($data, Response::HTTP_FORBIDDEN, $headers);
case $data instanceof ConflictResponse:
$this->debug('Conflict. Generating an error response');
return $this->generateJsonErrorResponse($data, Response::HTTP_CONFLICT, $headers);
case $data instanceof CreatedResponse:
return $this->generateJsonResponse($data, Response::HTTP_CREATED, $headers);
case $data instanceof NoContentResponse:
return $this->generateJsonResponse(null, Response::HTTP_NO_CONTENT, $headers);
case $data instanceof MultiStatusResponse:
return $this->generateJsonResponse($data, Response::HTTP_MULTI_STATUS, $headers);
case $data instanceof NotModifiedResponse:
return $this->generateJsonResponse($data, Response::HTTP_NOT_MODIFIED, $headers);
default:
return $this->generateJsonResponse($data, Response::HTTP_OK, $headers);
}
}
return $this->generateJsonResponse($data, Response::HTTP_OK, $headers);
}
public function setEncodingOptions(?int $encodingOptions): void
{
$this->encodingOptions = $encodingOptions;
}
/**
* Format content on error.
*
* @param mixed $data
* @param int $code
*
* @return mixed[]|null
*/
protected function formatErrorContent(mixed $data, int $code): ?array
{
$content = null;
if (is_object($data) && is_a($data, ResponseStatusInterface::class)) {
$content = [
'code' => $code,
'message' => $data->getMessage(),
];
if (is_a($data, BodyResponseInterface::class) && is_array($data->getBody())) {
$content = array_merge($content, $data->getBody());
}
}
return $content;
}
/**
* Generates json response with error message and http code.
*
* @param mixed $data
* @param int $code
* @param array<string, mixed> $headers
*
* @throws \TypeError
* @throws \InvalidArgumentException
*
* @return JsonResponse
*/
private function generateJsonErrorResponse(mixed $data, int $code, array $headers): JsonResponse
{
$errorData = $this->formatErrorContent($data, $code);
return $this->generateJsonResponse($errorData, $code, $headers);
}
/**
* @param mixed $data
* @param int $code
* @param array<string, mixed> $headers
*
* @throws \TypeError
* @throws \InvalidArgumentException
*
* @return JsonResponse
*/
private function generateJsonResponse(mixed $data, int $code, array $headers): JsonResponse
{
if (is_object($data)) {
if ($data instanceof \Generator) {
$data = iterator_to_array($data);
} elseif ($data instanceof CreatedResponse) {
$data = $data->getPayload();
} elseif ($data instanceof MultiStatusResponse) {
$data = $data->getPayload();
}
}
$response = new JsonResponse(null, $code, $headers);
if ($this->encodingOptions !== null) {
$response->setEncodingOptions($this->encodingOptions);
}
$response->setData($data);
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/Infrastructure/Common/Presenter/PresenterTrait.php | centreon/src/Core/Infrastructure/Common/Presenter/PresenterTrait.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Infrastructure\Common\Presenter;
/**
* This trait is here only to expose utility methods **only** to avoid duplicate code.
* The methods SHOULD be "Pure" functions.
*/
trait PresenterTrait
{
/**
* Convert a DateTime into a string format ISO 8601.
*
* @param \DateTimeInterface|null $date
*
* @return string|null
*/
public function formatDateToIso8601(?\DateTimeInterface $date): ?string
{
return $date !== null ? $date->format(\DateTimeInterface::ATOM) : $date;
}
/**
* Transform an empty string `''` in `null` value, otherwise keep the same string.
*
* @phpstan-pure
*
* @param string $string
*
* @return string|null
*/
public function emptyStringAsNull(string $string): ?string
{
return $string === '' ? null : $string;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/Common/Presenter/CsvFormatter.php | centreon/src/Core/Infrastructure/Common/Presenter/CsvFormatter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Infrastructure\Common\Presenter;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
class CsvFormatter implements PresenterFormatterInterface
{
/**
* @inheritDoc
*/
public function format(mixed $data, array $headers): Response
{
$response = new StreamedResponse(null, Response::HTTP_OK, $headers);
$response->setCallback(function () use ($data): void {
$handle = fopen('php://output', 'r+');
if ($handle === false) {
throw new \RuntimeException('Unable to open the output buffer');
}
$lineHeadersCreated = false;
if (is_iterable($data)) {
foreach ($data as $oneData) {
if (! $lineHeadersCreated) {
$columnNames = array_keys($oneData);
fputcsv($handle, $columnNames, ';');
$lineHeadersCreated = true;
}
$columnValues = array_values($oneData);
fputcsv($handle, $columnValues, ';');
}
}
fclose($handle);
});
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/Infrastructure/Common/Api/HttpUrlTrait.php | centreon/src/Core/Infrastructure/Common/Api/HttpUrlTrait.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Infrastructure\Common\Api;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\ServerBag;
use Symfony\Contracts\Service\Attribute\Required;
trait HttpUrlTrait
{
/** @var ServerBag|null */
private ?ServerBag $httpServerBag = null;
/**
* @param RequestStack $requestStack
*/
#[Required]
public function setHttpServerBag(RequestStack $requestStack): void
{
$this->httpServerBag = $requestStack->getCurrentRequest()?->server;
}
/**
* @param bool $withScheme
*
* @return string
*/
public function getHost(bool $withScheme = false): string
{
$httpHost = $_SERVER['HTTP_HOST'];
if ($withScheme) {
$scheme = $_SERVER['REQUEST_SCHEME'];
}
return $withScheme ? sprintf('%s://%s', $scheme, $httpHost) : $httpHost;
}
/**
* Get base URL (example: https://127.0.0.1/centreon).
*
* @return string
*/
protected function getBaseUrl(): string
{
if (! $this->httpServerBag?->has('SERVER_NAME')) {
return '';
}
$protocol = $this->httpServerBag->has('HTTPS') && $this->httpServerBag->get('HTTPS') !== 'off'
? 'https'
: 'http';
$port = null;
if ($this->httpServerBag->get('SERVER_PORT')) {
if (
($protocol === 'http' && $this->httpServerBag->get('SERVER_PORT') !== '80')
|| ($protocol === 'https' && $this->httpServerBag->get('SERVER_PORT') !== '443')
) {
/**
* @var string
*/
$port = $this->httpServerBag->get('SERVER_PORT');
$port = (int) $port;
}
}
$serverName = $this->httpServerBag->get('SERVER_NAME');
$baseUri = trim($this->getBaseUri(), '/');
return rtrim(
$protocol . '://' . $serverName . ($port !== null ? ':' . $port : '') . '/' . $baseUri,
'/'
);
}
/**
* Get base URI (example: /centreon).
*
* @return string
*/
protected function getBaseUri(): string
{
$baseUri = '';
$routeSuffixPatterns = [
'(api|widgets|modules|include)\/.+',
'main(\.get)?\.php',
'(?<!administration\/)authentication\/.+',
];
if ($this->httpServerBag?->has('REQUEST_URI')) {
/**
* @var string
*/
$requestUri = $this->httpServerBag->get('REQUEST_URI');
if (preg_match('/^(.+?)\/?(' . implode('|', $routeSuffixPatterns) . ')/', $requestUri, $matches)) {
$baseUri = $matches[1];
}
}
return rtrim($baseUri, '/');
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/Common/Api/DefaultPresenter.php | centreon/src/Core/Infrastructure/Common/Api/DefaultPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Infrastructure\Common\Api;
use Core\Application\Common\UseCase\AbstractPresenter;
class DefaultPresenter extends AbstractPresenter
{
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/Common/Api/Router.php | centreon/src/Core/Infrastructure/Common/Api/Router.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Infrastructure\Common\Api;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\CacheWarmer\WarmableInterface;
use Symfony\Component\Routing\Matcher\RequestMatcherInterface;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\RouterInterface;
/**
* Override symfony router to generate base URI.
*/
class Router implements RouterInterface, RequestMatcherInterface, WarmableInterface
{
use HttpUrlTrait;
/** @var RouterInterface */
private RouterInterface $router;
/** @var RequestMatcherInterface */
private RequestMatcherInterface $requestMatcher;
/**
* MyRouter constructor.
*
* @param RouterInterface $router
* @param RequestMatcherInterface $requestMatcher
*/
public function __construct(RouterInterface $router, RequestMatcherInterface $requestMatcher)
{
$this->router = $router;
$this->requestMatcher = $requestMatcher;
}
/**
* Get router.
*
* @return RouterInterface
*/
public function getRouter(): RouterInterface
{
return $this->router;
}
/**
* {@inheritDoc}
*
* @param string $name
* @param array{
* base_uri?: string,
* ...<string, mixed>
* } $parameters
* @param int $referenceType
*
* @throws \Exception
*
* @return string
*/
public function generate(string $name, array $parameters = [], int $referenceType = self::ABSOLUTE_PATH): string
{
$parameters['base_uri'] ??= $this->getBaseUri();
$doubleBaseUri = '';
if (! empty($parameters['base_uri'])) {
$doubleBaseUri = $parameters['base_uri'] . '/' . $parameters['base_uri'];
$doubleBaseUri = preg_replace('/(?<!:)(\/{2,})/', '$2/', $doubleBaseUri);
if ($doubleBaseUri === null) {
throw new \Exception('Error occured during regular expression search and replace.');
}
$parameters['base_uri'] .= '/';
}
// Manage URL Generation for HTTPS and Legacy nested route generation calls
$context = $this->router->getContext();
$forwardedProtoHeader = $_SERVER['HTTP_X_FORWARDED_PROTO'] ?? null;
if ($forwardedProtoHeader) {
// It could be possible that HTTP_X_FORWARDED_PROTO contains multiple comma-separated values e.g "https,http"
$proto = mb_strtolower(trim(explode(',', $forwardedProtoHeader)[0]));
$scheme = $proto === 'https' ? 'https' : 'http';
$context = $this->router->getContext();
$context->setScheme($scheme);
} elseif ($_SERVER['REQUEST_SCHEME'] === 'https') {
$context->setScheme($_SERVER['REQUEST_SCHEME']);
}
if ($_SERVER['SERVER_NAME'] !== 'localhost') {
$context->setHost($_SERVER['SERVER_NAME']);
}
$generatedRoute = $this->router->generate($name, $parameters, $referenceType);
// remove double slashes
$generatedRoute = preg_replace('/(?<!:)(\/{2,})/', '$2/', $generatedRoute);
if ($generatedRoute === null) {
throw new \Exception('Error occured during regular expression search and replace.');
}
// remove double identical prefixes due to progressive migration
$generatedRoute = str_replace($doubleBaseUri, $parameters['base_uri'], $generatedRoute);
// remove double slashes
$generatedRoute = preg_replace('/(?<!:)(\/{2,})/', '$2/', $generatedRoute);
if ($generatedRoute === null) {
throw new \Exception('Error occured during regular expression search and replace.');
}
return $generatedRoute;
}
/**
* {@inheritDoc}
*
* @param RequestContext $context
*/
public function setContext(RequestContext $context): void
{
$this->router->setContext($context);
}
/**
* @inheritDoc
*/
public function getContext(): RequestContext
{
return $this->router->getContext();
}
/**
* @inheritDoc
*/
public function getRouteCollection(): RouteCollection
{
return $this->router->getRouteCollection();
}
/**
* {@inheritDoc}
*
* @return array<string,mixed>
*/
public function match(string $pathinfo): array
{
return $this->router->match($pathinfo);
}
/**
* {@inheritDoc}
*
* @return array<string,mixed>
*/
public function matchRequest(Request $request): array
{
return $this->requestMatcher->matchRequest($request);
}
/**
* @param string $cacheDir
* @param null|string $buildDir
*
* @return string[]
*/
public function warmUp(string $cacheDir, ?string $buildDir = null): array
{
return [];
}
/**
* Create a href to a legacy page.
*
* @param int $topologyPage
* @param array<string, mixed> $options
*
* @return string
*/
public function generateLegacyHref(int $topologyPage, array $options = []): string
{
return $options === []
? $this->getBaseUrl() . '/main.php?p=' . $topologyPage
: $this->getBaseUrl() . '/main.php?p=' . $topologyPage . '&' . http_build_query($options);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/Common/Api/StandardPresenter.php | centreon/src/Core/Infrastructure/Common/Api/StandardPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Infrastructure\Common\Api;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\{
BulkResponseInterface,
ListingResponseInterface,
StandardPresenterInterface,
StandardResponseInterface
};
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Exception\ExceptionInterface;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\SerializerInterface;
class StandardPresenter implements StandardPresenterInterface
{
/**
* @param Serializer $serializer
* @param RequestParametersInterface $requestParameters
*/
public function __construct(
private readonly SerializerInterface $serializer,
private readonly RequestParametersInterface $requestParameters,
) {
}
/**
* @param StandardResponseInterface $data
* @param array<string, mixed> $context
* @param string $format
*
* @throws ExceptionInterface
*
* @return string
*/
public function present(
StandardResponseInterface $data,
array $context = [],
string $format = JsonEncoder::FORMAT,
): string {
return match (true) {
$data instanceof ListingResponseInterface => $this->presentListing($data, $context, $format),
$data instanceof BulkResponseInterface => $this->presentWithoutMeta($data, $context, $format),
default => $this->serializer->serialize($data->getData(), $format, $context),
};
}
/**
* @param ListingResponseInterface $data
* @param array<string, mixed> $context
* @param string $format
*
* @throws ExceptionInterface
*
* @return string
*/
private function presentListing(
ListingResponseInterface $data,
array $context = [],
string $format = JsonEncoder::FORMAT,
): string {
return $this->serializer->serialize(
[
'result' => $data->getData(),
'meta' => $this->requestParameters->toArray(),
],
$format,
$context,
);
}
/**
* @param BulkResponseInterface $data
* @param array<string, mixed> $context
* @param string $format
*
* @throws ExceptionInterface
*
* @return string
*/
private function presentWithoutMeta(
BulkResponseInterface $data,
array $context = [],
string $format = JsonEncoder::FORMAT,
): string {
return $this->serializer->serialize(
[
'results' => $data->getData(),
],
$format,
$context,
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/Common/Repository/DbFactoryUtilitiesTrait.php | centreon/src/Core/Infrastructure/Common/Repository/DbFactoryUtilitiesTrait.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Infrastructure\Common\Repository;
/**
* This class is design to provide all common methods to handle db records.
*/
trait DbFactoryUtilitiesTrait
{
/**
* Creates DateTime from timestamp.
*
* @param int|null $timestamp
*
* @return \DateTime|null
*/
public static function createDateTimeFromTimestamp(?int $timestamp): ?\DateTime
{
return $timestamp !== null
? (new \DateTime())->setTimestamp($timestamp)
: null;
}
/**
* Creates DateTimeImmutable from timestamp.
*
* @param int|string|null $timestamp
*
* @return \DateTimeImmutable|null
*/
public static function createDateTimeImmutableFromTimestamp(int|string|null $timestamp): ?\DateTimeImmutable
{
return $timestamp !== null
? (new \DateTimeImmutable())->setTimestamp((int) $timestamp)
: null;
}
/**
* @param int|string|null $property
*
* @return int|null
*/
public static function getIntOrNull($property): ?int
{
return ($property !== null) ? (int) $property : null;
}
/**
* @param float|string|null $property
*
* @return float|null
*/
public static function getFloatOrNull($property): ?float
{
return ($property !== null) ? (float) $property : null;
}
/**
* @param string|null $property
*
* @return int[]|array{}
*/
public static function fromStringToArrayOfInts(?string $property): array
{
if (
$property === null
|| $property === ''
) {
return [];
}
return array_map(
fn (string $value): int => (int) $value,
explode(',', $property)
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/Common/Repository/SystemReadSessionRepository.php | centreon/src/Core/Infrastructure/Common/Repository/SystemReadSessionRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Infrastructure\Common\Repository;
use Centreon\Domain\Repository\RepositoryException;
use Core\Application\Common\Session\Repository\ReadSessionRepositoryInterface;
class SystemReadSessionRepository implements ReadSessionRepositoryInterface
{
/**
* @inheritDoc
*/
public function findSessionIdsByUserId(int $userId): array
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function getValueFromSession(string $sessionId, string $key): mixed
{
session_id($sessionId);
session_start();
$value = $_SESSION[$key];
session_write_close();
return $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/Infrastructure/Common/Repository/DbReadSessionRepository.php | centreon/src/Core/Infrastructure/Common/Repository/DbReadSessionRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Infrastructure\Common\Repository;
use Centreon\Domain\Repository\RepositoryException;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Core\Application\Common\Session\Repository\ReadSessionRepositoryInterface;
class DbReadSessionRepository extends AbstractRepositoryDRB implements ReadSessionRepositoryInterface
{
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function findSessionIdsByUserId(int $userId): array
{
$statement = $this->db->prepare(
$this->translateDbName(
'SELECT session_id FROM session WHERE user_id = :user_id'
)
);
$statement->bindValue(':user_id', $userId, \PDO::PARAM_INT);
$statement->execute();
$sessionIds = [];
while ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
/** @var array<string,string> $result */
$sessionIds[] = $result['session_id'];
}
return $sessionIds;
}
/**
* @inheritDoc
*/
public function getValueFromSession(string $sessionId, string $key): mixed
{
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/Infrastructure/Common/Repository/SystemWriteSessionRepository.php | centreon/src/Core/Infrastructure/Common/Repository/SystemWriteSessionRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Infrastructure\Common\Repository;
use Core\Application\Common\Session\Repository\WriteSessionRepositoryInterface;
class SystemWriteSessionRepository implements WriteSessionRepositoryInterface
{
/**
* @inheritDoc
*/
public function updateSession(string $sessionId, string $key, mixed $value): void
{
session_id($sessionId);
session_start();
$_SESSION[$key] = $value;
session_write_close();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/Common/Repository/MultiReadSessionRepository.php | centreon/src/Core/Infrastructure/Common/Repository/MultiReadSessionRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Infrastructure\Common\Repository;
use Core\Application\Common\Session\Repository\ReadSessionRepositoryInterface;
class MultiReadSessionRepository implements ReadSessionRepositoryInterface
{
/**
* @param SystemReadSessionRepository $systemRepository
* @param DbReadSessionRepository $dbReadSessionRepository
*/
public function __construct(
private SystemReadSessionRepository $systemRepository,
private DbReadSessionRepository $dbReadSessionRepository,
) {
}
/**
* @inheritDoc
*/
public function findSessionIdsByUserId(int $userId): array
{
return $this->dbReadSessionRepository->findSessionIdsByUserId($userId);
}
/**
* @inheritDoc
*/
public function getValueFromSession(string $sessionId, string $key): mixed
{
return $this->systemRepository->getValueFromSession($sessionId, $key);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/Platform/Api/FindInstallationStatus/FindInstallationStatusController.php | centreon/src/Core/Infrastructure/Platform/Api/FindInstallationStatus/FindInstallationStatusController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Infrastructure\Platform\Api\FindInstallationStatus;
use Centreon\Application\Controller\AbstractController;
use Core\Application\Platform\UseCase\FindInstallationStatus\FindInstallationStatus;
use Core\Application\Platform\UseCase\FindInstallationStatus\FindInstallationStatusPresenterInterface;
final class FindInstallationStatusController extends AbstractController
{
/**
* @param FindInstallationStatus $useCase
* @param FindInstallationStatusPresenterInterface $presenter
*
* @return object
*/
public function __invoke(
FindInstallationStatus $useCase,
FindInstallationStatusPresenterInterface $presenter,
): object {
$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/Infrastructure/Platform/Api/FindInstallationStatus/FindInstallationStatusPresenter.php | centreon/src/Core/Infrastructure/Platform/Api/FindInstallationStatus/FindInstallationStatusPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Infrastructure\Platform\Api\FindInstallationStatus;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Platform\UseCase\FindInstallationStatus\FindInstallationStatusPresenterInterface;
use Core\Application\Platform\UseCase\FindInstallationStatus\FindInstallationStatusResponse;
class FindInstallationStatusPresenter extends AbstractPresenter implements FindInstallationStatusPresenterInterface
{
/**
* {@inheritDoc}
*
* @param FindInstallationStatusResponse $data
*/
public function present(mixed $data): void
{
$presenterResponse = [
'is_installed' => $data->isCentreonWebInstalled,
'has_upgrade_available' => $data->isCentreonWebUpgradeAvailable,
];
parent::present($presenterResponse);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Escalation/Application/Repository/ReadEscalationRepositoryInterface.php | centreon/src/Core/Escalation/Application/Repository/ReadEscalationRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Escalation\Application\Repository;
use Core\Escalation\Domain\Model\Escalation;
interface ReadEscalationRepositoryInterface
{
/**
* Find multiple escalations.
*
* @param int[] $ids
*
* @throws \Throwable
*
* @return Escalation[]
*/
public function findByIds(array $ids): array;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Escalation/Domain/Model/Escalation.php | centreon/src/Core/Escalation/Domain/Model/Escalation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Escalation\Domain\Model;
use Centreon\Domain\Common\Assertion\Assertion;
class Escalation
{
public const MAX_LENGTH_NAME = 255;
public function __construct(
private readonly int $id,
private string $name,
// NOTE: minimal implementation for current needs as november 2023
) {
$className = (new \ReflectionClass($this))->getShortName();
$this->name = trim($name);
Assertion::positiveInt($this->id, "{$className}::id");
Assertion::notEmptyString($this->name, "{$className}::name");
Assertion::maxLength($name, self::MAX_LENGTH_NAME, "{$className}::name");
}
public function getId(): int
{
return $this->id;
}
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/Escalation/Infrastructure/Repository/DbReadEscalationRepository.php | centreon/src/Core/Escalation/Infrastructure/Repository/DbReadEscalationRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Escalation\Infrastructure\Repository;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Escalation\Application\Repository\ReadEscalationRepositoryInterface;
use Core\Escalation\Domain\Model\Escalation;
use Utility\SqlConcatenator;
/**
* @phpstan-type _Escalation array{
* esc_id: int,
* esc_name: string
* }
*/
class DbReadEscalationRepository extends AbstractRepositoryRDB implements ReadEscalationRepositoryInterface
{
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function findByIds(array $escalationIds): array
{
if ($escalationIds === []) {
return $escalationIds;
}
$concatenator = new SqlConcatenator();
$concatenator->defineSelect(
<<<'SQL'
SELECT
esc_id,
esc_name
FROM escalation
WHERE esc_id IN (:ids)
SQL
);
$concatenator->storeBindValueMultiple(':ids', $escalationIds, \PDO::PARAM_INT);
$statement = $this->db->prepare($this->translateDbName($concatenator->__toString()));
$concatenator->bindValuesToStatement($statement);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
$escalations = [];
foreach ($statement as $row) {
/** @var _Escalation $row */
$escalations[] = $this->createEscalation($row);
}
return $escalations;
}
/**
* @param _Escalation $data
*
* @return Escalation
*/
private function createEscalation(array $data): Escalation
{
return new Escalation($data['esc_id'], $data['esc_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/CommandMacro/Application/Repository/ReadCommandMacroRepositoryInterface.php | centreon/src/Core/CommandMacro/Application/Repository/ReadCommandMacroRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\CommandMacro\Application\Repository;
use Core\CommandMacro\Domain\Model\CommandMacro;
use Core\CommandMacro\Domain\Model\CommandMacroType;
interface ReadCommandMacroRepositoryInterface
{
/**
* Find macros linked to a command for a specified type.
*
* @param int $commandId
* @param CommandMacroType $type
*
* @throws \Throwable
*
* @return CommandMacro[]
*/
public function findByCommandIdAndType(int $commandId, CommandMacroType $type): 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/CommandMacro/Domain/Model/CommandMacro.php | centreon/src/Core/CommandMacro/Domain/Model/CommandMacro.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\CommandMacro\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
class CommandMacro
{
public const MAX_NAME_LENGTH = 255;
public const MAX_DESCRIPTION_LENGTH = 65535;
private string $shortName;
private string $description = '';
/**
* @param int $commandId
* @param CommandMacroType $type
* @param string $name
*
* Note: See DB for complete property list
*
* @throws AssertionFailedException
*/
public function __construct(
private readonly int $commandId,
private readonly CommandMacroType $type,
private string $name,
) {
$this->shortName = (new \ReflectionClass($this))->getShortName();
Assertion::positiveInt($commandId, "{$this->shortName}::commandId");
Assertion::notEmptyString($this->name, "{$this->shortName}::name");
Assertion::maxLength($this->name, self::MAX_NAME_LENGTH, "{$this->shortName}::name");
}
public function getCommandId(): int
{
return $this->commandId;
}
public function getName(): string
{
return $this->name;
}
public function getType(): CommandMacroType
{
return $this->type;
}
public function getDescription(): string
{
return $this->description;
}
public function setDescription(string $description): void
{
$description = trim($description);
Assertion::maxLength($description, self::MAX_DESCRIPTION_LENGTH, "{$this->shortName}::description");
$this->description = $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/CommandMacro/Domain/Model/NewCommandMacro.php | centreon/src/Core/CommandMacro/Domain/Model/NewCommandMacro.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\CommandMacro\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
class NewCommandMacro
{
public const MAX_NAME_LENGTH = 255;
public const MAX_DESCRIPTION_LENGTH = 65535;
private string $shortName;
private string $description = '';
/**
* @param CommandMacroType $type
* @param string $name
* @param string $description
*
* Note: See DB for complete property list
*
* @throws AssertionFailedException
*/
public function __construct(
private readonly CommandMacroType $type,
private string $name,
string $description = '',
) {
$this->shortName = (new \ReflectionClass($this))->getShortName();
Assertion::notEmptyString($this->name, "{$this->shortName}::name");
Assertion::maxLength($this->name, self::MAX_NAME_LENGTH, "{$this->shortName}::name");
$this->setDescription($description);
}
public function getName(): string
{
return $this->name;
}
public function getType(): CommandMacroType
{
return $this->type;
}
public function getDescription(): string
{
return $this->description;
}
public function setDescription(string $description): void
{
$description = trim($description);
Assertion::maxLength($description, self::MAX_DESCRIPTION_LENGTH, "{$this->shortName}::description");
$this->description = $description;
}
public static function createFromMacro(CommandMacro $macro): self
{
return new self(
$macro->getType(),
$macro->getName(),
$macro->getDescription()
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/CommandMacro/Domain/Model/CommandMacroType.php | centreon/src/Core/CommandMacro/Domain/Model/CommandMacroType.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\CommandMacro\Domain\Model;
enum CommandMacroType: string
{
case Host = '1';
case Service = '2';
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/CommandMacro/Infrastructure/Repository/DbReadCommandMacroRepository.php | centreon/src/Core/CommandMacro/Infrastructure/Repository/DbReadCommandMacroRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\CommandMacro\Infrastructure\Repository;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Infrastructure\DatabaseConnection;
use Core\CommandMacro\Application\Repository\ReadCommandMacroRepositoryInterface;
use Core\CommandMacro\Domain\Model\CommandMacro;
use Core\CommandMacro\Domain\Model\CommandMacroType;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
class DbReadCommandMacroRepository extends AbstractRepositoryRDB implements ReadCommandMacroRepositoryInterface
{
use LoggerTrait;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function findByCommandIdAndType(int $commandId, CommandMacroType $type): array
{
$this->info('Get command macros by command ID and type', ['command_id' => $commandId, 'type' => $type]);
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
SELECT
m.command_command_id,
m.command_macro_name,
m.command_macro_desciption,
m.command_macro_type
FROM `:db`.on_demand_macro_command m
WHERE
m.command_command_id = :commandId
AND m.command_macro_type = :macroType
SQL
));
$statement->bindValue(':macroType', $type->value, \PDO::PARAM_STR);
$statement->bindValue(':commandId', $commandId, \PDO::PARAM_INT);
$statement->execute();
$macros = [];
foreach ($statement->fetchAll(\PDO::FETCH_ASSOC) as $result) {
/** @var array{
* command_command_id:int,
* command_macro_name:string,
* command_macro_desciption:string,
* command_macro_type:string
* } $result */
$macros[] = $this->createCommandMacroFromArray($result);
}
return $macros;
}
/**
* @param array{
* command_command_id:int,
* command_macro_name:string,
* command_macro_desciption:string,
* command_macro_type: string
* } $data
*
* @return CommandMacro
*/
private function createCommandMacroFromArray(array $data): CommandMacro
{
$macro = new CommandMacro(
(int) $data['command_command_id'],
CommandMacroType::from($data['command_macro_type']),
$data['command_macro_name'],
);
$macro->setDescription($data['command_macro_desciption']);
return $macro;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/TimePeriod/Application/UseCase/AddTimePeriod/AddTimePeriodRequest.php | centreon/src/Core/TimePeriod/Application/UseCase/AddTimePeriod/AddTimePeriodRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Application\UseCase\AddTimePeriod;
use Symfony\Component\Validator\Constraints as Assert;
final class AddTimePeriodRequest
{
/**
* @param mixed $name
* @param mixed $alias
* @param array<array{day:int, time_range:string}>|null $days
* @param array<int>|null $templates
* @param array<array{day_range:string, time_range:string}>|null $exceptions
*/
public function __construct(
#[Assert\NotNull]
#[Assert\Type('string')]
#[Assert\Length(min: 1, max: 200)]
public readonly mixed $name,
#[Assert\NotNull]
#[Assert\Type('string')]
#[Assert\Length(min: 1, max: 200)]
public readonly mixed $alias,
#[Assert\NotNull]
#[Assert\Type('array')]
#[Assert\All([
new Assert\Collection(
fields: [
'day' => [
new Assert\NotNull(),
new Assert\Type('integer'),
],
'time_range' => [
new Assert\NotNull(),
new Assert\Type('string'),
],
],
),
])]
public readonly mixed $days,
#[Assert\NotNull]
#[Assert\Type('array')]
#[Assert\All(
new Assert\Type('integer'),
)]
public readonly mixed $templates,
#[Assert\NotNull]
#[Assert\Type('array')]
#[Assert\All([
new Assert\Collection(
fields: [
'day_range' => [
new Assert\NotNull(),
new Assert\Type('string'),
],
'time_range' => [
new Assert\NotNull(),
new Assert\Type('string'),
],
],
),
])]
public readonly mixed $exceptions = [],
) {
}
public function toDto(): AddTimePeriodDto
{
return new AddTimePeriodDto(
is_string($this->name) ? $this->name : '',
is_string($this->alias) ? $this->alias : '',
array_map(
fn (array $day): array => ['day' => $day['day'], 'time_range' => $day['time_range']],
is_array($this->days) ? $this->days : []
),
is_array($this->templates) ? $this->templates : [],
array_map(
fn (array $exception): array => [
'day_range' => $exception['day_range'],
'time_range' => $exception['time_range'],
],
is_array($this->exceptions) ? $this->exceptions : []
),
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/TimePeriod/Application/UseCase/AddTimePeriod/AddTimePeriod.php | centreon/src/Core/TimePeriod/Application/UseCase/AddTimePeriod/AddTimePeriod.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Application\UseCase\AddTimePeriod;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\{ConflictResponse,
CreatedResponse,
ErrorResponse,
InvalidArgumentResponse,
PresenterInterface};
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Common\Domain\TrimmedString;
use Core\TimePeriod\Application\Exception\TimePeriodException;
use Core\TimePeriod\Application\Repository\ReadTimePeriodRepositoryInterface;
use Core\TimePeriod\Application\Repository\WriteTimePeriodRepositoryInterface;
use Core\TimePeriod\Domain\Exception\TimeRangeException;
use Core\TimePeriod\Domain\Model\Day;
use Core\TimePeriod\Domain\Model\ExtraTimePeriod;
use Core\TimePeriod\Domain\Model\Template;
use Core\TimePeriod\Domain\Model\TimePeriod;
final class AddTimePeriod
{
use LoggerTrait;
/**
* @param ReadTimePeriodRepositoryInterface $readTimePeriodRepository
* @param WriteTimePeriodRepositoryInterface $writeTimePeriodRepository
* @param ContactInterface $user
*/
public function __construct(
readonly private ReadTimePeriodRepositoryInterface $readTimePeriodRepository,
readonly private WriteTimePeriodRepositoryInterface $writeTimePeriodRepository,
readonly private ContactInterface $user,
) {
}
/**
* @param AddTimePeriodDto $request
* @param PresenterInterface $presenter
*/
public function __invoke(AddTimePeriodDto $request, PresenterInterface $presenter): void
{
try {
$this->info('Add a new time period', ['request' => $request]);
if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_TIME_PERIODS_READ_WRITE)) {
$this->error('User doesn\'t have sufficient rights to edit time periods', [
'user_id' => $this->user->getId(),
]);
$presenter->setResponseStatus(
new ForbiddenResponse(TimePeriodException::editNotAllowed()->getMessage())
);
return;
}
if ($this->readTimePeriodRepository->nameAlreadyExists(new TrimmedString($request->name))) {
$this->error('A time period with this name already exists');
$presenter->setResponseStatus(
new ConflictResponse(TimePeriodException::nameAlreadyExists($request->name))
);
return;
}
// TODO: add a check to prevent templates loop (see testTemplateLoop() in legacy code)
$newTimePeriod = NewTimePeriodFactory::create($request);
$newTimePeriodId = $this->writeTimePeriodRepository->add($newTimePeriod);
$timePeriod = $this->readTimePeriodRepository->findById($newTimePeriodId);
if ($timePeriod === null) {
throw new \Exception('Impossible to retrieve the time period when it has just been created');
}
$presenter->present(
new CreatedResponse($newTimePeriodId, $this->createResponse($timePeriod))
);
} catch (AssertionFailedException|TimeRangeException $ex) {
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (\Throwable $ex) {
$this->error(
'Error when adding the time period',
['message' => $ex->getMessage(), 'trace' => $ex->getTraceAsString()]
);
$presenter->setResponseStatus(
new ErrorResponse(TimePeriodException::errorWhenAddingTimePeriod())
);
}
}
/**
* @param TimePeriod $timePeriod
*
* @return AddTimePeriodResponse
*/
private function createResponse(TimePeriod $timePeriod): AddTimePeriodResponse
{
$response = new AddTimePeriodResponse();
$response->id = $timePeriod->getId();
$response->name = $timePeriod->getName();
$response->alias = $timePeriod->getAlias();
$response->days = array_map(fn (Day $day) => [
'day' => $day->getDay(),
'time_range' => (string) $day->getTimeRange(),
], $timePeriod->getDays());
$response->templates = array_map(fn (Template $template) => [
'id' => $template->getId(),
'alias' => $template->getAlias(),
], $timePeriod->getTemplates());
$response->exceptions = array_map(fn (ExtraTimePeriod $exception) => [
'id' => $exception->getId(),
'day_range' => $exception->getDayRange(),
'time_range' => (string) $exception->getTimeRange(),
], $timePeriod->getExtraTimePeriods());
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/TimePeriod/Application/UseCase/AddTimePeriod/AddTimePeriodDto.php | centreon/src/Core/TimePeriod/Application/UseCase/AddTimePeriod/AddTimePeriodDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Application\UseCase\AddTimePeriod;
final class AddTimePeriodDto
{
/**
* @param string $name
* @param string $alias
* @param array<array{day: int, time_range: string}> $days
* @param int[] $templates
* @param array<array{day_range: string, time_range: string}> $exceptions
*/
public function __construct(
public readonly string $name,
public readonly string $alias,
public readonly array $days,
public readonly array $templates,
public readonly array $exceptions,
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/TimePeriod/Application/UseCase/AddTimePeriod/AddTimePeriodResponse.php | centreon/src/Core/TimePeriod/Application/UseCase/AddTimePeriod/AddTimePeriodResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Application\UseCase\AddTimePeriod;
final class AddTimePeriodResponse
{
public int $id = 0;
public string $name = '';
public string $alias = '';
/** @var array<array{day: int, time_range: string}> */
public array $days = [];
/** @var array<array{id: int, alias: string}> */
public array $templates = [];
/** @var array<array{id: int, day_range: string, time_range: string}> */
public array $exceptions = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/TimePeriod/Application/UseCase/AddTimePeriod/NewTimePeriodFactory.php | centreon/src/Core/TimePeriod/Application/UseCase/AddTimePeriod/NewTimePeriodFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Application\UseCase\AddTimePeriod;
use Core\TimePeriod\Domain\Model\{
Day,
NewExtraTimePeriod,
NewTimePeriod,
TimeRange
};
final class NewTimePeriodFactory
{
/**
* @param AddTimePeriodDto $dto
*
* @throws \Assert\AssertionFailedException
* @throws \Throwable
*
* @return NewTimePeriod
*/
public static function create(AddTimePeriodDto $dto): NewTimePeriod
{
$newTimePeriod = new NewTimePeriod($dto->name, $dto->alias);
$newTimePeriod->setDays(
array_map(
fn (array $day): Day => new Day(
$day['day'],
new TimeRange($day['time_range']),
),
$dto->days
)
);
$newTimePeriod->setTemplates($dto->templates);
$newTimePeriod->setExtraTimePeriods(
array_map(
fn (array $exception): NewExtraTimePeriod => new NewExtraTimePeriod(
$exception['day_range'],
new TimeRange($exception['time_range'])
),
$dto->exceptions
)
);
return $newTimePeriod;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/TimePeriod/Application/UseCase/FindTimePeriods/FindTimePeriodsResponse.php | centreon/src/Core/TimePeriod/Application/UseCase/FindTimePeriods/FindTimePeriodsResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Application\UseCase\FindTimePeriods;
final class FindTimePeriodsResponse
{
/**
* @var array<array{
* id: int,
* name: string,
* alias: string,
* days: array<array{day: int, time_range: string}>,
* templates: array<array{id: int, alias: string}>,
* exceptions: array<array{id: int, day_range: string, time_range: string}>,
* in_period: boolean
* }>
*/
public array $timePeriods = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/TimePeriod/Application/UseCase/FindTimePeriods/FindTimePeriods.php | centreon/src/Core/TimePeriod/Application/UseCase/FindTimePeriods/FindTimePeriods.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Application\UseCase\FindTimePeriods;
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\TimePeriod\Application\Exception\TimePeriodException;
use Core\TimePeriod\Application\Repository\ReadTimePeriodRepositoryInterface;
use Core\TimePeriod\Domain\Model\Day;
use Core\TimePeriod\Domain\Model\ExtraTimePeriod;
use Core\TimePeriod\Domain\Model\Template;
use Core\TimePeriod\Domain\Model\TimePeriod;
use Core\TimePeriod\Domain\Rules\TimePeriodRuleStrategyInterface;
use Throwable;
use Traversable;
final class FindTimePeriods
{
use LoggerTrait;
/** @var TimePeriodRuleStrategyInterface[] */
private array $strategies;
/**
* @param ReadTimePeriodRepositoryInterface $readTimePeriodRepository
* @param RequestParametersInterface $requestParameters
* @param ContactInterface $user
* @param Traversable<TimePeriodRuleStrategyInterface> $strategies
*/
public function __construct(
readonly private ReadTimePeriodRepositoryInterface $readTimePeriodRepository,
readonly private RequestParametersInterface $requestParameters,
readonly private ContactInterface $user,
Traversable $strategies,
) {
$this->strategies = iterator_to_array($strategies);
}
/**
* @param PresenterInterface $presenter
*/
public function __invoke(PresenterInterface $presenter): void
{
try {
if (
! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_TIME_PERIODS_READ_WRITE)
&& ! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_TIME_PERIODS_READ)
) {
$this->error('User doesn\'t have sufficient rights to see time periods', [
'user_id' => $this->user->getId(),
]);
$presenter->setResponseStatus(
new ForbiddenResponse(TimePeriodException::accessNotAllowed()->getMessage())
);
return;
}
$this->info('Find the time periods', ['parameters' => $this->requestParameters->getSearch()]);
$timePeriods = $this->readTimePeriodRepository->findByRequestParameter($this->requestParameters);
$presenter->present($this->createResponse($timePeriods));
} catch (Throwable $ex) {
$presenter->setResponseStatus(
new ErrorResponse(TimePeriodException::errorWhenSearchingForAllTimePeriods()->getMessage())
);
$this->error(
'Error while searching for time periods',
['message' => $ex->getMessage(), 'trace' => $ex->getTraceAsString()]
);
}
}
/**
* @param TimePeriod[] $timePeriods
*
* @return FindTimePeriodsResponse
*/
private function createResponse(array $timePeriods): FindTimePeriodsResponse
{
$response = new FindTimePeriodsResponse();
foreach ($timePeriods as $timePeriod) {
$response->timePeriods[] = [
'id' => $timePeriod->getId(),
'name' => $timePeriod->getName(),
'alias' => $timePeriod->getAlias(),
'days' => array_map(
fn (Day $day): array => [
'day' => $day->getDay(),
'time_range' => (string) $day->getTimeRange(),
],
$timePeriod->getDays()
),
'templates' => array_map(
fn (Template $template): array => [
'id' => $template->getId(),
'alias' => $template->getAlias(),
],
$timePeriod->getTemplates()
),
'exceptions' => array_map(
fn (ExtraTimePeriod $exception): array => [
'id' => $exception->getId(),
'day_range' => $exception->getDayRange(),
'time_range' => (string) $exception->getTimeRange(),
],
$timePeriod->getExtraTimePeriods()
),
'in_period' => $timePeriod->isDateTimeIncludedInPeriod(new \DateTimeImmutable(), $this->strategies),
];
}
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/TimePeriod/Application/UseCase/DeleteTimePeriod/DeleteTimePeriod.php | centreon/src/Core/TimePeriod/Application/UseCase/DeleteTimePeriod/DeleteTimePeriod.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Application\UseCase\DeleteTimePeriod;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ {
ErrorResponse,
ForbiddenResponse,
NoContentResponse,
NotFoundResponse,
PresenterInterface
};
use Core\TimePeriod\Application\Exception\TimePeriodException;
use Core\TimePeriod\Application\Repository\{
ReadTimePeriodRepositoryInterface, WriteTimePeriodRepositoryInterface
};
final class DeleteTimePeriod
{
use LoggerTrait;
/**
* @param ReadTimePeriodRepositoryInterface $readTimePeriodRepository
* @param WriteTimePeriodRepositoryInterface $writeTimePeriodRepository
* @param ContactInterface $user
*/
public function __construct(
readonly private ReadTimePeriodRepositoryInterface $readTimePeriodRepository,
readonly private WriteTimePeriodRepositoryInterface $writeTimePeriodRepository,
readonly private ContactInterface $user,
) {
}
/**
* @param int $timePeriodId
* @param PresenterInterface $presenter
*/
public function __invoke(int $timePeriodId, PresenterInterface $presenter): void
{
try {
if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_TIME_PERIODS_READ_WRITE)) {
$this->error('User doesn\'t have sufficient rights to edit time periods', [
'user_id' => $this->user->getId(),
]);
$presenter->setResponseStatus(
new ForbiddenResponse(TimePeriodException::editNotAllowed()->getMessage())
);
return;
}
$this->info('Delete a time period', ['id' => $timePeriodId]);
if (! $this->readTimePeriodRepository->exists($timePeriodId)) {
$this->error('Time period not found', ['id' => $timePeriodId]);
$presenter->setResponseStatus(new NotFoundResponse('Time period'));
return;
}
$this->writeTimePeriodRepository->delete($timePeriodId);
$presenter->setResponseStatus(new NoContentResponse());
} catch (\Throwable $ex) {
$this->error(
'Error when deleting the time period',
['id' => $timePeriodId, 'message' => $ex->getMessage(), 'trace' => $ex->getTraceAsString()]
);
$presenter->setResponseStatus(
new ErrorResponse(TimePeriodException::errorOnDelete($timePeriodId)->getMessage())
);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/TimePeriod/Application/UseCase/FindTimePeriod/FindTimePeriod.php | centreon/src/Core/TimePeriod/Application/UseCase/FindTimePeriod/FindTimePeriod.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Application\UseCase\FindTimePeriod;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\{ErrorResponse,
ForbiddenResponse,
NotFoundResponse,
ResponseStatusInterface};
use Core\TimePeriod\Application\Exception\TimePeriodException;
use Core\TimePeriod\Application\Repository\ReadTimePeriodRepositoryInterface;
final class FindTimePeriod
{
use LoggerTrait;
/**
* @param ReadTimePeriodRepositoryInterface $readTimePeriodRepository
* @param ContactInterface $user
*/
public function __construct(
readonly private ReadTimePeriodRepositoryInterface $readTimePeriodRepository,
readonly private ContactInterface $user,
) {
}
/**
* @param int $timePeriodId
*
* @return FindTimePeriodResponse|ResponseStatusInterface
*/
public function __invoke(int $timePeriodId): FindTimePeriodResponse|ResponseStatusInterface
{
try {
if (
! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_TIME_PERIODS_READ_WRITE)
&& ! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_TIME_PERIODS_READ)
) {
$this->error('User doesn\'t have sufficient rights to see time periods', [
'user_id' => $this->user->getId(),
]);
return new ForbiddenResponse(TimePeriodException::accessNotAllowed()->getMessage());
}
$this->info('Find a time period', ['id' => $timePeriodId]);
$timePeriod = $this->readTimePeriodRepository->findById($timePeriodId);
if ($timePeriod === null) {
$this->error('Time period not found', ['id' => $timePeriodId]);
return new NotFoundResponse('Time period');
}
return new FindTimePeriodResponse($timePeriod);
} catch (\Throwable $ex) {
$this->error(
'Error when searching for the time period',
['id' => $timePeriodId, 'message' => $ex->getMessage(), 'trace' => $ex->getTraceAsString()]
);
return new ErrorResponse(TimePeriodException::errorWhenSearchingForTimePeriod($timePeriodId)->getMessage());
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/TimePeriod/Application/UseCase/FindTimePeriod/FindTimePeriodResponse.php | centreon/src/Core/TimePeriod/Application/UseCase/FindTimePeriod/FindTimePeriodResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Application\UseCase\FindTimePeriod;
use Core\Application\Common\UseCase\StandardResponseInterface;
use Core\TimePeriod\Domain\Model\TimePeriod;
final class FindTimePeriodResponse implements StandardResponseInterface
{
public function __construct(readonly public TimePeriod $timePeriod)
{
}
public function getData(): mixed
{
return $this->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/TimePeriod/Application/UseCase/UpdateTimePeriod/UpdateTimePeriod.php | centreon/src/Core/TimePeriod/Application/UseCase/UpdateTimePeriod/UpdateTimePeriod.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Application\UseCase\UpdateTimePeriod;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\{
ConflictResponse,
ErrorResponse,
InvalidArgumentResponse,
NoContentResponse,
NotFoundResponse,
PresenterInterface
};
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Common\Domain\TrimmedString;
use Core\TimePeriod\Application\Exception\TimePeriodException;
use Core\TimePeriod\Application\Repository\ReadTimePeriodRepositoryInterface;
use Core\TimePeriod\Application\Repository\WriteTimePeriodRepositoryInterface;
use Core\TimePeriod\Domain\Exception\TimeRangeException;
use Core\TimePeriod\Domain\Model\{Day, ExtraTimePeriod, Template, TimePeriod, TimeRange};
final class UpdateTimePeriod
{
use LoggerTrait;
public function __construct(
readonly ReadTimePeriodRepositoryInterface $readTimePeriodRepository,
readonly WriteTimePeriodRepositoryInterface $writeTimePeriodRepository,
readonly ContactInterface $user,
) {
}
/**
* @param UpdateTimePeriodRequest $request
* @param PresenterInterface $presenter
*/
public function __invoke(UpdateTimePeriodRequest $request, PresenterInterface $presenter): void
{
$this->info('Updating the time period', ['request' => $request]);
try {
if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_TIME_PERIODS_READ_WRITE)) {
$this->error('User doesn\'t have sufficient rights to edit time periods', [
'user_id' => $this->user->getId(),
]);
$presenter->setResponseStatus(
new ForbiddenResponse(TimePeriodException::editNotAllowed()->getMessage())
);
return;
}
if (($timePeriod = $this->readTimePeriodRepository->findById($request->id)) === null) {
$this->error('Time period not found', ['id' => $request->id]);
$presenter->setResponseStatus(new NotFoundResponse('Time period'));
return;
}
if ($this->readTimePeriodRepository->nameAlreadyExists(new TrimmedString($request->name), $request->id)) {
$this->error('Time period name already exists');
$presenter->setResponseStatus(
new ConflictResponse(TimePeriodException::nameAlreadyExists($request->name))
);
return;
}
// TODO: add a check to prevent templates loop (see testTemplateLoop() in legacy code)
$this->updateTimePeriodAndSave($timePeriod, $request);
$presenter->setResponseStatus(new NoContentResponse());
} catch (AssertionFailedException|TimeRangeException $ex) {
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (\Throwable $ex) {
$this->error(
'Error when updating the time period',
['message' => $ex->getMessage(), 'trace' => $ex->getTraceAsString()]
);
$presenter->setResponseStatus(
new ErrorResponse(TimePeriodException::errorOnUpdate($request->id))
);
}
}
/**
* @param TimePeriod $timePeriod
* @param UpdateTimePeriodRequest $request
*
* @throws AssertionFailedException
* @throws \Throwable
*/
private function updateTimePeriodAndSave(TimePeriod $timePeriod, UpdateTimePeriodRequest $request): void
{
$timePeriod->setName($request->name);
$timePeriod->setAlias($request->alias);
$timePeriod->setDays(
array_map(
fn (array $day): Day => new Day(
$day['day'],
new TimeRange($day['time_range']),
),
$request->days
)
);
$timePeriod->setTemplates(
array_map(
fn (int $templateId): Template => new Template(
$templateId,
'name_not_used'
),
$request->templates
)
);
$timePeriod->setExtraTimePeriods(
array_map(
fn (array $exception): ExtraTimePeriod => new ExtraTimePeriod(
1,
$exception['day_range'],
new TimeRange($exception['time_range'])
),
$request->exceptions
)
);
$this->writeTimePeriodRepository->update($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/TimePeriod/Application/UseCase/UpdateTimePeriod/UpdateTimePeriodRequest.php | centreon/src/Core/TimePeriod/Application/UseCase/UpdateTimePeriod/UpdateTimePeriodRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Application\UseCase\UpdateTimePeriod;
final class UpdateTimePeriodRequest
{
public int $id = 0;
public string $name = '';
public string $alias = '';
/** @var array<array{day: int, time_range: string}> */
public array $days = [];
/** @var int[] */
public array $templates = [];
/** @var array<array{day_range: string, time_range: string}> */
public array $exceptions = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/TimePeriod/Application/Exception/TimePeriodException.php | centreon/src/Core/TimePeriod/Application/Exception/TimePeriodException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Application\Exception;
class TimePeriodException extends \Exception
{
/**
* @param int $timePeriodId
*
* @return self
*/
public static function errorOnDelete(int $timePeriodId): self
{
return new self(sprintf(_('Error when deleting the time period %d'), $timePeriodId));
}
/**
* @param int $timePeriodId
*
* @return self
*/
public static function errorOnUpdate(int $timePeriodId): self
{
return new self(sprintf(_('Error when updating the time period %d'), $timePeriodId));
}
/**
* @return self
*/
public static function errorWhenAddingTimePeriod(): self
{
return new self(_('Error when adding the time period'));
}
/**
* @return self
*/
public static function errorWhenSearchingForAllTimePeriods(): self
{
return new self(_('Error when searching for time periods'));
}
/**
* @param int $timePeriodId
*
* @return self
*/
public static function errorWhenSearchingForTimePeriod(int $timePeriodId): self
{
return new self(sprintf(_('Error when searching for the time period %d'), $timePeriodId));
}
/**
* @param string $timePeriodName
*
* @return self
*/
public static function nameAlreadyExists(string $timePeriodName): self
{
return new self(sprintf(_("The time period name '%s' already exists"), $timePeriodName));
}
/**
* @return self
*/
public static function accessNotAllowed(): self
{
return new self(_('You are not allowed to access time periods'));
}
/**
* @return self
*/
public static function editNotAllowed(): self
{
return new self(_('You are not allowed to edit time periods'));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/TimePeriod/Application/Repository/WriteTimePeriodRepositoryInterface.php | centreon/src/Core/TimePeriod/Application/Repository/WriteTimePeriodRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Application\Repository;
use Core\TimePeriod\Domain\Model\NewTimePeriod;
use Core\TimePeriod\Domain\Model\TimePeriod;
interface WriteTimePeriodRepositoryInterface
{
/**
* @param NewTimePeriod $newTimePeriod
*
* @throws \Throwable
*
* @return int Return the new TimePeriod id
*/
public function add(NewTimePeriod $newTimePeriod): int;
/**
* @param int $timePeriodId
*
* @throws \Throwable
*/
public function delete(int $timePeriodId): void;
/**
* @param TimePeriod $timePeriod
*
* @throws \Throwable
*/
public function update(TimePeriod $timePeriod): 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/TimePeriod/Application/Repository/ReadTimePeriodRepositoryInterface.php | centreon/src/Core/TimePeriod/Application/Repository/ReadTimePeriodRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Application\Repository;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Common\Domain\TrimmedString;
use Core\TimePeriod\Domain\Model\TimePeriod;
interface ReadTimePeriodRepositoryInterface
{
/**
* Find All time period.
*
* @param RequestParametersInterface $requestParameters
*
* @throws \Throwable
*
* @return TimePeriod[]
*/
public function findByRequestParameter(RequestParametersInterface $requestParameters): array;
/**
* @param int $timePeriodId
*
* @throws \Throwable
*
* @return TimePeriod|null
*/
public function findById(int $timePeriodId): ?TimePeriod;
/**
* @param int[] $timePeriodIds
*
* @throws \Throwable
*
* @return TimePeriod[]
*/
public function findByIds(array $timePeriodIds): array;
/**
* @param int $timePeriodId
*
* @throws \Throwable
*
* @return bool
*/
public function exists(int $timePeriodId): bool;
/**
* @param TrimmedString $timePeriodName
* @param int|null $timePeriodId
*
* @return bool
*/
public function nameAlreadyExists(TrimmedString $timePeriodName, ?int $timePeriodId = null): 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/TimePeriod/Domain/Model/TimePeriod.php | centreon/src/Core/TimePeriod/Domain/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\TimePeriod\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Core\TimePeriod\Domain\Rules\TimePeriodRuleStrategyInterface;
class TimePeriod
{
public const MIN_ALIAS_LENGTH = 1;
public const MAX_ALIAS_LENGTH = 200;
public const MIN_NAME_LENGTH = 1;
public const MAX_NAME_LENGTH = 200;
private string $name;
private string $alias;
/** @var list<Template> */
private array $templates = [];
/** @var list<ExtraTimePeriod> */
private array $extraTimePeriods = [];
/** @var list<Day> */
private array $days;
/**
* @param int $id
* @param string $name
* @param string $alias
*
* @throws AssertionFailedException
*/
public function __construct(
readonly private int $id,
string $name,
string $alias,
) {
$this->setName($name);
$this->setAlias($alias);
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @return string
*/
public function getAlias(): string
{
return $this->alias;
}
/**
* @param string $alias
*
* @throws AssertionFailedException
*/
public function setAlias(string $alias): void
{
$alias = trim($alias);
Assertion::minLength($alias, self::MIN_ALIAS_LENGTH, 'TimePeriod::alias');
Assertion::maxLength($alias, self::MAX_ALIAS_LENGTH, 'TimePeriod::alias');
$this->alias = $alias;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @param string $name
*
* @throws AssertionFailedException
*/
public function setName(string $name): void
{
$name = trim($name);
Assertion::minLength($name, self::MIN_NAME_LENGTH, 'TimePeriod::name');
Assertion::maxLength($name, self::MAX_NAME_LENGTH, 'TimePeriod::name');
$this->name = $name;
}
/**
* @param list<ExtraTimePeriod> $extraTimePeriods
*/
public function setExtraTimePeriods(array $extraTimePeriods): void
{
$this->extraTimePeriods = [];
foreach ($extraTimePeriods as $extra) {
$this->addExtraTimePeriod($extra);
}
}
/**
* @param ExtraTimePeriod $extraTimePeriod
*/
public function addExtraTimePeriod(ExtraTimePeriod $extraTimePeriod): void
{
$this->extraTimePeriods[] = $extraTimePeriod;
}
/**
* @return ExtraTimePeriod[]
*/
public function getExtraTimePeriods(): array
{
return $this->extraTimePeriods;
}
/**
* @return list<Template>
*/
public function getTemplates(): array
{
return $this->templates;
}
/**
* @param list<Template> $templates
*/
public function setTemplates(array $templates): void
{
$this->templates = [];
foreach ($templates as $template) {
$this->addTemplate($template);
}
}
/**
* @param Template $template
*/
public function addTemplate(Template $template): void
{
$this->templates[] = $template;
}
/**
* @param Day $day
*/
public function addDay(Day $day): void
{
$this->days[] = $day;
}
/**
* @return Day[]
*/
public function getDays(): array
{
return $this->days;
}
/**
* @param Day[] $days
*/
public function setDays(array $days): void
{
$this->days = [];
foreach ($days as $day) {
$this->addDay($day);
}
}
/**
* @param \DateTimeInterface $dateTime
* @param TimePeriodRuleStrategyInterface[] $strategies
*
* @return bool
*/
public function isDateTimeIncludedInPeriod(\DateTimeInterface $dateTime, array $strategies): bool
{
foreach ($strategies as $strategy) {
foreach ($this->getDays() as $day) {
$ranges = $day->getTimeRange()->getRanges();
if (
$strategy->supports($ranges)
&& $strategy->isIncluded($dateTime, $day->getDay(), $ranges)
) {
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/TimePeriod/Domain/Model/Template.php | centreon/src/Core/TimePeriod/Domain/Model/Template.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
class Template
{
public const MIN_ALIAS_LENGTH = TimePeriod::MIN_ALIAS_LENGTH;
public const MAX_ALIAS_LENGTH = TimePeriod::MAX_ALIAS_LENGTH;
/**
* @param int $id
* @param string $alias
*
* @throws AssertionFailedException
*/
public function __construct(readonly private int $id, private string $alias)
{
Assertion::min($id, 1, 'Template::id');
$this->alias = trim($alias);
Assertion::minLength(
$this->alias,
self::MIN_ALIAS_LENGTH,
'Template::alias'
);
Assertion::maxLength(
$this->alias,
self::MAX_ALIAS_LENGTH,
'Template::alias'
);
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @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/TimePeriod/Domain/Model/Day.php | centreon/src/Core/TimePeriod/Domain/Model/Day.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Domain\Model;
use Centreon\Domain\Common\Assertion\Assertion;
class Day
{
/** @var int ISO 8601 numeric representation of the day of the week (1 for monday) */
private int $day;
private TimeRange $timeRange;
/**
* @param int $day
* @param TimeRange $timeRange
*
* @throws \Assert\AssertionFailedException
*/
public function __construct(int $day, TimeRange $timeRange)
{
Assertion::min($day, 1, 'TimePeriodDay::day');
Assertion::max($day, 7, 'TimePeriodDay::day');
$this->day = $day;
$this->timeRange = $timeRange;
}
/**
* @return int
*/
public function getDay(): int
{
return $this->day;
}
/**
* @return TimeRange
*/
public function getTimeRange(): TimeRange
{
return $this->timeRange;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/TimePeriod/Domain/Model/NewExtraTimePeriod.php | centreon/src/Core/TimePeriod/Domain/Model/NewExtraTimePeriod.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Domain\Model;
use Centreon\Domain\Common\Assertion\Assertion;
class NewExtraTimePeriod
{
public const MIN_DAY_RANGE_LENGTH = 1;
public const MAX_DAY_RANGE_LENGTH = 2048;
/**
* @param string $dayRange
* @param TimeRange $timeRange
*
* @throws \Assert\AssertionFailedException
*/
public function __construct(private string $dayRange, private TimeRange $timeRange)
{
$this->dayRange = trim($this->dayRange);
Assertion::minLength(
$this->dayRange,
self::MIN_DAY_RANGE_LENGTH,
(new \ReflectionClass($this))->getShortName() . '::dayRange'
);
Assertion::maxLength(
$this->dayRange,
self::MAX_DAY_RANGE_LENGTH,
(new \ReflectionClass($this))->getShortName() . '::dayRange'
);
}
/**
* @param string $dayRange
*/
public function setDayRange(string $dayRange): void
{
$this->dayRange = $dayRange;
}
/**
* @return string
*/
public function getDayRange(): string
{
return $this->dayRange;
}
/**
* @param TimeRange $timeRange
*/
public function setTimeRange(TimeRange $timeRange): void
{
$this->timeRange = $timeRange;
}
/**
* @return TimeRange
*/
public function getTimeRange(): TimeRange
{
return $this->timeRange;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/TimePeriod/Domain/Model/TimeRange.php | centreon/src/Core/TimePeriod/Domain/Model/TimeRange.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Domain\Model;
use Centreon\Domain\Common\Assertion\Assertion;
use Core\TimePeriod\Domain\Exception\TimeRangeException;
/**
* Value object.
*/
class TimeRange implements \Stringable
{
/**
* @var string TIME_RANGE_FULL_DAY_ALIAS The time range for the entire day in DOC
*/
private const TIME_RANGE_FULL_DAY_ALIAS = '00:00-00:00';
/** @var string Comma-delimited time range (00:00-12:00) for a particular day of the week. */
private string $timeRange;
/**
* @param string $timeRange
*
* @throws \Assert\AssertionFailedException
* @throws TimeRangeException
*/
public function __construct(string $timeRange)
{
Assertion::minLength($timeRange, 11, 'TimeRange::timeRange');
if (! $this->isValidTimeRangeFormat($timeRange)) {
throw TimeRangeException::badTimeRangeFormat($timeRange);
}
if (! $this->areTimeRangesOrderedWithoutOverlap($timeRange)) {
throw TimeRangeException::orderTimeIntervalsNotConsistent();
}
$this->timeRange = $timeRange;
}
/**
* @return string
*/
public function __toString(): string
{
return $this->timeRange;
}
/**
* @return array<array{start: string, end: string}>
*/
public function getRanges(): array
{
return $this->extractRange($this->timeRange);
}
/**
* Check the format of the time range(s).
* 00:00-12:00,13:00-14:00,...
*
* @param string $timeRange
*
* @return bool Return false if the time range(s) is wrong formatted
*/
private function isValidTimeRangeFormat(string $timeRange): bool
{
return (bool) preg_match(
"/^((?'time_range'(?'time'(([[0-1][0-9]|2[0-3]):[0-5][0-9]))-((?&time)|24:00))(,(?&time_range))*)$/",
$timeRange
);
}
/**
* We check whether the time intervals are consistent in the defined order.
* - The end time of a time range cannot be greater than or equal to the start time of a time range.
* - The start of a new time range cannot be less than or equal to the end of the previous time range.
*
* @param string $timeRanges Time ranges (00:00-12:00,13:00-14:00,...)
*
* @return bool
*/
private function areTimeRangesOrderedWithoutOverlap(string $timeRanges): bool
{
$previousEndTime = null;
if ($timeRanges === self::TIME_RANGE_FULL_DAY_ALIAS) {
return true;
}
foreach (explode(',', $timeRanges) as $timeRange) {
[$start, $end] = explode('-', $timeRange);
// The start of a new time range cannot be less than or equal to the end of the previous time range
if ($previousEndTime !== null && strtotime($previousEndTime) >= strtotime($start)) {
return false;
}
// The end time of a time range cannot be greater than or equal to the start time of a time range
if (strtotime($start) >= strtotime($end)) {
return false;
}
$previousEndTime = $end;
}
return true;
}
/**
* @param string $rule
*
* @return array<array{start: string, end: string}>
*/
private function extractRange(string $rule): array
{
return $this->extractRanges($rule);
}
/**
* @param string $rule
*
* @return array<array{start: string, end: string}>
*/
private function extractRanges(string $rule): array
{
$timePeriodRanges = explode(',', trim($rule));
$timeRanges = [];
foreach ($timePeriodRanges as $timePeriodRange) {
[$start, $end] = explode('-', trim($timePeriodRange));
$timeRanges[] = ['start' => $start, 'end' => $end];
}
return $timeRanges;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/TimePeriod/Domain/Model/ExtraTimePeriod.php | centreon/src/Core/TimePeriod/Domain/Model/ExtraTimePeriod.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
class ExtraTimePeriod extends NewExtraTimePeriod
{
/**
* @param int $id
* @param string $dayRange
* @param TimeRange $timeRange
*
* @throws AssertionFailedException
*/
public function __construct(private int $id, private string $dayRange, private TimeRange $timeRange)
{
Assertion::min($id, 1, 'ExtraTimePeriod::id');
parent::__construct($this->dayRange, $this->timeRange);
}
/**
* @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/TimePeriod/Domain/Model/NewTimePeriod.php | centreon/src/Core/TimePeriod/Domain/Model/NewTimePeriod.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Domain\Model;
use Centreon\Domain\Common\Assertion\Assertion;
class NewTimePeriod
{
public const MIN_NAME_LENGTH = 1;
public const MAX_NAME_LENGTH = 200;
public const MIN_ALIAS_LENGTH = 1;
public const MAX_ALIAS_LENGTH = 200;
private string $name;
private string $alias;
/** @var int[] */
private array $templates = [];
/** @var Day[] */
private array $days = [];
/** @var NewExtraTimePeriod[] */
private array $extraTimePeriods = [];
/**
* @param string $name
* @param string $alias
*
* @throws \Assert\AssertionFailedException
*/
public function __construct(
string $name,
string $alias,
) {
$name = trim($name);
Assertion::minLength($name, self::MIN_NAME_LENGTH, 'NewTimePeriod::name');
Assertion::maxLength($name, self::MAX_NAME_LENGTH, 'NewTimePeriod::name');
$alias = trim($alias);
Assertion::minLength($alias, self::MIN_ALIAS_LENGTH, 'NewTimePeriod::alias');
Assertion::maxLength($alias, self::MAX_ALIAS_LENGTH, 'NewTimePeriod::alias');
$this->name = $name;
$this->alias = $alias;
}
/**
* @param NewExtraTimePeriod $exception
*/
public function addExtraTimePeriod(NewExtraTimePeriod $exception): void
{
$this->extraTimePeriods[] = $exception;
}
/**
* @param int $template
*/
public function addTemplate(int $template): void
{
$this->templates[] = $template;
}
/**
* @return string
*/
public function getAlias(): string
{
return $this->alias;
}
/**
* @return Day[]
*/
public function getDays(): array
{
return $this->days;
}
/**
* @return NewExtraTimePeriod[]
*/
public function getExtraTimePeriods(): array
{
return $this->extraTimePeriods;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @return int[]
*/
public function getTemplates(): array
{
return $this->templates;
}
/**
* @param Day $day
*/
public function addDay(Day $day): void
{
$this->days[] = $day;
}
/**
* @param Day[] $days
*/
public function setDays(array $days): void
{
$this->days = [];
foreach ($days as $day) {
$this->addDay($day);
}
}
/**
* @param NewExtraTimePeriod[] $extraTimePeriods
*/
public function setExtraTimePeriods(array $extraTimePeriods): void
{
$this->extraTimePeriods = [];
foreach ($extraTimePeriods as $exception) {
$this->addExtraTimePeriod($exception);
}
}
/**
* @param int[] $templates
*/
public function setTemplates(array $templates): void
{
$this->templates = [];
foreach ($templates as $template) {
$this->addTemplate($template);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/TimePeriod/Domain/Rules/TimePeriodRuleStrategyInterface.php | centreon/src/Core/TimePeriod/Domain/Rules/TimePeriodRuleStrategyInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Domain\Rules;
use DateTimeInterface;
interface TimePeriodRuleStrategyInterface
{
/**
* @param DateTimeInterface $dateTime
* @param int $dayRule
* @param array{start: string, end: string}|array<array{start: string, end: string}> $ranges
*
* @return bool
*/
public function isIncluded(DateTimeInterface $dateTime, int $dayRule, array $ranges): bool;
/**
* @param mixed $data
*
* @return bool
*/
public function supports(mixed $data): 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/TimePeriod/Domain/Rules/Strategies/SimpleDayTimeRangeRuleStrategy.php | centreon/src/Core/TimePeriod/Domain/Rules/Strategies/SimpleDayTimeRangeRuleStrategy.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Domain\Rules\Strategies;
use Core\TimePeriod\Domain\Rules\TimePeriodRuleStrategyInterface;
use DateTimeInterface;
class SimpleDayTimeRangeRuleStrategy implements TimePeriodRuleStrategyInterface
{
/**
* @param DateTimeInterface $dateTime
* @param int $dayRule
* @param array<array{start: string, end: string}> $ranges
*
* @return bool
*/
public function isIncluded(DateTimeInterface $dateTime, int $dayRule, array $ranges): bool
{
$day = (int) $dateTime->format('N');
if ($day !== $dayRule) {
return false;
}
$time = $dateTime->format('H:i');
foreach ($ranges as $range) {
if ($time >= $range['start'] && $time <= $range['end']) {
return true;
}
}
return false;
}
/**
* @param mixed $data
*
* @return bool
*/
public function supports(mixed $data): bool
{
return is_array($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/TimePeriod/Domain/Exception/TimeRangeException.php | centreon/src/Core/TimePeriod/Domain/Exception/TimeRangeException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Domain\Exception;
class TimeRangeException extends \InvalidArgumentException
{
/**
* @param string $badTimeRange
*
* @return self
*/
public static function badTimeRangeFormat(string $badTimeRange): self
{
return new self(sprintf(_('The time range format is wrong (%s)'), $badTimeRange));
}
/**
* @return self
*/
public static function orderTimeIntervalsNotConsistent(): self
{
return new self(_('The order of the time intervals is not consistent'));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/TimePeriod/Infrastructure/Repository/DbWriteTimePeriodActionLogRepository.php | centreon/src/Core/TimePeriod/Infrastructure/Repository/DbWriteTimePeriodActionLogRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Infrastructure\Repository;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Repository\RepositoryException;
use Centreon\Infrastructure\DatabaseConnection;
use Core\ActionLog\Application\Repository\WriteActionLogRepositoryInterface;
use Core\ActionLog\Domain\Model\ActionLog;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\TimePeriod\Application\Repository\ReadTimePeriodRepositoryInterface;
use Core\TimePeriod\Application\Repository\WriteTimePeriodRepositoryInterface;
use Core\TimePeriod\Domain\Model\Day;
use Core\TimePeriod\Domain\Model\{NewExtraTimePeriod, NewTimePeriod, Template, TimePeriod};
class DbWriteTimePeriodActionLogRepository extends AbstractRepositoryRDB implements WriteTimePeriodRepositoryInterface
{
use LoggerTrait;
public const TIMEPERIOD_OBJECT_TYPE = 'timeperiod';
public function __construct(
private readonly WriteTimePeriodRepositoryInterface $writeTimePeriodRepository,
private readonly ReadTimePeriodRepositoryInterface $readTimePeriodRepository,
private readonly ContactInterface $contact,
private readonly WriteActionLogRepositoryInterface $writeActionLogRepository,
DatabaseConnection $db,
) {
$this->db = $db;
}
/**
* @inheritDoc
*/
public function delete(int $timePeriodId): void
{
try {
$timePeriod = $this->readTimePeriodRepository->findById($timePeriodId);
if ($timePeriod === null) {
throw new RepositoryException('Cannot find timeperiod to delete');
}
$this->writeTimePeriodRepository->delete($timePeriodId);
$actionLog = new ActionLog(
self::TIMEPERIOD_OBJECT_TYPE,
$timePeriodId,
$timePeriod->getName(),
ActionLog::ACTION_TYPE_DELETE,
$this->contact->getId()
);
$this->writeActionLogRepository->addAction($actionLog);
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
throw $ex;
}
}
/**
* @inheritDoc
*/
public function add(NewTimePeriod $timePeriod): int
{
try {
$timePeriodId = $this->writeTimePeriodRepository->add($timePeriod);
if ($timePeriodId === 0) {
throw new RepositoryException('Timeperiod ID cannot be 0');
}
$actionLog = new ActionLog(
self::TIMEPERIOD_OBJECT_TYPE,
$timePeriodId,
$timePeriod->getName(),
ActionLog::ACTION_TYPE_ADD,
$this->contact->getId()
);
$actionLogId = $this->writeActionLogRepository->addAction($actionLog);
$actionLog->setId($actionLogId);
$details = $this->getTimePeriodPropertiesAsArray($timePeriod);
$this->writeActionLogRepository->addActionDetails($actionLog, $details);
return $timePeriodId;
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
throw $ex;
}
}
/**
* @inheritDoc
*/
public function update(TimePeriod $timePeriod): void
{
try {
$currentTimePeriod = $this->readTimePeriodRepository->findById($timePeriod->getId());
if ($currentTimePeriod === null) {
throw new RepositoryException('Cannot find timeperiod to update');
}
$currentTimePeriodDetails = $this->getTimePeriodPropertiesAsArray($currentTimePeriod);
$updatedTimePeriodDetails = $this->getTimePeriodPropertiesAsArray($timePeriod);
$diff = array_diff_assoc($updatedTimePeriodDetails, $currentTimePeriodDetails);
$this->writeTimePeriodRepository->update($timePeriod);
$actionLog = new ActionLog(
self::TIMEPERIOD_OBJECT_TYPE,
$timePeriod->getId(),
$timePeriod->getName(),
ActionLog::ACTION_TYPE_CHANGE,
$this->contact->getId()
);
$actionLogId = $this->writeActionLogRepository->addAction($actionLog);
if ($actionLogId === 0) {
throw new RepositoryException('Action log ID cannot be 0');
}
$actionLog->setId($actionLogId);
$this->writeActionLogRepository->addActionDetails($actionLog, $updatedTimePeriodDetails);
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
throw $ex;
}
}
/**
* @param NewTimePeriod|TimePeriod $timePeriod
*
* @return array<string,string|int|bool>
*/
private function getTimePeriodPropertiesAsArray(NewTimePeriod|TimePeriod $timePeriod): array
{
$timePeriodAsArray = [];
$timePeriodReflection = new \ReflectionClass($timePeriod);
foreach ($timePeriodReflection->getProperties() as $property) {
$value = $property->getValue($timePeriod);
if ($value === null) {
$value = '';
}
if (is_array($value)) {
if ($value === []) {
$value = '';
} elseif ($value[0] instanceof Day) {
$days = [];
foreach ($value as $day) {
$dayAsString = match ($day->getDay()) {
1 => 'monday',
2 => 'tuesday',
3 => 'wednesday',
4 => 'thursday',
5 => 'friday',
6 => 'saturday',
7 => 'sunday',
default => throw new RepositoryException('Should never happen'),
};
$days[$dayAsString] = $day->getTimeRange()->__toString();
}
$value = $days;
} elseif ($value[0] instanceof NewExtraTimePeriod) {
$exceptions = [
'nbOfExceptions' => count($value),
];
foreach ($value as $key => $extra) {
$exceptions["exceptionInput_{$key}"] = $extra->getDayRange();
$exceptions["exceptionTimerange_{$key}"] = $extra->getTimeRange()->__toString();
}
$value = $exceptions;
} elseif ($value[0] instanceof Template) {
$value = implode(
',',
array_map(
fn (Template $tpl) => $tpl->getId(),
$value
)
);
} elseif (is_int($value[0])) {
$value = implode(
',',
$value
);
}
}
if (is_array($value)) {
$timePeriodAsArray = array_merge($timePeriodAsArray, $value);
} else {
$timePeriodAsArray[$property->getName()] = $value;
}
}
return $timePeriodAsArray;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/TimePeriod/Infrastructure/Repository/DbWriteTimePeriodRepository.php | centreon/src/Core/TimePeriod/Infrastructure/Repository/DbWriteTimePeriodRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Infrastructure\Repository;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\TimePeriod\Application\Repository\WriteTimePeriodRepositoryInterface;
use Core\TimePeriod\Domain\Model\{ExtraTimePeriod, NewExtraTimePeriod, NewTimePeriod, Template, TimePeriod};
class DbWriteTimePeriodRepository extends AbstractRepositoryRDB implements WriteTimePeriodRepositoryInterface
{
use LoggerTrait;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function add(NewTimePeriod $newTimePeriod): int
{
$alreadyInTransaction = $this->db->inTransaction();
if (! $alreadyInTransaction) {
$this->db->beginTransaction();
}
try {
$statement = $this->db->prepare(
$this->translateDbName(
<<<'SQL'
INSERT INTO `:db`.timeperiod
(tp_name, tp_alias, tp_sunday, tp_monday, tp_tuesday, tp_wednesday,
tp_thursday, tp_friday, tp_saturday)
VALUES
(:name, :alias, :sunday, :monday, :tuesday, :wednesday, :thursday, :friday, :saturday)
SQL
)
);
$this->bindValueOfTimePeriod($statement, $newTimePeriod);
$statement->execute();
$newTimePeriodId = (int) $this->db->lastInsertId();
$this->addTimePeriodTemplates($newTimePeriodId, $newTimePeriod->getTemplates());
$this->addExtraTimePeriods($newTimePeriodId, $newTimePeriod->getExtraTimePeriods());
if (! $alreadyInTransaction) {
$this->db->commit();
}
return $newTimePeriodId;
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
if (! $alreadyInTransaction) {
$this->db->rollBack();
}
throw $ex;
}
}
/**
* @inheritDoc
*/
public function delete(int $timePeriodId): void
{
$statement = $this->db->prepare(
$this->translateDbName('DELETE FROM `:db`.timeperiod WHERE tp_id = :id')
);
$statement->bindValue(':id', $timePeriodId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @inheritDoc
*/
public function update(TimePeriod $timePeriod): void
{
$alreadyInTransaction = $this->db->inTransaction();
if (! $alreadyInTransaction) {
$this->db->beginTransaction();
}
try {
$statement = $this->db->prepare(
$this->translateDbName(
<<<'SQL'
UPDATE `:db`.timeperiod
SET tp_name = :name,
tp_alias = :alias,
tp_monday = :monday,
tp_tuesday = :tuesday,
tp_wednesday = :wednesday,
tp_thursday = :thursday,
tp_friday = :friday,
tp_saturday = :saturday,
tp_sunday = :sunday
WHERE tp_id = :id
SQL
)
);
$this->bindValueOfTimePeriod($statement, $timePeriod);
$statement->bindValue(':id', $timePeriod->getId(), \PDO::PARAM_INT);
$statement->execute();
$this->deleteExtraTimePeriods($timePeriod->getId());
$this->deleteTimePeriodTemplates($timePeriod->getId());
$templateIds = array_map(fn (Template $template): int => $template->getId(), $timePeriod->getTemplates());
$this->addTimePeriodTemplates($timePeriod->getId(), $templateIds);
$this->addExtraTimePeriods($timePeriod->getId(), $timePeriod->getExtraTimePeriods());
if (! $alreadyInTransaction) {
$this->db->commit();
}
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
if (! $alreadyInTransaction) {
$this->db->rollBack();
}
throw $ex;
}
}
/**
* @param int $timePeriodId
* @param list<ExtraTimePeriod|NewExtraTimePeriod> $extraTimePeriods
*
* @throws \PDOException
*/
private function addExtraTimePeriods(int $timePeriodId, array $extraTimePeriods): void
{
if ($extraTimePeriods === []) {
return;
}
$subRequest = [];
$bindValues = [];
foreach ($extraTimePeriods as $index => $extraTimePeriod) {
$subRequest[$index] = "(:timeperiod_id_{$index}, :days_{$index}, :timerange_{$index})";
$bindValues[$index]['day'] = $extraTimePeriod->getDayRange();
$bindValues[$index]['timerange'] = $extraTimePeriod->getTimeRange();
}
$statement = $this->db->prepare(
$this->translateDbName(
<<<'SQL'
INSERT INTO `:db`.timeperiod_exceptions
(timeperiod_id, days, timerange)
VALUES
SQL . implode(', ', $subRequest)
)
);
foreach ($bindValues as $index => $extraTimePeriod) {
$statement->bindValue(':timeperiod_id_' . $index, $timePeriodId, \PDO::PARAM_INT);
$statement->bindValue(':days_' . $index, $extraTimePeriod['day']);
$statement->bindValue(':timerange_' . $index, $extraTimePeriod['timerange']);
}
$statement->execute();
}
/**
* @param int $timePeriodId
* @param list<int> $templateIds
*
* @throws \PDOException
*/
private function addTimePeriodTemplates(int $timePeriodId, array $templateIds): void
{
if ($templateIds === []) {
return;
}
$subRequest = [];
$bindValues = [];
foreach ($templateIds as $index => $templateId) {
$subRequest[$index] = "(:timeperiod_id_{$index}, :template_id_{$index})";
$bindValues[$index] = $templateId;
}
$statement = $this->db->prepare(
$this->translateDbName(
<<<'SQL'
INSERT INTO `:db`.timeperiod_include_relations
(timeperiod_id, timeperiod_include_id)
VALUES
SQL . implode(', ', $subRequest)
)
);
foreach ($bindValues as $index => $templateId) {
$statement->bindValue(':timeperiod_id_' . $index, $timePeriodId, \PDO::PARAM_INT);
$statement->bindValue(':template_id_' . $index, $templateId, \PDO::PARAM_INT);
}
$statement->execute();
}
/**
* @param \PDOStatement $statement
* @param TimePeriod|NewTimePeriod $timePeriod
*/
private function bindValueOfTimePeriod(\PDOStatement $statement, TimePeriod|NewTimePeriod $timePeriod): void
{
$statement->bindValue(':name', $timePeriod->getName());
$statement->bindValue(':alias', $timePeriod->getAlias());
$statement->bindValue(':monday', $this->extractTimeRange($timePeriod, 1));
$statement->bindValue(':tuesday', $this->extractTimeRange($timePeriod, 2));
$statement->bindValue(':wednesday', $this->extractTimeRange($timePeriod, 3));
$statement->bindValue(':thursday', $this->extractTimeRange($timePeriod, 4));
$statement->bindValue(':friday', $this->extractTimeRange($timePeriod, 5));
$statement->bindValue(':saturday', $this->extractTimeRange($timePeriod, 6));
$statement->bindValue(':sunday', $this->extractTimeRange($timePeriod, 7));
}
/**
* @param int $timePeriodId
*
* @throws \PDOException
*/
private function deleteExtraTimePeriods(int $timePeriodId): void
{
$statement = $this->db->prepare(
$this->translateDbName('DELETE FROM `:db`.timeperiod_exceptions WHERE timeperiod_id = :id')
);
$statement->bindValue(':id', $timePeriodId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @param int $timePeriodId
*
* @throws \PDOException
*/
private function deleteTimePeriodTemplates(int $timePeriodId): void
{
$statement = $this->db->prepare(
$this->translateDbName('DELETE FROM `:db`.timeperiod_include_relations WHERE timeperiod_id = :id')
);
$statement->bindValue(':id', $timePeriodId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @param TimePeriod|NewTimePeriod $timePeriod
* @param int $id
*
* @return string|null
*/
private function extractTimeRange(TimePeriod|NewTimePeriod $timePeriod, int $id): ?string
{
foreach ($timePeriod->getDays() as $day) {
if ($day->getDay() === $id) {
return (string) $day->getTimeRange();
}
}
return null;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/TimePeriod/Infrastructure/Repository/DbReadTimePeriodRepository.php | centreon/src/Core/TimePeriod/Infrastructure/Repository/DbReadTimePeriodRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Infrastructure\Repository;
use Assert\AssertionFailedException;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use Core\Common\Domain\TrimmedString;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\TimePeriod\Application\Repository\ReadTimePeriodRepositoryInterface;
use Core\TimePeriod\Domain\Exception\TimeRangeException;
use Core\TimePeriod\Domain\Model\{Day, ExtraTimePeriod, Template, TimePeriod, TimeRange};
use Utility\SqlConcatenator;
/**
* @phpstan-type _timeperiod array{
* tp_id: int,
* tp_name: string,
* tp_alias: string,
* tp_monday: string,
* tp_tuesday: string,
* tp_wednesday: string,
* tp_thursday: string,
* tp_friday: string,
* tp_saturday: string,
* tp_sunday: string,
* template_id: int,
* }
*/
class DbReadTimePeriodRepository extends AbstractRepositoryRDB implements ReadTimePeriodRepositoryInterface
{
use LoggerTrait;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function exists(int $timePeriodId): bool
{
$this->info('Does the time period exist?', ['id' => $timePeriodId]);
$statement = $this->db->prepare(
$this->translateDbName('SELECT 1 FROM `:db`.timeperiod WHERE tp_id = :id')
);
$statement->bindValue(':id', $timePeriodId, \PDO::PARAM_INT);
$statement->execute();
return ! empty($statement->fetch());
}
/**
* @inheritDoc
*/
public function findById(int $timePeriodId): ?TimePeriod
{
$this->info('Find time period by id', ['id' => $timePeriodId]);
$statement = $this->db->prepare(
$this->translateDbName('SELECT * FROM `:db`.timeperiod WHERE tp_id = :id')
);
$statement->bindValue(':id', $timePeriodId, \PDO::PARAM_INT);
$statement->execute();
if (($result = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
/**
* @var _timeperiod $result
*/
$newTimePeriod = $this->createTimePeriod($result);
$timePeriod[$newTimePeriod->getId()] = $newTimePeriod;
$this->addTemplates($timePeriod);
$this->addExtraTimePeriods($timePeriod);
return $timePeriod[$newTimePeriod->getId()];
}
return null;
}
/**
* @inheritDoc
*/
public function findByIds(array $timePeriodIds): array
{
if ($timePeriodIds === []) {
return $timePeriodIds;
}
$concatenator = new SqlConcatenator();
$concatenator->defineSelect(<<<'SQL'
SELECT * FROM `:db`.timeperiod WHERE tp_id IN (:ids)
SQL);
$concatenator->storeBindValueMultiple(':ids', $timePeriodIds, \PDO::PARAM_INT);
$statement = $this->db->prepare($this->translateDbName($concatenator->__toString()));
$concatenator->bindValuesToStatement($statement);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
$timeperiods = [];
foreach ($statement as $row) {
/**
* @var _timeperiod $row
*/
$timeperiods[] = $this->createTimePeriod($row);
}
return $timeperiods;
}
/**
* @inheritDoc
*/
public function findByRequestParameter(RequestParametersInterface $requestParameters): array
{
$this->info('Find time periods by request parameter');
$sqlRequestTranslator = new SqlRequestParametersTranslator($requestParameters);
$sqlRequestTranslator
->getRequestParameters()
->setConcordanceStrictMode(RequestParameters::CONCORDANCE_MODE_STRICT);
$sqlRequestTranslator->setConcordanceArray([
'id' => 'tp_id',
'name' => 'tp_name',
'alias' => 'tp_alias',
]);
$request = $this->translateDbName('SELECT SQL_CALC_FOUND_ROWS tp.* FROM `:db`.timeperiod tp');
// Search
$request .= $sqlRequestTranslator->translateSearchParameterToSql();
// Sort
$sortRequest = $sqlRequestTranslator->translateSortParameterToSql();
$request .= ! is_null($sortRequest)
? $sortRequest
: ' ORDER BY tp_id ASC';
// Pagination
$request .= $sqlRequestTranslator->translatePaginationToSql();
$statement = $this->db->prepare($request);
foreach ($sqlRequestTranslator->getSearchValues() as $key => $data) {
$type = key($data);
if ($type !== null) {
$value = $data[$type];
$statement->bindValue($key, $value, $type);
}
}
$statement->execute();
$result = $this->db->query('SELECT FOUND_ROWS()');
if ($result !== false && ($total = $result->fetchColumn()) !== false) {
$sqlRequestTranslator->getRequestParameters()->setTotal((int) $total);
}
/**
* @var array<int, TimePeriod> $timePeriods
*/
$timePeriods = [];
while (($result = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
/**
* @var _timeperiod $result
*/
$timePeriod = $this->createTimePeriod($result);
$timePeriods[$result['tp_id']] = $timePeriod;
}
$this->addTemplates($timePeriods);
$this->addExtraTimePeriods($timePeriods);
return $timePeriods;
}
/**
* @inheritDoc
*/
public function nameAlreadyExists(TrimmedString $timePeriodName, ?int $timePeriodId = null): bool
{
$statement = $this->db->prepare(
$this->translateDbName('SELECT tp_id FROM `:db`.timeperiod WHERE tp_name = :name')
);
$statement->bindValue(':name', $timePeriodName->value);
$statement->execute();
/**
* @var array{tp_id: int}|false $result
*/
$result = $statement->fetch(\PDO::FETCH_ASSOC);
if ($timePeriodId !== null) {
if ($result !== false) {
return $result['tp_id'] !== $timePeriodId;
}
return false;
}
return ! (empty($result));
}
/**
* @param list<TimePeriod> $timePeriods
*
* @throws AssertionFailedException
* @throws TimeRangeException
* @throws \PDOException
*/
private function addExtraTimePeriods(array $timePeriods): void
{
if ($timePeriods === []) {
return;
}
$timePeriodIds = array_keys($timePeriods);
$timePeriodIncludeRequest = str_repeat('?, ', count($timePeriodIds) - 1) . '?';
$requestTemplates = $this->translateDbName(
<<<SQL
SELECT *
FROM `:db`.timeperiod_exceptions
WHERE timeperiod_id IN ({$timePeriodIncludeRequest})
ORDER BY timeperiod_id ASC, exception_id ASC
SQL
);
$statement = $this->db->prepare($requestTemplates);
$statement->execute($timePeriodIds);
while (($result = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
/**
* @var array{
* exception_id: int,
* timeperiod_id: int,
* days: string,
* timerange: string,
* } $result
*/
$timePeriods[$result['timeperiod_id']]->addExtraTimePeriod(
new ExtraTimePeriod(
$result['exception_id'],
$result['days'],
new TimeRange($result['timerange'])
)
);
}
}
/**
* @param list<TimePeriod> $timePeriods
*
* @throws \PDOException
*/
private function addTemplates(array $timePeriods): void
{
if ($timePeriods === []) {
return;
}
$timePeriodIds = array_keys($timePeriods);
$timePeriodIncludeRequest = str_repeat('?, ', count($timePeriodIds) - 1) . '?';
$requestTemplates = $this->translateDbName(
<<<SQL
SELECT rel.timeperiod_id, tp.tp_id, tp.tp_alias
FROM `:db`.timeperiod tp
INNER JOIN `:db`.timeperiod_include_relations rel
ON rel.timeperiod_include_id = tp.tp_id
WHERE rel.timeperiod_id IN ({$timePeriodIncludeRequest})
ORDER BY rel.timeperiod_id ASC, rel.include_id ASC
SQL
);
$statement = $this->db->prepare($requestTemplates);
$statement->execute($timePeriodIds);
while (($result = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
/**
* @var array{
* tp_id: int,
* tp_alias: string,
* timeperiod_id: int,
* } $result
*/
$timePeriods[$result['timeperiod_id']]->addTemplate(
new Template($result['tp_id'], $result['tp_alias'])
);
}
}
/**
* @param _timeperiod $data
*
* @throws AssertionFailedException
* @throws TimeRangeException
*
* @return TimePeriod
*/
private function createTimePeriod(array $data): TimePeriod
{
$timePeriod = new TimePeriod(
$data['tp_id'],
$data['tp_name'],
$data['tp_alias'],
);
$days = [];
$weekdays = [1 => 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
foreach ($weekdays as $id => $name) {
if (($timeRange = $data['tp_' . $name]) !== null && $timeRange !== '') {
$days[] = new Day($id, new TimeRange($timeRange));
}
}
$timePeriod->setDays($days);
return $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/TimePeriod/Infrastructure/API/AddTimePeriod/AddTimePeriodsPresenter.php | centreon/src/Core/TimePeriod/Infrastructure/API/AddTimePeriod/AddTimePeriodsPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Infrastructure\API\AddTimePeriod;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\CreatedResponse;
use Core\Application\Common\UseCase\PresenterInterface;
use Core\Infrastructure\Common\Api\Router;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\TimePeriod\Application\UseCase\AddTimePeriod\AddTimePeriodResponse;
class AddTimePeriodsPresenter extends AbstractPresenter implements PresenterInterface
{
use LoggerTrait;
private const ROUTE_NAME = 'FindTimePeriod';
private const ROUTE_TIME_PERIOD_ID = 'id';
/**
* @param PresenterFormatterInterface $presenterFormatter
* @param Router $router
*/
public function __construct(PresenterFormatterInterface $presenterFormatter, readonly private Router $router)
{
$this->presenterFormatter = $presenterFormatter;
parent::__construct($presenterFormatter);
}
/**
* @inheritDoc
*/
public function present(mixed $data): void
{
if (
$data instanceof CreatedResponse
&& $data->getPayload() instanceof AddTimePeriodResponse
) {
$payload = $data->getPayload();
$data->setPayload([
'id' => $payload->id,
'name' => $payload->name,
'alias' => $payload->alias,
'days' => $payload->days,
'templates' => $payload->templates,
'exceptions' => $payload->exceptions,
]);
try {
$this->setResponseHeaders([
'Location' => $this->router->generate(self::ROUTE_NAME, [self::ROUTE_TIME_PERIOD_ID => $payload->id]),
]);
} catch (\Throwable $ex) {
$this->error('Impossible to generate the location header', [
'message' => $ex->getMessage(),
'trace' => $ex->getTraceAsString(),
'route' => self::ROUTE_NAME,
'payload' => $payload,
]);
}
}
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/TimePeriod/Infrastructure/API/AddTimePeriod/AddTimePeriodController.php | centreon/src/Core/TimePeriod/Infrastructure/API/AddTimePeriod/AddTimePeriodController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Infrastructure\API\AddTimePeriod;
use Centreon\Application\Controller\AbstractController;
use Core\TimePeriod\Application\UseCase\AddTimePeriod\{AddTimePeriod, AddTimePeriodRequest};
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\MapRequestPayload;
final class AddTimePeriodController extends AbstractController
{
/**
* @param AddTimePeriod $useCase
* @param AddTimePeriodRequest $request
* @param AddTimePeriodsPresenter $presenter
*
* @return Response
*/
public function __invoke(
AddTimePeriod $useCase,
#[MapRequestPayload] AddTimePeriodRequest $request,
AddTimePeriodsPresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($request->toDto(), $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/TimePeriod/Infrastructure/API/FindTimePeriods/FindTimePeriodsController.php | centreon/src/Core/TimePeriod/Infrastructure/API/FindTimePeriods/FindTimePeriodsController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Infrastructure\API\FindTimePeriods;
use Centreon\Application\Controller\AbstractController;
use Core\TimePeriod\Application\UseCase\FindTimePeriods\FindTimePeriods;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class FindTimePeriodsController extends AbstractController
{
/**
* @param FindTimePeriods $useCase
* @param FindTimePeriodsPresenter $presenter
*
* @throws AccessDeniedException
*
* @return object
*/
public function __invoke(
FindTimePeriods $useCase,
FindTimePeriodsPresenter $presenter,
): object {
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($presenter);
return $presenter->show();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/TimePeriod/Infrastructure/API/FindTimePeriods/FindTimePeriodsPresenter.php | centreon/src/Core/TimePeriod/Infrastructure/API/FindTimePeriods/FindTimePeriodsPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Infrastructure\API\FindTimePeriods;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\PresenterInterface;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\TimePeriod\Application\UseCase\FindTimePeriods\FindTimePeriodsResponse;
class FindTimePeriodsPresenter extends AbstractPresenter implements PresenterInterface
{
/**
* @param RequestParametersInterface $requestParameters
* @param PresenterFormatterInterface $presenterFormatter
*/
public function __construct(
readonly private RequestParametersInterface $requestParameters,
PresenterFormatterInterface $presenterFormatter,
) {
parent::__construct($presenterFormatter);
}
/**
* {@inheritDoc}
*
* @param FindTimePeriodsResponse $data
*/
public function present(mixed $data): void
{
$response = [
'result' => [],
];
foreach ($data->timePeriods as $timePeriod) {
$response['result'][] = [
'id' => $timePeriod['id'],
'name' => $timePeriod['name'],
'alias' => $timePeriod['alias'],
'days' => $timePeriod['days'],
'templates' => $timePeriod['templates'],
'exceptions' => $timePeriod['exceptions'],
'in_period' => $timePeriod['in_period'],
];
}
$response['meta'] = $this->requestParameters->toArray();
parent::present($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/TimePeriod/Infrastructure/API/DeleteTimePeriod/DeleteTimePeriodController.php | centreon/src/Core/TimePeriod/Infrastructure/API/DeleteTimePeriod/DeleteTimePeriodController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Infrastructure\API\DeleteTimePeriod;
use Centreon\Application\Controller\AbstractController;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\TimePeriod\Application\UseCase\DeleteTimePeriod\DeleteTimePeriod;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class DeleteTimePeriodController extends AbstractController
{
/**
* @param DeleteTimePeriod $useCase
* @param DefaultPresenter $presenter
* @param int $id
*
* @throws AccessDeniedException
*
* @return object
*/
public function __invoke(DeleteTimePeriod $useCase, DefaultPresenter $presenter, int $id): object
{
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($id, $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/TimePeriod/Infrastructure/API/FindTimePeriod/DayNormalizer.php | centreon/src/Core/TimePeriod/Infrastructure/API/FindTimePeriod/DayNormalizer.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Infrastructure\API\FindTimePeriod;
use Core\TimePeriod\Domain\Model\Day;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Serializer\Exception\ExceptionInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
class DayNormalizer implements NormalizerInterface
{
public function __construct(
#[Autowire(service: 'serializer.normalizer.object')]
private readonly NormalizerInterface $normalizer,
) {
}
/**
* @param Day $object
* @param string|null $format
* @param array<string, mixed> $context
*
* @throws ExceptionInterface
*
* @return array<string, mixed>
*/
public function normalize(mixed $object, ?string $format = null, array $context = []): array
{
/** @var array<string, mixed> $data */
$data = $this->normalizer->normalize($object, $format, $context);
if (is_array($data) && array_key_exists('time_range', $data)) {
$data['time_range'] = (string) $object->getTimeRange();
}
return $data;
}
/**
* @param array<string, mixed> $context
* @param mixed $data
* @param ?string $format
*/
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof Day;
}
/**
* @param ?string $format
* @return array<class-string|'*'|'object'|string, bool|null>
*/
public function getSupportedTypes(?string $format): array
{
return [
Day::class => 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/TimePeriod/Infrastructure/API/FindTimePeriod/FindTimePeriodController.php | centreon/src/Core/TimePeriod/Infrastructure/API/FindTimePeriod/FindTimePeriodController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Infrastructure\API\FindTimePeriod;
use Centreon\Application\Controller\AbstractController;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Infrastructure\Common\Api\StandardPresenter;
use Core\TimePeriod\Application\UseCase\FindTimePeriod\FindTimePeriod;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Exception\ExceptionInterface;
final class FindTimePeriodController extends AbstractController
{
/**
* @param FindTimePeriod $useCase
* @param StandardPresenter $presenter
* @param int $id
*
* @throws ExceptionInterface
*
* @return Response
*/
public function __invoke(FindTimePeriod $useCase, StandardPresenter $presenter, int $id): Response
{
$this->denyAccessUnlessGrantedForApiConfiguration();
$response = $useCase($id);
if ($response instanceof ResponseStatusInterface) {
return $this->createResponse($response);
}
return JsonResponse::fromJsonString(
$presenter->present($response, ['groups' => ['TimePeriod:Read']])
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/TimePeriod/Infrastructure/API/FindTimePeriod/TimePeriodNormalizer.php | centreon/src/Core/TimePeriod/Infrastructure/API/FindTimePeriod/TimePeriodNormalizer.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Infrastructure\API\FindTimePeriod;
use Core\TimePeriod\Domain\Model\TimePeriod;
use Core\TimePeriod\Domain\Rules\TimePeriodRuleStrategyInterface;
use DateTimeImmutable;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Serializer\Exception\ExceptionInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Traversable;
class TimePeriodNormalizer implements NormalizerInterface
{
/** @var TimePeriodRuleStrategyInterface[] */
private array $strategies;
/**
* @param Traversable<TimePeriodRuleStrategyInterface> $strategies
* @param NormalizerInterface $normalizer
*/
public function __construct(
#[Autowire(service: 'serializer.normalizer.object')]
private readonly NormalizerInterface $normalizer,
Traversable $strategies,
) {
$this->strategies = iterator_to_array($strategies);
}
/**
* @param TimePeriod $object
* @param string|null $format
* @param array<string, mixed> $context
*
* @throws ExceptionInterface
*
* @return array<string, mixed>
*/
public function normalize(
mixed $object,
?string $format = null,
array $context = [],
): array {
/** @var array<string, bool|float|int|string> $data */
$data = $this->normalizer->normalize($object, $format, $context);
$data['in_period'] = $object->isDateTimeIncludedInPeriod(new DateTimeImmutable(), $this->strategies);
return $data;
}
/**
* @param array<string, mixed> $context
* @param mixed $data
* @param ?string $format
*/
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof TimePeriod;
}
/**
* @param ?string $format
* @return array<class-string|'*'|'object'|string, bool|null>
*/
public function getSupportedTypes(?string $format): array
{
return [
TimePeriod::class => 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/TimePeriod/Infrastructure/API/FindTimePeriod/ExtraTimePeriodNormalizer.php | centreon/src/Core/TimePeriod/Infrastructure/API/FindTimePeriod/ExtraTimePeriodNormalizer.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Infrastructure\API\FindTimePeriod;
use Core\TimePeriod\Domain\Model\ExtraTimePeriod;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Serializer\Exception\ExceptionInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
class ExtraTimePeriodNormalizer implements NormalizerInterface
{
public function __construct(
#[Autowire(service: 'serializer.normalizer.object')]
private readonly NormalizerInterface $normalizer,
) {
}
/**
* @param ExtraTimePeriod $object
* @param string|null $format
* @param array<string, mixed> $context
*
* @throws ExceptionInterface
*
* @return array<string, mixed>
*/
public function normalize(mixed $object, ?string $format = null, array $context = []): array
{
/** @var array<string, mixed> $data */
$data = $this->normalizer->normalize($object, $format, $context);
if (is_array($data) && array_key_exists('time_range', $data)) {
$data['time_range'] = (string) $object->getTimeRange();
}
return $data;
}
/**
* @param mixed $data
* @param ?string $format
* @param array<string, mixed> $context
*/
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof ExtraTimePeriod;
}
/**
* @param ?string $format
* @return array<class-string|'*'|'object'|string, bool|null>
*/
public function getSupportedTypes(?string $format): array
{
return [
ExtraTimePeriod::class => 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/TimePeriod/Infrastructure/API/UpdateTimePeriod/UpdateTimePeriodController.php | centreon/src/Core/TimePeriod/Infrastructure/API/UpdateTimePeriod/UpdateTimePeriodController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\TimePeriod\Infrastructure\API\UpdateTimePeriod;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\TimePeriod\Application\UseCase\UpdateTimePeriod\UpdateTimePeriod;
use Core\TimePeriod\Application\UseCase\UpdateTimePeriod\UpdateTimePeriodRequest;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class UpdateTimePeriodController extends AbstractController
{
use LoggerTrait;
/**
* @param Request $request
* @param UpdateTimePeriod $useCase
* @param DefaultPresenter $presenter
* @param int $id
*
* @throws AccessDeniedException
*
* @return object
*/
public function __invoke(
Request $request,
UpdateTimePeriod $useCase,
DefaultPresenter $presenter,
int $id,
): object {
$this->denyAccessUnlessGrantedForApiConfiguration();
try {
/**
* @var array{
* name: string,
* alias: string,
* days: array<array{
* day: integer,
* time_range: string
* }>,
* templates: int[],
* exceptions: array<array{
* day_range: string,
* time_range: string
* }>
* } $dataSent
*/
$dataSent = $this->validateAndRetrieveDataSent($request, __DIR__ . '/UpdateTimePeriodSchema.json');
$dtoRequest = $this->createDtoRequest($dataSent, $id);
$useCase($dtoRequest, $presenter);
} catch (\InvalidArgumentException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
}
return $presenter->show();
}
/**
* @param array{
* name: string,
* alias: string,
* days: array<array{
* day: integer,
* time_range: string
* }>,
* templates: int[],
* exceptions: array<array{
* day_range: string,
* time_range: string
* }>
* } $dataSent
* @param int $id
*
* @return UpdateTimePeriodRequest
*/
private function createDtoRequest(array $dataSent, int $id): UpdateTimePeriodRequest
{
$dto = new UpdateTimePeriodRequest();
$dto->id = $id;
$dto->name = $dataSent['name'];
$dto->alias = $dataSent['alias'];
$dto->days = array_map(
fn (array $day): array => [
'day' => $day['day'],
'time_range' => $day['time_range'],
],
$dataSent['days']
);
$dto->templates = $dataSent['templates'];
$dto->exceptions = array_map(
fn (array $exception): array => [
'day_range' => $exception['day_range'],
'time_range' => $exception['time_range'],
],
$dataSent['exceptions']
);
return $dto;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostSeverity/Application/UseCase/AddHostSeverity/AddHostSeverityRequest.php | centreon/src/Core/HostSeverity/Application/UseCase/AddHostSeverity/AddHostSeverityRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\HostSeverity\Application\UseCase\AddHostSeverity;
final class AddHostSeverityRequest
{
public string $name = '';
public string $alias = '';
public int $level = 0;
public int $iconId = 0;
public bool $isActivated = true;
public ?string $comment = 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/HostSeverity/Application/UseCase/AddHostSeverity/AddHostSeverityResponse.php | centreon/src/Core/HostSeverity/Application/UseCase/AddHostSeverity/AddHostSeverityResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\HostSeverity\Application\UseCase\AddHostSeverity;
final class AddHostSeverityResponse
{
public int $id = 0;
public string $name = '';
public string $alias = '';
public int $level = 0;
public int $iconId = 0;
public bool $isActivated = true;
public ?string $comment = 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/HostSeverity/Application/UseCase/AddHostSeverity/AddHostSeverity.php | centreon/src/Core/HostSeverity/Application/UseCase/AddHostSeverity/AddHostSeverity.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\HostSeverity\Application\UseCase\AddHostSeverity;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ConflictResponse;
use Core\Application\Common\UseCase\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\Common\Domain\TrimmedString;
use Core\HostSeverity\Application\Exception\HostSeverityException;
use Core\HostSeverity\Application\Repository\ReadHostSeverityRepositoryInterface;
use Core\HostSeverity\Application\Repository\WriteHostSeverityRepositoryInterface;
use Core\HostSeverity\Domain\Model\HostSeverity;
use Core\HostSeverity\Domain\Model\NewHostSeverity;
use Core\HostSeverity\Infrastructure\API\AddHostSeverity\AddHostSeverityPresenter;
use Core\ViewImg\Application\Repository\ReadViewImgRepositoryInterface;
final class AddHostSeverity
{
use LoggerTrait;
public function __construct(
private readonly WriteHostSeverityRepositoryInterface $writeHostSeverityRepository,
private readonly ReadHostSeverityRepositoryInterface $readHostSeverityRepository,
private readonly ReadViewImgRepositoryInterface $readViewImgRepository,
private readonly ContactInterface $user,
) {
}
/**
* @param AddHostSeverityRequest $request
* @param AddHostSeverityPresenter $presenter
*/
public function __invoke(AddHostSeverityRequest $request, PresenterInterface $presenter): void
{
try {
if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ_WRITE)) {
$this->error(
"User doesn't have sufficient rights to add host severities",
['user_id' => $this->user->getId()]
);
$presenter->setResponseStatus(
new ForbiddenResponse(HostSeverityException::writeActionsNotAllowed())
);
} elseif ($this->readHostSeverityRepository->existsByName(new TrimmedString($request->name))) {
$this->error(
'Host severity name already exists',
['hostseverity_name' => $request->name]
);
$presenter->setResponseStatus(
new ConflictResponse(HostSeverityException::hostNameAlreadyExists())
);
} elseif (
$request->iconId === 0
|| ! $this->readViewImgRepository->existsOne($request->iconId)
) {
$this->error(
'Host severity icon does not exist',
['hostseverity_name' => $request->name]
);
$presenter->setResponseStatus(
new ConflictResponse(HostSeverityException::iconDoesNotExist($request->iconId))
);
} else {
$newHostSeverity = new NewHostSeverity(
$request->name,
$request->alias,
$request->level,
$request->iconId,
);
$newHostSeverity->setActivated($request->isActivated);
$newHostSeverity->setComment($request->comment);
$hostSeverityId = $this->writeHostSeverityRepository->add($newHostSeverity);
$hostSeverity = $this->readHostSeverityRepository->findById($hostSeverityId);
$this->info('Add a new host severity', ['hostseverity_id' => $hostSeverityId]);
if (! $hostSeverity) {
$presenter->setResponseStatus(
new ErrorResponse(HostSeverityException::errorWhileRetrievingObject())
);
return;
}
$presenter->present(
new CreatedResponse($hostSeverityId, $this->createResponse($hostSeverity))
);
}
} catch (AssertionFailedException $ex) {
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (\Throwable $ex) {
$presenter->setResponseStatus(
new ErrorResponse(HostSeverityException::addHostSeverity($ex))
);
$this->error($ex->getMessage());
}
}
/**
* @param HostSeverity|null $hostSeverity
*
* @return AddHostSeverityResponse
*/
private function createResponse(?HostSeverity $hostSeverity): AddHostSeverityResponse
{
$response = new AddHostSeverityResponse();
if ($hostSeverity !== null) {
$response->id = $hostSeverity->getId();
$response->name = $hostSeverity->getName();
$response->alias = $hostSeverity->getAlias();
$response->level = $hostSeverity->getLevel();
$response->iconId = $hostSeverity->getIconId();
$response->isActivated = $hostSeverity->isActivated();
$response->comment = $hostSeverity->getComment();
}
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/HostSeverity/Application/UseCase/FindHostSeverity/FindHostSeverityResponse.php | centreon/src/Core/HostSeverity/Application/UseCase/FindHostSeverity/FindHostSeverityResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\HostSeverity\Application\UseCase\FindHostSeverity;
final class FindHostSeverityResponse
{
public int $id = 0;
public string $name = '';
public string $alias = '';
public int $level = 0;
public int $iconId = 0;
public bool $isActivated = true;
public ?string $comment = 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/HostSeverity/Application/UseCase/FindHostSeverity/FindHostSeverity.php | centreon/src/Core/HostSeverity/Application/UseCase/FindHostSeverity/FindHostSeverity.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\HostSeverity\Application\UseCase\FindHostSeverity;
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\HostSeverity\Application\Exception\HostSeverityException;
use Core\HostSeverity\Application\Repository\ReadHostSeverityRepositoryInterface;
use Core\HostSeverity\Domain\Model\HostSeverity;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
final class FindHostSeverity
{
use LoggerTrait;
/**
* @param ReadHostSeverityRepositoryInterface $readHostSeverityRepository
* @param ReadAccessGroupRepositoryInterface $readAccessGroupRepositoryInterface
* @param ContactInterface $user
*/
public function __construct(
private ReadHostSeverityRepositoryInterface $readHostSeverityRepository,
private ReadAccessGroupRepositoryInterface $readAccessGroupRepositoryInterface,
private ContactInterface $user,
) {
}
/**
* @param int $hostSeverityId
* @param PresenterInterface $presenter
*/
public function __invoke(int $hostSeverityId, PresenterInterface $presenter): void
{
try {
if ($this->user->isAdmin()) {
if (! $this->readHostSeverityRepository->exists($hostSeverityId)) {
$this->error('Host severity not found', [
'hostseverity_id' => $hostSeverityId,
]);
$presenter->setResponseStatus(new NotFoundResponse('Host severity'));
return;
}
$this->retrieveObjectAndSetResponse($presenter, $hostSeverityId);
} elseif (
$this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ)
|| $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ_WRITE)
) {
$this->debug(
'User is not admin, use ACLs to retrieve a host severity',
['user' => $this->user->getName(), 'hostseverity_id' => $hostSeverityId]
);
$accessGroups = $this->readAccessGroupRepositoryInterface->findByContact($this->user);
if (! $this->readHostSeverityRepository->existsByAccessGroups($hostSeverityId, $accessGroups)) {
$this->error('Host severity not found', [
'hostseverity_id' => $hostSeverityId,
'accessgroups' => $accessGroups,
]);
$presenter->setResponseStatus(new NotFoundResponse('Host severity'));
return;
}
$this->retrieveObjectAndSetResponse($presenter, $hostSeverityId);
} else {
$this->error(
"User doesn't have sufficient rights to see host severities",
['user_id' => $this->user->getId()]
);
$presenter->setResponseStatus(
new ForbiddenResponse(HostSeverityException::accessNotAllowed())
);
}
} catch (\Throwable $ex) {
$presenter->setResponseStatus(
new ErrorResponse(HostSeverityException::findHostSeverity($ex, $hostSeverityId))
);
$this->error($ex->getMessage());
}
}
/**
* @param HostSeverity $hostSeverity
*
* @return FindHostSeverityResponse
*/
private function createResponse(HostSeverity $hostSeverity): FindHostSeverityResponse
{
$response = new FindHostSeverityResponse();
$response->id = $hostSeverity->getId();
$response->name = $hostSeverity->getName();
$response->alias = $hostSeverity->getAlias();
$response->level = $hostSeverity->getLevel();
$response->iconId = $hostSeverity->getIconId();
$response->isActivated = $hostSeverity->isActivated();
$response->comment = $hostSeverity->getComment();
return $response;
}
/**
* Retrieve host severity and set response with object or error if retrieving fails.
*
* @param PresenterInterface $presenter
* @param int $hostSeverityId
*/
private function retrieveObjectAndSetResponse(PresenterInterface $presenter, int $hostSeverityId): void
{
$hostSeverity = $this->readHostSeverityRepository->findById($hostSeverityId);
if (! $hostSeverity) {
$presenter->setResponseStatus(
new ErrorResponse(HostSeverityException::errorWhileRetrievingObject())
);
return;
}
$presenter->present($this->createResponse($hostSeverity));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostSeverity/Application/UseCase/UpdateHostSeverity/UpdateHostSeverity.php | centreon/src/Core/HostSeverity/Application/UseCase/UpdateHostSeverity/UpdateHostSeverity.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\HostSeverity\Application\UseCase\UpdateHostSeverity;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ConflictResponse;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Application\Common\UseCase\PresenterInterface;
use Core\Common\Domain\TrimmedString;
use Core\HostSeverity\Application\Exception\HostSeverityException;
use Core\HostSeverity\Application\Repository\ReadHostSeverityRepositoryInterface;
use Core\HostSeverity\Application\Repository\WriteHostSeverityRepositoryInterface;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\ViewImg\Application\Repository\ReadViewImgRepositoryInterface;
final class UpdateHostSeverity
{
use LoggerTrait;
public function __construct(
private readonly WriteHostSeverityRepositoryInterface $writeHostSeverityRepository,
private readonly ReadHostSeverityRepositoryInterface $readHostSeverityRepository,
private readonly ReadViewImgRepositoryInterface $readViewImgRepository,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly ContactInterface $user,
) {
}
/**
* @param UpdateHostSeverityRequest $request
* @param DefaultPresenter $presenter
*/
public function __invoke(UpdateHostSeverityRequest $request, PresenterInterface $presenter): void
{
try {
if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ_WRITE)) {
$this->error(
"User doesn't have sufficient rights to update host severities",
['user_id' => $this->user->getId()]
);
$presenter->setResponseStatus(
new ForbiddenResponse(HostSeverityException::writeActionsNotAllowed())
);
return;
}
if ($this->user->isAdmin()) {
if (! $this->readHostSeverityRepository->exists($request->id)) {
$this->error('Host severity not found', [
'hostseverity_id' => $request->id,
]);
$presenter->setResponseStatus(new NotFoundResponse('Host severity'));
return;
}
} else {
$accessGroups = $this->readAccessGroupRepository->findByContact($this->user);
if (! $this->readHostSeverityRepository->existsByAccessGroups($request->id, $accessGroups)) {
$this->error('Host severity not found', [
'hostseverity_id' => $request->id,
'accessgroups' => $accessGroups,
]);
$presenter->setResponseStatus(new NotFoundResponse('Host severity'));
return;
}
}
$hostSeverity = $this->readHostSeverityRepository->findById($request->id);
if (! $hostSeverity) {
$presenter->setResponseStatus(
new ErrorResponse(HostSeverityException::errorWhileRetrievingObject())
);
return;
}
if (
$hostSeverity->getName() !== $request->name
&& $this->readHostSeverityRepository->existsByName(new TrimmedString($request->name))
) {
$this->error(
'Host severity name already exists',
['hostseverity_name' => $request->name]
);
$presenter->setResponseStatus(
new ConflictResponse(HostSeverityException::hostNameAlreadyExists())
);
return;
}
if (
$request->iconId === 0
|| ! $this->readViewImgRepository->existsOne($request->iconId)
) {
$this->error(
'Host severity icon does not exist',
['hostseverity_name' => $request->name]
);
$presenter->setResponseStatus(
new ConflictResponse(HostSeverityException::iconDoesNotExist($request->iconId))
);
return;
}
$hostSeverity->setName($request->name);
$hostSeverity->setAlias($request->alias);
$hostSeverity->setIconId($request->iconId);
$hostSeverity->setLevel($request->level);
$hostSeverity->setActivated($request->isActivated);
$hostSeverity->setComment($request->comment);
$this->writeHostSeverityRepository->update($hostSeverity);
$presenter->setResponseStatus(new NoContentResponse());
} catch (AssertionFailedException $ex) {
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (\Throwable $ex) {
$presenter->setResponseStatus(
new ErrorResponse(HostSeverityException::updateHostSeverity($ex))
);
$this->error($ex->getMessage());
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostSeverity/Application/UseCase/UpdateHostSeverity/UpdateHostSeverityRequest.php | centreon/src/Core/HostSeverity/Application/UseCase/UpdateHostSeverity/UpdateHostSeverityRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\HostSeverity\Application\UseCase\UpdateHostSeverity;
final class UpdateHostSeverityRequest
{
public int $id = 0;
public string $name = '';
public string $alias = '';
public int $level = 0;
/** @var int<0, max> */
public int $iconId = 0;
public bool $isActivated = true;
public ?string $comment = 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/HostSeverity/Application/UseCase/FindHostSeverities/FindHostSeverities.php | centreon/src/Core/HostSeverity/Application/UseCase/FindHostSeverities/FindHostSeverities.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\HostSeverity\Application\UseCase\FindHostSeverities;
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\HostSeverity\Application\Exception\HostSeverityException;
use Core\HostSeverity\Application\Repository\ReadHostSeverityRepositoryInterface;
use Core\HostSeverity\Domain\Model\HostSeverity;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
final class FindHostSeverities
{
use LoggerTrait;
/**
* @param ReadHostSeverityRepositoryInterface $readHostSeverityRepository
* @param ReadAccessGroupRepositoryInterface $readAccessGroupRepositoryInterface
* @param RequestParametersInterface $requestParameters
* @param ContactInterface $user
*/
public function __construct(
private ReadHostSeverityRepositoryInterface $readHostSeverityRepository,
private ReadAccessGroupRepositoryInterface $readAccessGroupRepositoryInterface,
private RequestParametersInterface $requestParameters,
private ContactInterface $user,
) {
}
/**
* @param PresenterInterface $presenter
*/
public function __invoke(PresenterInterface $presenter): void
{
try {
if ($this->user->isAdmin()) {
$hostSeverities = $this->readHostSeverityRepository->findAll($this->requestParameters);
$presenter->present($this->createResponse($hostSeverities));
} elseif (
$this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ)
|| $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ_WRITE)
) {
$this->debug(
'User is not admin, use ACLs to retrieve host severities',
['user' => $this->user->getName()]
);
$accessGroups = $this->readAccessGroupRepositoryInterface->findByContact($this->user);
$hostSeverities = $this->readHostSeverityRepository->findAllByAccessGroups(
$accessGroups,
$this->requestParameters
);
$presenter->present($this->createResponse($hostSeverities));
} else {
$this->error(
"User doesn't have sufficient rights to see host severities",
['user_id' => $this->user->getId()]
);
$presenter->setResponseStatus(
new ForbiddenResponse(HostSeverityException::accessNotAllowed())
);
}
} catch (\Throwable $ex) {
$presenter->setResponseStatus(
new ErrorResponse(HostSeverityException::findHostSeverities($ex))
);
$this->error($ex->getMessage());
}
}
/**
* @param HostSeverity[] $hostSeverities
*
* @return FindHostSeveritiesResponse
*/
private function createResponse(
array $hostSeverities,
): FindHostSeveritiesResponse {
$response = new FindHostSeveritiesResponse();
foreach ($hostSeverities as $hostSeverity) {
$response->hostSeverities[] = [
'id' => $hostSeverity->getId(),
'name' => $hostSeverity->getName(),
'alias' => $hostSeverity->getAlias(),
'level' => $hostSeverity->getLevel(),
'iconId' => $hostSeverity->getIconId(),
'isActivated' => $hostSeverity->isActivated(),
'comment' => $hostSeverity->getComment(),
];
}
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/HostSeverity/Application/UseCase/FindHostSeverities/FindHostSeveritiesResponse.php | centreon/src/Core/HostSeverity/Application/UseCase/FindHostSeverities/FindHostSeveritiesResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\HostSeverity\Application\UseCase\FindHostSeverities;
final class FindHostSeveritiesResponse
{
/**
* @var array<array{
* id: int,
* name: string,
* alias: string,
* level: int,
* iconId: int,
* isActivated: bool,
* comment: string|null
* }>
*/
public array $hostSeverities = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostSeverity/Application/UseCase/DeleteHostSeverity/DeleteHostSeverity.php | centreon/src/Core/HostSeverity/Application/UseCase/DeleteHostSeverity/DeleteHostSeverity.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\HostSeverity\Application\UseCase\DeleteHostSeverity;
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\HostSeverity\Application\Exception\HostSeverityException;
use Core\HostSeverity\Application\Repository\ReadHostSeverityRepositoryInterface;
use Core\HostSeverity\Application\Repository\WriteHostSeverityRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
final class DeleteHostSeverity
{
use LoggerTrait;
public function __construct(
private readonly WriteHostSeverityRepositoryInterface $writeHostSeverityRepository,
private readonly ReadHostSeverityRepositoryInterface $readHostSeverityRepository,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepositoryInterface,
private ContactInterface $user,
) {
}
/**
* @param int $hostSeverityId
* @param PresenterInterface $presenter
*/
public function __invoke(int $hostSeverityId, PresenterInterface $presenter): void
{
try {
if ($this->user->isAdmin()) {
if ($this->readHostSeverityRepository->exists($hostSeverityId)) {
$this->writeHostSeverityRepository->deleteById($hostSeverityId);
$presenter->setResponseStatus(new NoContentResponse());
} else {
$this->error(
'Host severity not found',
['hostseverity_id' => $hostSeverityId]
);
$presenter->setResponseStatus(new NotFoundResponse('Host severity'));
}
} elseif ($this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ_WRITE)) {
$accessGroups = $this->readAccessGroupRepositoryInterface->findByContact($this->user);
if ($this->readHostSeverityRepository->existsByAccessGroups($hostSeverityId, $accessGroups)) {
$this->writeHostSeverityRepository->deleteById($hostSeverityId);
$presenter->setResponseStatus(new NoContentResponse());
$this->info('Delete a host severity', ['hostseverity_id' => $hostSeverityId]);
} else {
$this->error(
'Host severity not found',
['hostseverity_id' => $hostSeverityId, 'accessgroups' => $accessGroups]
);
$presenter->setResponseStatus(new NotFoundResponse('Host severity'));
}
} else {
$this->error(
"User doesn't have sufficient rights to delete host severities",
['user_id' => $this->user->getId()]
);
$presenter->setResponseStatus(
new ForbiddenResponse(HostSeverityException::deleteNotAllowed())
);
}
} catch (\Throwable $ex) {
$presenter->setResponseStatus(
new ErrorResponse(HostSeverityException::deleteHostSeverity($ex))
);
$this->error($ex->getMessage());
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostSeverity/Application/Exception/HostSeverityException.php | centreon/src/Core/HostSeverity/Application/Exception/HostSeverityException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\HostSeverity\Application\Exception;
class HostSeverityException extends \Exception
{
/**
* @return self
*/
public static function accessNotAllowed(): self
{
return new self(_('You are not allowed to access host severities'));
}
/**
* @param \Throwable $ex
*
* @return self
*/
public static function findHostSeverities(\Throwable $ex): self
{
return new self(_('Error while searching for host severities'), 0, $ex);
}
/**
* @param \Throwable $ex
* @param int $hostSeverityId
*
* @return self
*/
public static function findHostSeverity(\Throwable $ex, int $hostSeverityId): self
{
return new self(sprintf(_('Error when searching for the host severity #%d'), $hostSeverityId), 0, $ex);
}
/**
* @return self
*/
public static function deleteNotAllowed(): self
{
return new self(_('You are not allowed to delete host severities'));
}
/**
* @param \Throwable $ex
*
* @return self
*/
public static function deleteHostSeverity(\Throwable $ex): self
{
return new self(_('Error while deleting host severity'), 0, $ex);
}
/**
* @param \Throwable $ex
*
* @return self
*/
public static function addHostSeverity(\Throwable $ex): self
{
return new self(_('Error while creating host severity'), 0, $ex);
}
/**
* @return self
*/
public static function writeActionsNotAllowed(): self
{
return new self(_('You are not allowed to create/modify a host severity'));
}
/**
* @param \Throwable $ex
*
* @return self
*/
public static function updateHostSeverity(\Throwable $ex): self
{
return new self(_('Error while updating host severity'), 0, $ex);
}
/**
* @return self
*/
public static function errorWhileRetrievingObject(): self
{
return new self(_('Error while retrieving host severity'));
}
/**
* @return self
*/
public static function hostNameAlreadyExists(): self
{
return new self(_('Host severity name already exists'));
}
/**
* @param int $iconId
*
* @return self
*/
public static function iconDoesNotExist(int $iconId): self
{
return new self(sprintf(_("The host severity icon with id '%d' does not exist"), $iconId));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostSeverity/Application/Repository/ReadHostSeverityRepositoryInterface.php | centreon/src/Core/HostSeverity/Application/Repository/ReadHostSeverityRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\HostSeverity\Application\Repository;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Common\Domain\TrimmedString;
use Core\HostSeverity\Domain\Model\HostSeverity;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
interface ReadHostSeverityRepositoryInterface
{
/**
* Find all host severities.
*
* @param RequestParametersInterface|null $requestParameters
*
* @throws \Throwable
*
* @return HostSeverity[]
*/
public function findAll(?RequestParametersInterface $requestParameters): array;
/**
* Find all host severities by access groups.
*
* @param AccessGroup[] $accessGroups
* @param RequestParametersInterface|null $requestParameters
*
* @throws \Throwable
*
* @return HostSeverity[]
*/
public function findAllByAccessGroups(array $accessGroups, ?RequestParametersInterface $requestParameters): array;
/**
* Check existence of a host severity.
*
* @param int $hostSeverityId
*
* @throws \Throwable
*
* @return bool
*/
public function exists(int $hostSeverityId): bool;
/**
* Check existence of a host severity by access groups.
*
* @param int $hostSeverityId
* @param AccessGroup[] $accessGroups
*
* @throws \Throwable
*
* @return bool
*/
public function existsByAccessGroups(int $hostSeverityId, array $accessGroups): bool;
/**
* Check existence of a host severity by name.
*
* @param TrimmedString $hostSeverityName
*
* @throws \Throwable
*
* @return bool
*/
public function existsByName(TrimmedString $hostSeverityName): bool;
/**
* Find one host severity.
*
* @param int $hostSeverityId
*
* @return HostSeverity|null
*/
public function findById(int $hostSeverityId): ?HostSeverity;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostSeverity/Application/Repository/WriteHostSeverityRepositoryInterface.php | centreon/src/Core/HostSeverity/Application/Repository/WriteHostSeverityRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\HostSeverity\Application\Repository;
use Core\HostSeverity\Domain\Model\HostSeverity;
use Core\HostSeverity\Domain\Model\NewHostSeverity;
interface WriteHostSeverityRepositoryInterface
{
/**
* Delete host severity by id.
*
* @param int $hostSeverityId
*/
public function deleteById(int $hostSeverityId): void;
/**
* Add a host severity
* Return the id of the host severity.
*
* @param NewHostSeverity $hostSeverity
*
* @throws \Throwable
*
* @return int
*/
public function add(NewHostSeverity $hostSeverity): int;
/**
* Update a host severity.
*
* @param HostSeverity $hostSeverity
*
* @throws \Throwable
*/
public function update(HostSeverity $hostSeverity): 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/HostSeverity/Domain/Model/NewHostSeverity.php | centreon/src/Core/HostSeverity/Domain/Model/NewHostSeverity.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\HostSeverity\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
class NewHostSeverity
{
public const MAX_NAME_LENGTH = 200;
public const MAX_ALIAS_LENGTH = 200;
public const MAX_COMMENT_LENGTH = 65535;
public const MIN_LEVEL_VALUE = -128;
public const MAX_LEVEL_VALUE = 127;
protected bool $isActivated = true;
protected ?string $comment = null;
/**
* @param string $name
* @param string $alias
* @param int $level
* @param int $iconId FK
*
* @throws AssertionFailedException
*/
public function __construct(
protected string $name,
protected string $alias,
protected int $level,
protected int $iconId,
) {
$this->name = trim($name);
$this->alias = trim($alias);
$shortName = (new \ReflectionClass($this))->getShortName();
Assertion::maxLength($name, self::MAX_NAME_LENGTH, $shortName . '::name');
Assertion::notEmptyString($name, $shortName . '::name');
Assertion::maxLength($alias, self::MAX_ALIAS_LENGTH, $shortName . '::alias');
Assertion::notEmptyString($alias, $shortName . '::alias');
Assertion::min($level, self::MIN_LEVEL_VALUE, $shortName . '::level');
Assertion::max($level, self::MAX_LEVEL_VALUE, $shortName . '::level');
Assertion::positiveInt($iconId, "{$shortName}::iconId");
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @return string
*/
public function getAlias(): string
{
return $this->alias;
}
/**
* @return int
*/
public function getLevel(): int
{
return $this->level;
}
/**
* @return int
*/
public function getIconId(): int
{
return $this->iconId;
}
/**
* @return bool
*/
public function isActivated(): bool
{
return $this->isActivated;
}
/**
* @param bool $isActivated
*/
public function setActivated(bool $isActivated): void
{
$this->isActivated = $isActivated;
}
/**
* @return string|null
*/
public function getComment(): ?string
{
return $this->comment;
}
/**
* @param string|null $comment
*
* @throws AssertionFailedException
*/
public function setComment(?string $comment): void
{
if ($comment !== null) {
$comment = trim($comment);
Assertion::maxLength(
$comment,
self::MAX_COMMENT_LENGTH,
(new \ReflectionClass($this))->getShortName() . '::comment'
);
}
$this->comment = $comment;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostSeverity/Domain/Model/HostSeverity.php | centreon/src/Core/HostSeverity/Domain/Model/HostSeverity.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\HostSeverity\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
class HostSeverity extends NewHostSeverity
{
/**
* @param int $id
* @param string $name
* @param string $alias
* @param int $level
* @param int $iconId
*
* @throws AssertionFailedException
*/
public function __construct(
private readonly int $id,
string $name,
string $alias,
int $level,
int $iconId,
) {
parent::__construct($name, $alias, $level, $iconId);
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @param string $name
*
* @throws AssertionFailedException
*/
public function setName(string $name): void
{
$name = trim($name);
$shortName = (new \ReflectionClass($this))->getShortName();
Assertion::maxLength($name, self::MAX_NAME_LENGTH, $shortName . '::name');
Assertion::notEmptyString($name, $shortName . '::name');
$this->name = $name;
}
/**
* @param string $alias
*
* @throws AssertionFailedException
*/
public function setAlias(string $alias): void
{
$alias = trim($alias);
$shortName = (new \ReflectionClass($this))->getShortName();
Assertion::maxLength($alias, self::MAX_NAME_LENGTH, $shortName . '::alias');
Assertion::notEmptyString($alias, $shortName . '::alias');
$this->alias = $alias;
}
/**
* @param int $iconId
*
* @throws AssertionFailedException
*/
public function setIconId(int $iconId): void
{
$shortName = (new \ReflectionClass($this))->getShortName();
Assertion::positiveInt($iconId, "{$shortName}::iconId");
$this->iconId = $iconId;
}
/**
* @param int $level
*
* @throws AssertionFailedException
*/
public function setLevel(int $level): void
{
$shortName = (new \ReflectionClass($this))->getShortName();
Assertion::min($level, self::MIN_LEVEL_VALUE, $shortName . '::level');
Assertion::max($level, self::MAX_LEVEL_VALUE, $shortName . '::level');
$this->level = $level;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostSeverity/Infrastructure/Repository/DbReadHostSeverityRepository.php | centreon/src/Core/HostSeverity/Infrastructure/Repository/DbReadHostSeverityRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\HostSeverity\Infrastructure\Repository;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use Core\Common\Domain\TrimmedString;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait;
use Core\Common\Infrastructure\RequestParameters\Normalizer\BoolToEnumNormalizer;
use Core\HostSeverity\Application\Repository\ReadHostSeverityRepositoryInterface;
use Core\HostSeverity\Domain\Model\HostSeverity;
use Utility\SqlConcatenator;
class DbReadHostSeverityRepository extends AbstractRepositoryRDB implements ReadHostSeverityRepositoryInterface
{
use LoggerTrait;
use SqlMultipleBindTrait;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function findAll(?RequestParametersInterface $requestParameters): array
{
$this->info('Getting all host severities');
$concatenator = new SqlConcatenator();
$concatenator->withCalcFoundRows(true);
$concatenator->defineSelect(
<<<'SQL'
SELECT hc.hc_id, hc.hc_name, hc.hc_alias, hc.hc_activate, hc.level, hc.icon_id, hc.hc_comment
FROM `:db`.hostcategories hc
SQL
);
return $this->retrieveHostSeverities($concatenator, $requestParameters);
}
/**
* @inheritDoc
*/
public function findAllByAccessGroups(array $accessGroups, ?RequestParametersInterface $requestParameters): array
{
$this->info('Getting all host severities by access groups');
if ($accessGroups === []) {
$this->debug('No access group for this user, return empty');
return [];
}
$accessGroupIds = array_map(
static fn ($accessGroup) => $accessGroup->getId(),
$accessGroups
);
// if host severities are not filtered in ACLs, then user has access to ALL host severities
if (! $this->hasRestrictedAccessToHostSeverities($accessGroupIds)) {
$this->info('Host severities access not filtered');
return $this->findAll($requestParameters);
}
$concatenator = new SqlConcatenator();
$concatenator->withCalcFoundRows(true);
$concatenator->defineSelect(
<<<'SQL'
SELECT hc.hc_id, hc.hc_name, hc.hc_alias, hc.hc_activate, hc.level, hc.icon_id, hc.hc_comment
FROM `:db`.hostcategories hc
INNER JOIN `:db`.acl_resources_hc_relations arhr
ON hc.hc_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
);
$concatenator->storeBindValueMultiple(':access_group_ids', $accessGroupIds, \PDO::PARAM_INT)
->appendWhere('ag.acl_group_id IN (:access_group_ids)');
return $this->retrieveHostSeverities($concatenator, $requestParameters);
}
/**
* @inheritDoc
*/
public function exists(int $hostSeverityId): bool
{
$this->info('Check existence of host severity with id #' . $hostSeverityId);
$request = $this->translateDbName(
<<<'SQL'
SELECT 1
FROM `:db`.hostcategories hc
WHERE hc.hc_id = :hostSeverityId
AND hc.level IS NOT NULL
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':hostSeverityId', $hostSeverityId, \PDO::PARAM_INT);
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* @inheritDoc
*/
public function existsByAccessGroups(int $hostSeverityId, array $accessGroups): bool
{
$this->info(
'Check existence of host severity by access groups',
['id' => $hostSeverityId, 'accessgroups' => $accessGroups]
);
if ($accessGroups === []) {
$this->debug('Access groups array empty');
return false;
}
$accessGroupIds = array_map(
fn ($accessGroup) => $accessGroup->getId(),
$accessGroups
);
// if host severities are not filtered in ACLs, then user has access to ALL host severities
if (! $this->hasRestrictedAccessToHostSeverities($accessGroupIds)) {
$this->info('Host severities access not filtered');
return $this->exists($hostSeverityId);
}
[$bindValues, $bindQuery] = $this->createMultipleBindQuery($accessGroupIds, ':access_group_id_');
$request = $this->translateDbName(
<<<SQL
SELECT 1
FROM `:db`.hostcategories hc
INNER JOIN `:db`.acl_resources_hc_relations arhr
ON hc.hc_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
WHERE hc.hc_id = :host_severity_id
AND hc.level IS NOT NULL
AND ag.acl_group_id IN ({$bindQuery})
SQL
);
$statement = $this->db->prepare($this->translateDbName($request));
$statement->bindValue(':host_severity_id', $hostSeverityId, \PDO::PARAM_INT);
foreach ($bindValues as $bindParam => $bindValue) {
$statement->bindValue($bindParam, $bindValue, \PDO::PARAM_INT);
}
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* @inheritDoc
*/
public function existsByName(TrimmedString $hostSeverityName): bool
{
$this->info('Check existence of host severity with name ' . $hostSeverityName);
$request = $this->translateDbName(
'SELECT 1 FROM `:db`.hostcategories hc WHERE hc.hc_name = :hostSeverityName'
);
$statement = $this->db->prepare($request);
$statement->bindValue(':hostSeverityName', $hostSeverityName->value, \PDO::PARAM_STR);
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* @inheritDoc
*/
public function findById(int $hostSeverityId): ?HostSeverity
{
$this->info('Get a host severity with id #' . $hostSeverityId);
$request = $this->translateDbName(
<<<'SQL'
SELECT hc.hc_id, hc.hc_name, hc.hc_alias, hc.hc_activate, hc.hc_comment, hc.level, hc.icon_id
FROM `:db`.hostcategories hc
WHERE hc.hc_id = :hostSeverityId
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':hostSeverityId', $hostSeverityId, \PDO::PARAM_INT);
$statement->execute();
$result = $statement->fetch(\PDO::FETCH_ASSOC);
if ($result === false) {
return null;
}
/** @var array{
* hc_id: int,
* hc_name: string,
* hc_alias: string,
* hc_activate: '0'|'1',
* level: int,
* icon_id: int,
* hc_comment: string|null
* } $result
*/
return $this->createHostSeverityFromArray($result);
}
/**
* @param SqlConcatenator $concatenator
* @param RequestParametersInterface|null $requestParameters
*
* @return HostSeverity[]
*/
private function retrieveHostSeverities(
SqlConcatenator $concatenator,
?RequestParametersInterface $requestParameters,
): array {
// Exclude severities from the results
$concatenator->appendWhere('hc.level IS NOT NULL');
$concatenator->defineOrderBy('ORDER BY hc.hc_id ASC');
// Setup for search, pagination, order
$sqlTranslator = $requestParameters ? new SqlRequestParametersTranslator($requestParameters) : null;
$sqlTranslator?->setConcordanceArray([
'id' => 'hc.hc_id',
'name' => 'hc.hc_name',
'alias' => 'hc.hc_alias',
'level' => 'hc.level',
'is_activated' => 'hc.hc_activate',
]);
$sqlTranslator?->addNormalizer('is_activated', new BoolToEnumNormalizer());
$sqlTranslator?->translateForConcatenator($concatenator);
$statement = $this->db->prepare($this->translateDbName($concatenator->__toString()));
$sqlTranslator?->bindSearchValues($statement);
$concatenator->bindValuesToStatement($statement);
$statement->execute();
$sqlTranslator?->calculateNumberOfRows($this->db);
$hostSeverities = [];
while (is_array($result = $statement->fetch(\PDO::FETCH_ASSOC))) {
/** @var array{
* hc_id: int,
* hc_name: string,
* hc_alias: string,
* hc_activate: '0'|'1',
* level: int,
* icon_id: int,
* hc_comment: string|null
* } $result */
$hostSeverities[] = $this->createHostSeverityFromArray($result);
}
return $hostSeverities;
}
/**
* @param array{
* hc_id: int,
* hc_name: string,
* hc_alias: string,
* hc_activate: '0'|'1',
* level: int,
* icon_id: int,
* hc_comment: string|null
* } $result
*
* @return HostSeverity
*/
private function createHostSeverityFromArray(array $result): HostSeverity
{
$hostSeverity = new HostSeverity(
$result['hc_id'],
$result['hc_name'],
$result['hc_alias'],
$result['level'],
$result['icon_id'],
);
$hostSeverity->setActivated((bool) $result['hc_activate']);
$hostSeverity->setComment($result['hc_comment']);
return $hostSeverity;
}
/**
* Determine if host severities are filtered for given access group ids:
* - true: accessible host severities are filtered
* - false: accessible host severities are not filtered.
*
* @param int[] $accessGroupIds
*
* @phpstan-param non-empty-array<int> $accessGroupIds
*
* @return bool
*/
private function hasRestrictedAccessToHostSeverities(array $accessGroupIds): bool
{
$concatenator = new SqlConcatenator();
$concatenator->defineSelect(
'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'
);
$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/HostSeverity/Infrastructure/Repository/DbWriteHostSeverityRepository.php | centreon/src/Core/HostSeverity/Infrastructure/Repository/DbWriteHostSeverityRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\HostSeverity\Infrastructure\Repository;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Common\Infrastructure\RequestParameters\Normalizer\BoolToEnumNormalizer;
use Core\HostSeverity\Application\Repository\WriteHostSeverityRepositoryInterface;
use Core\HostSeverity\Domain\Model\HostSeverity;
use Core\HostSeverity\Domain\Model\NewHostSeverity;
class DbWriteHostSeverityRepository extends AbstractRepositoryRDB implements WriteHostSeverityRepositoryInterface
{
use LoggerTrait;
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function deleteById(int $hostSeverityId): void
{
$this->debug('Delete host severity', ['hostSeverityId' => $hostSeverityId]);
$request = $this->translateDbName(
<<<'SQL'
DELETE hc FROM `:db`.hostcategories hc
WHERE hc.hc_id = :hostSeverityId
AND hc.level IS NOT NULL
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':hostSeverityId', $hostSeverityId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @inheritDoc
*/
public function add(NewHostSeverity $hostSeverity): int
{
$this->debug('Add host severity', ['hostSeverity' => $hostSeverity]);
$request = $this->translateDbName(
<<<'SQL'
INSERT INTO `:db`.hostcategories
(hc_name, hc_alias, hc_comment, level, icon_id, hc_activate) VALUES
(:name, :alias, :comment, :level, :icon_id, :activate)
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':name', $hostSeverity->getName(), \PDO::PARAM_STR);
$statement->bindValue(':alias', $hostSeverity->getAlias(), \PDO::PARAM_STR);
$statement->bindValue(':comment', $hostSeverity->getComment(), \PDO::PARAM_STR);
$statement->bindValue(':level', $hostSeverity->getLevel(), \PDO::PARAM_INT);
$statement->bindValue(':icon_id', $hostSeverity->getIconId(), \PDO::PARAM_INT);
$statement->bindValue(':activate', (new BoolToEnumNormalizer())->normalize($hostSeverity->isActivated()));
$statement->execute();
return (int) $this->db->lastInsertId();
}
/**
* @inheritDoc
*/
public function update(HostSeverity $hostSeverity): void
{
$this->debug('Update host severity', ['hostSeverity' => $hostSeverity]);
$request = $this->translateDbName(
<<<'SQL'
UPDATE `:db`.hostcategories
SET hc_name = :name,
hc_alias = :alias,
hc_comment = :comment,
level = :level,
icon_id = :iconId,
hc_activate = :isActivated
WHERE hc_id = :id
AND level IS NOT NULL
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':id', $hostSeverity->getId(), \PDO::PARAM_INT);
$statement->bindValue(':name', $hostSeverity->getName(), \PDO::PARAM_STR);
$statement->bindValue(':alias', $hostSeverity->getAlias(), \PDO::PARAM_STR);
$statement->bindValue(':comment', $hostSeverity->getComment(), \PDO::PARAM_STR);
$statement->bindValue(':level', $hostSeverity->getLevel(), \PDO::PARAM_INT);
$statement->bindValue(':iconId', $hostSeverity->getIconId(), \PDO::PARAM_INT);
$statement->bindValue(
':isActivated',
(new BoolToEnumNormalizer())->normalize($hostSeverity->isActivated()),
\PDO::PARAM_STR
);
$statement->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostSeverity/Infrastructure/Repository/DbWriteHostSeverityActionLogRepository.php | centreon/src/Core/HostSeverity/Infrastructure/Repository/DbWriteHostSeverityActionLogRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\HostSeverity\Infrastructure\Repository;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Repository\RepositoryException;
use Centreon\Infrastructure\DatabaseConnection;
use Core\ActionLog\Application\Repository\WriteActionLogRepositoryInterface;
use Core\ActionLog\Domain\Model\ActionLog;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\HostSeverity\Application\Repository\ReadHostSeverityRepositoryInterface;
use Core\HostSeverity\Application\Repository\WriteHostSeverityRepositoryInterface;
use Core\HostSeverity\Domain\Model\NewHostSeverity;
class DbWriteHostSeverityActionLogRepository extends AbstractRepositoryRDB implements WriteHostSeverityRepositoryInterface
{
use LoggerTrait;
private const HOST_SEVERITY_PROPERTIES_MAP = [
'name' => 'hc_name',
'alias' => 'hc_alias',
'level' => 'hc_severity_level',
'iconId' => 'hc_severity_icon',
'isActivated' => 'hc_activate',
'comment' => 'hc_comment',
];
/**
* @param WriteHostSeverityRepositoryInterface $writeHostSeverityRepository
* @param ReadHostSeverityRepositoryInterface $readHostSeverityRepository
* @param WriteActionLogRepositoryInterface $writeActionLogRepository
* @param ContactInterface $contact
* @param DatabaseConnection $db
*/
public function __construct(
private readonly WriteHostSeverityRepositoryInterface $writeHostSeverityRepository,
private readonly ReadHostSeverityRepositoryInterface $readHostSeverityRepository,
private readonly WriteActionLogRepositoryInterface $writeActionLogRepository,
private readonly ContactInterface $contact,
DatabaseConnection $db,
) {
$this->db = $db;
}
/**
* @inheritDoc
*/
public function deleteById(int $hostSeverityId): void
{
$hostSeverity = null;
try {
$hostSeverity = $this->readHostSeverityRepository->findById($hostSeverityId);
if ($hostSeverity === null) {
throw new RepositoryException('Host severity not found');
}
$this->writeHostSeverityRepository->deleteById($hostSeverityId);
$actionLog = new ActionLog(
ActionLog::OBJECT_TYPE_HOST_SEVERITY,
$hostSeverityId,
$hostSeverity->getName(),
ActionLog::ACTION_TYPE_DELETE,
$this->contact->getId()
);
$this->writeActionLogRepository->addAction($actionLog);
} catch (\Throwable $ex) {
$this->error(
"Error while deleting host severity : {$ex->getMessage()}",
['hostSeverity' => $hostSeverity, 'trace' => $ex->getTraceAsString()]
);
throw $ex;
}
}
/**
* @inheritDoc
*/
public function add(NewHostSeverity $hostSeverity): int
{
try {
$hostSeverityId = $this->writeHostSeverityRepository->add($hostSeverity);
$actionLog = new ActionLog(
ActionLog::OBJECT_TYPE_HOST_SEVERITY,
$hostSeverityId,
$hostSeverity->getName(),
ActionLog::ACTION_TYPE_ADD,
$this->contact->getId()
);
$actionLogId = $this->writeActionLogRepository->addAction($actionLog);
$actionLog->setId($actionLogId);
$details = $this->getHostSeverityPropertiesAsArray($hostSeverity);
$this->writeActionLogRepository->addActionDetails($actionLog, $details);
return $hostSeverityId;
} catch (\Throwable $ex) {
$this->error(
"Error while adding host severity : {$ex->getMessage()}",
['hostSeverity' => $hostSeverity, 'trace' => $ex->getTraceAsString()]
);
throw $ex;
}
}
/**
* @inheritDoc
*/
public function update(NewHostSeverity $hostSeverity): void
{
try {
$initialHostSeverity = $this->readHostSeverityRepository->findById($hostSeverity->getId());
if ($initialHostSeverity === null) {
throw new RepositoryException('Host severity not found');
}
$this->writeHostSeverityRepository->update($hostSeverity);
$diff = $this->getHostSeverityDiff($initialHostSeverity, $hostSeverity);
// If enable/disable has been changed
if (array_key_exists('hc_activate', $diff)) {
// If only the activation has been changed
if (count($diff) === 1) {
$action = (bool) $diff['hc_activate']
? ActionLog::ACTION_TYPE_ENABLE
: ActionLog::ACTION_TYPE_DISABLE;
$actionLog = new ActionLog(
ActionLog::OBJECT_TYPE_HOST_SEVERITY,
$hostSeverity->getId(),
$hostSeverity->getName(),
$action,
$this->contact->getId()
);
$this->writeActionLogRepository->addAction($actionLog);
}
// If other properties have been changed as well
if (count($diff) > 1) {
// Log enable/disable action
$action = (bool) $diff['hc_activate']
? ActionLog::ACTION_TYPE_ENABLE
: ActionLog::ACTION_TYPE_DISABLE;
$actionLog = new ActionLog(
ActionLog::OBJECT_TYPE_HOST_SEVERITY,
$hostSeverity->getId(),
$hostSeverity->getName(),
$action,
$this->contact->getId()
);
$this->writeActionLogRepository->addAction($actionLog);
// Log change action
unset($diff['hc_activate']);
$actionLog = new ActionLog(
ActionLog::OBJECT_TYPE_HOST_SEVERITY,
$hostSeverity->getId(),
$hostSeverity->getName(),
ActionLog::ACTION_TYPE_CHANGE,
$this->contact->getId()
);
$actionLogId = $this->writeActionLogRepository->addAction($actionLog);
$actionLog->setId($actionLogId);
$this->writeActionLogRepository->addActionDetails($actionLog, $diff);
}
return;
}
// Log change action if other properties have been changed without activation
$actionLog = new ActionLog(
ActionLog::OBJECT_TYPE_HOST_SEVERITY,
$hostSeverity->getId(),
$hostSeverity->getName(),
ActionLog::ACTION_TYPE_CHANGE,
$this->contact->getId()
);
$actionLogId = $this->writeActionLogRepository->addAction($actionLog);
$actionLog->setId($actionLogId);
$this->writeActionLogRepository->addActionDetails($actionLog, $diff);
} catch (\Throwable $ex) {
$this->error(
"Error while updating host severity : {$ex->getMessage()}",
['hostSeverity' => $hostSeverity, 'trace' => $ex->getTraceAsString()]
);
throw $ex;
}
}
/**
* @param NewHostSeverity $initialSeverity
* @param NewHostSeverity $updatedHostSeverity
*
* @return array<string, string|int|bool>
*/
private function getHostSeverityDiff(
NewHostSeverity $initialSeverity,
NewHostSeverity $updatedHostSeverity,
): array {
$diff = [];
$reflection = new \ReflectionClass($initialSeverity);
foreach ($reflection->getProperties() as $property) {
$initialValue = $property->getValue($initialSeverity);
$updatedValue = $property->getValue($updatedHostSeverity);
if ($initialValue !== $updatedValue) {
if (array_key_exists($property->getName(), self::HOST_SEVERITY_PROPERTIES_MAP)) {
$diff[self::HOST_SEVERITY_PROPERTIES_MAP[$property->getName()]] = $updatedValue;
}
}
}
return $diff;
}
/**
* @param NewHostSeverity $hostSeverity
*
* @return array<string,int|bool|string>
*/
private function getHostSeverityPropertiesAsArray(NewHostSeverity $hostSeverity): array
{
$hostSeverityPropertiesArray = [];
$hostSeverityReflection = new \ReflectionClass($hostSeverity);
foreach ($hostSeverityReflection->getProperties() as $property) {
$value = $property->getValue($hostSeverity);
if ($value === null) {
$value = '';
}
if (array_key_exists($property->getName(), self::HOST_SEVERITY_PROPERTIES_MAP)) {
$hostSeverityPropertiesArray[self::HOST_SEVERITY_PROPERTIES_MAP[$property->getName()]] = $value;
}
}
return $hostSeverityPropertiesArray;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostSeverity/Infrastructure/API/AddHostSeverity/AddHostSeverityController.php | centreon/src/Core/HostSeverity/Infrastructure/API/AddHostSeverity/AddHostSeverityController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\HostSeverity\Infrastructure\API\AddHostSeverity;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\HostSeverity\Application\UseCase\AddHostSeverity\AddHostSeverity;
use Core\HostSeverity\Application\UseCase\AddHostSeverity\AddHostSeverityRequest;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class AddHostSeverityController extends AbstractController
{
use LoggerTrait;
/**
* @param Request $request
* @param AddHostSeverity $useCase
* @param AddHostSeverityPresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
Request $request,
AddHostSeverity $useCase,
AddHostSeverityPresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
try {
/** @var array{
* name: string,
* alias: string,
* level: int,
* icon_id: int,
* is_activated?: bool,
* comment?: string|null
* } $data
*/
$data = $this->validateAndRetrieveDataSent($request, __DIR__ . '/AddHostSeveritySchema.json');
} catch (\InvalidArgumentException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
return $presenter->show();
}
$hostSeverityRequest = $this->createRequestDto($data);
$useCase($hostSeverityRequest, $presenter);
return $presenter->show();
}
/**
* @param array{
* name: string,
* alias: string,
* level: int,
* icon_id: int,
* is_activated?: bool,
* comment?: string|null
* } $data
*
* @return AddHostSeverityRequest
*/
private function createRequestDto(array $data): AddHostSeverityRequest
{
$hostSeverityRequest = new AddHostSeverityRequest();
$hostSeverityRequest->name = $data['name'];
$hostSeverityRequest->alias = $data['alias'];
$hostSeverityRequest->level = $data['level'];
$hostSeverityRequest->iconId = $data['icon_id'];
$hostSeverityRequest->isActivated = $data['is_activated'] ?? true;
$hostSeverityRequest->comment = $data['comment'] ?? null;
return $hostSeverityRequest;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostSeverity/Infrastructure/API/AddHostSeverity/AddHostSeverityPresenter.php | centreon/src/Core/HostSeverity/Infrastructure/API/AddHostSeverity/AddHostSeverityPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\HostSeverity\Infrastructure\API\AddHostSeverity;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\CreatedResponse;
use Core\HostSeverity\Application\UseCase\AddHostSeverity\AddHostSeverityResponse;
use Core\Infrastructure\Common\Api\Router;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
class AddHostSeverityPresenter extends AbstractPresenter
{
use LoggerTrait;
private const ROUTE_NAME = 'FindHostSeverity';
private const ROUTE_HOST_SEVERITY_ID = 'hostSeverityId';
public function __construct(
PresenterFormatterInterface $presenterFormatter,
readonly private Router $router,
) {
parent::__construct($presenterFormatter);
}
/**
* @inheritDoc
*/
public function present(mixed $data): void
{
if (
$data instanceof CreatedResponse
&& $data->getPayload() instanceof AddHostSeverityResponse
) {
$payload = $data->getPayload();
$data->setPayload([
'id' => $payload->id,
'name' => $payload->name,
'alias' => $payload->alias,
'level' => $payload->level,
'icon_id' => $payload->iconId,
'is_activated' => $payload->isActivated,
'comment' => $payload->comment,
]);
try {
$this->setResponseHeaders([
'Location' => $this->router->generate(self::ROUTE_NAME, [self::ROUTE_HOST_SEVERITY_ID => $payload->id]),
]);
} catch (\Throwable $ex) {
$this->error('Impossible to generate the location header', [
'message' => $ex->getMessage(),
'trace' => $ex->getTraceAsString(),
'route' => self::ROUTE_NAME,
'payload' => $payload,
]);
}
}
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/HostSeverity/Infrastructure/API/FindHostSeverity/FindHostSeverityController.php | centreon/src/Core/HostSeverity/Infrastructure/API/FindHostSeverity/FindHostSeverityController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\HostSeverity\Infrastructure\API\FindHostSeverity;
use Centreon\Application\Controller\AbstractController;
use Core\HostSeverity\Application\UseCase\FindHostSeverity\FindHostSeverity;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class FindHostSeverityController extends AbstractController
{
/**
* @param int $hostSeverityId
* @param FindHostSeverity $useCase
* @param FindHostSeverityPresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
int $hostSeverityId,
FindHostSeverity $useCase,
FindHostSeverityPresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($hostSeverityId, $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/HostSeverity/Infrastructure/API/FindHostSeverity/FindHostSeverityPresenter.php | centreon/src/Core/HostSeverity/Infrastructure/API/FindHostSeverity/FindHostSeverityPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\HostSeverity\Infrastructure\API\FindHostSeverity;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\HostSeverity\Application\UseCase\FindHostSeverity\FindHostSeverityResponse;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
class FindHostSeverityPresenter extends AbstractPresenter
{
/**
* @param PresenterFormatterInterface $presenterFormatter
*/
public function __construct(
protected PresenterFormatterInterface $presenterFormatter,
) {
parent::__construct($presenterFormatter);
}
/**
* @param FindHostSeverityResponse $data
*/
public function present(mixed $data): void
{
parent::present([
'id' => $data->id,
'name' => $data->name,
'alias' => $data->alias,
'level' => $data->level,
'icon_id' => $data->iconId,
'is_activated' => $data->isActivated,
'comment' => $data->comment,
]);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostSeverity/Infrastructure/API/UpdateHostSeverity/UpdateHostSeverityController.php | centreon/src/Core/HostSeverity/Infrastructure/API/UpdateHostSeverity/UpdateHostSeverityController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\HostSeverity\Infrastructure\API\UpdateHostSeverity;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\HostSeverity\Application\UseCase\UpdateHostSeverity\UpdateHostSeverity;
use Core\HostSeverity\Application\UseCase\UpdateHostSeverity\UpdateHostSeverityRequest;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class UpdateHostSeverityController extends AbstractController
{
use LoggerTrait;
/**
* @param int $hostSeverityId
* @param Request $request
* @param UpdateHostSeverity $useCase
* @param DefaultPresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
int $hostSeverityId,
Request $request,
UpdateHostSeverity $useCase,
DefaultPresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
try {
/** @var array{
* name: string,
* alias: string,
* level: int,
* icon_id: int,
* is_activated?: bool,
* comment?: string|null
* } $data
*/
$data = $this->validateAndRetrieveDataSent($request, __DIR__ . '/UpdateHostSeveritySchema.json');
} catch (\InvalidArgumentException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
return $presenter->show();
}
$hostSeverityRequest = $this->createRequestDto($hostSeverityId, $data);
$useCase($hostSeverityRequest, $presenter);
return $presenter->show();
}
/**
* @param int $hostSeverityId
* @param array{
* name: string,
* alias: string,
* level: int,
* icon_id: int,
* is_activated?: bool,
* comment?: string|null
* } $data
*
* @return UpdateHostSeverityRequest
*/
private function createRequestDto(int $hostSeverityId, array $data): UpdateHostSeverityRequest
{
$hostSeverityRequest = new UpdateHostSeverityRequest();
$hostSeverityRequest->id = $hostSeverityId;
$hostSeverityRequest->name = $data['name'];
$hostSeverityRequest->alias = $data['alias'];
$hostSeverityRequest->level = $data['level'];
$hostSeverityRequest->iconId = max(0, $data['icon_id']);
$hostSeverityRequest->isActivated = $data['is_activated'] ?? true;
$hostSeverityRequest->comment = $data['comment'] ?? null;
return $hostSeverityRequest;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostSeverity/Infrastructure/API/FindHostSeverities/FindHostSeveritiesPresenter.php | centreon/src/Core/HostSeverity/Infrastructure/API/FindHostSeverities/FindHostSeveritiesPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\HostSeverity\Infrastructure\API\FindHostSeverities;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\HostSeverity\Application\UseCase\FindHostSeverities\FindHostSeveritiesResponse;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
class FindHostSeveritiesPresenter extends AbstractPresenter
{
/**
* @param RequestParametersInterface $requestParameters
* @param PresenterFormatterInterface $presenterFormatter
*/
public function __construct(
private readonly RequestParametersInterface $requestParameters,
protected PresenterFormatterInterface $presenterFormatter,
) {
parent::__construct($presenterFormatter);
}
/**
* @param FindHostSeveritiesResponse $data
*/
public function present(mixed $data): void
{
$result = [];
foreach ($data->hostSeverities as $hostSeverity) {
$result[] = [
'id' => $hostSeverity['id'],
'name' => $hostSeverity['name'],
'alias' => $hostSeverity['alias'],
'level' => $hostSeverity['level'],
'icon_id' => $hostSeverity['iconId'],
'is_activated' => $hostSeverity['isActivated'],
'comment' => $hostSeverity['comment'],
];
}
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/HostSeverity/Infrastructure/API/FindHostSeverities/FindHostSeveritiesController.php | centreon/src/Core/HostSeverity/Infrastructure/API/FindHostSeverities/FindHostSeveritiesController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\HostSeverity\Infrastructure\API\FindHostSeverities;
use Centreon\Application\Controller\AbstractController;
use Core\HostSeverity\Application\UseCase\FindHostSeverities\FindHostSeverities;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class FindHostSeveritiesController extends AbstractController
{
/**
* @param FindHostSeverities $useCase
* @param FindHostSeveritiesPresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(FindHostSeverities $useCase, FindHostSeveritiesPresenter $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/HostSeverity/Infrastructure/API/DeleteHostSeverity/DeleteHostSeverityController.php | centreon/src/Core/HostSeverity/Infrastructure/API/DeleteHostSeverity/DeleteHostSeverityController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\HostSeverity\Infrastructure\API\DeleteHostSeverity;
use Centreon\Application\Controller\AbstractController;
use Core\HostSeverity\Application\UseCase\DeleteHostSeverity\DeleteHostSeverity;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class DeleteHostSeverityController extends AbstractController
{
/**
* @param int $hostSeverityId
* @param DeleteHostSeverity $useCase
* @param DefaultPresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
int $hostSeverityId,
DeleteHostSeverity $useCase,
DefaultPresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($hostSeverityId, $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/Severity/RealTime/Application/UseCase/FindSeverity/FindSeverityPresenterInterface.php | centreon/src/Core/Severity/RealTime/Application/UseCase/FindSeverity/FindSeverityPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Severity\RealTime\Application\UseCase\FindSeverity;
use Core\Application\Common\UseCase\PresenterInterface;
interface FindSeverityPresenterInterface 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/Severity/RealTime/Application/UseCase/FindSeverity/FindSeverity.php | centreon/src/Core/Severity/RealTime/Application/UseCase/FindSeverity/FindSeverity.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Severity\RealTime\Application\UseCase\FindSeverity;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Severity\RealTime\Application\Repository\ReadSeverityRepositoryInterface;
use Core\Severity\RealTime\Domain\Model\Severity;
final class FindSeverity
{
use LoggerTrait;
/**
* @param ReadSeverityRepositoryInterface $repository
* @param ContactInterface $user
* @param ReadAccessGroupRepositoryInterface $readAccessGroupRepository
*/
public function __construct(
private readonly ReadSeverityRepositoryInterface $repository,
private readonly ContactInterface $user,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
) {
}
/**
* @param int $severityTypeId
* @param FindSeverityPresenterInterface $presenter
*/
public function __invoke(int $severityTypeId, FindSeverityPresenterInterface $presenter): void
{
$this->info('Searching for severities in the realtime', ['typeId' => $severityTypeId]);
$severities = [];
try {
if ($this->user->isAdmin()) {
$severities = $this->repository->findAllByTypeId($severityTypeId);
} else {
$accessGroups = $this->readAccessGroupRepository->findByContact($this->user);
$severities = $this->repository->findAllByTypeIdAndAccessGroups($severityTypeId, $accessGroups);
}
} catch (\Throwable $ex) {
$this->error(
'An error occured while retrieving severities from real-time data',
[
'typeId' => $severityTypeId,
'trace' => $ex->getTraceAsString(),
]
);
$presenter->setResponseStatus(
new ErrorResponse('An error occured while retrieving severities')
);
return;
}
$presenter->present($this->createResponse($severities));
}
/**
* @param Severity[] $severities
*
* @return FindSeverityResponse
*/
private function createResponse(array $severities): FindSeverityResponse
{
return new FindSeverityResponse($severities);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Severity/RealTime/Application/UseCase/FindSeverity/FindSeverityResponse.php | centreon/src/Core/Severity/RealTime/Application/UseCase/FindSeverity/FindSeverityResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Severity\RealTime\Application\UseCase\FindSeverity;
use Core\Application\RealTime\Common\RealTimeResponseTrait;
use Core\Severity\RealTime\Domain\Model\Severity;
final class FindSeverityResponse
{
use RealTimeResponseTrait;
/** @var array<int, array<string, mixed>> */
public array $severities;
/**
* @param Severity[] $severities
*/
public function __construct(array $severities)
{
$this->severities = $this->severitiesToArray($severities);
}
/**
* @param Severity[] $severities
*
* @return array<int, array<string, mixed>>
*/
private function severitiesToArray(array $severities): array
{
return array_map(
fn (Severity $severity) => [
'id' => $severity->getId(),
'name' => $severity->getName(),
'level' => $severity->getLevel(),
'type' => $severity->getTypeAsString(),
'icon' => $this->iconToArray($severity->getIcon()),
],
$severities
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Severity/RealTime/Application/Repository/ReadSeverityRepositoryInterface.php | centreon/src/Core/Severity/RealTime/Application/Repository/ReadSeverityRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Severity\RealTime\Application\Repository;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Core\Severity\RealTime\Domain\Model\Severity;
interface ReadSeverityRepositoryInterface
{
/**
* Returns all the severities from the RealTime of provided type id (without ACls).
*
* @param int $typeId
*
* @throws \Throwable
*
* @return Severity[]
*/
public function findAllByTypeId(int $typeId): array;
/**
* Returns all the severities from the RealTime of provided type id (with ACLs).
*
* @param int $typeId
* @param AccessGroup[] $accessGroups
*
* @throws \Throwable
*
* @return Severity[]
*/
public function findAllByTypeIdAndAccessGroups(int $typeId, array $accessGroups): array;
/**
* Finds a Severity by id, parentId and typeId.
*
* @param int $resourceId
* @param int $parentResourceId
* @param int $typeId
*
* @throws \Throwable
*
* @return Severity|null
*/
public function findByResourceAndTypeId(int $resourceId, int $parentResourceId, int $typeId): ?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/Severity/RealTime/Domain/Model/Severity.php | centreon/src/Core/Severity/RealTime/Domain/Model/Severity.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Severity\RealTime\Domain\Model;
use Centreon\Domain\Common\Assertion\Assertion;
use Core\Domain\RealTime\Model\Icon;
class Severity
{
public const MAX_NAME_LENGTH = 255;
public const SERVICE_SEVERITY_TYPE_ID = 0;
public const HOST_SEVERITY_TYPE_ID = 1;
public const TYPES_AS_STRING = [
self::HOST_SEVERITY_TYPE_ID => 'host',
self::SERVICE_SEVERITY_TYPE_ID => 'service',
];
/**
* @param int $id
* @param string $name
* @param int $level
* @param int $type
* @param Icon $icon
*
* @throws \Assert\AssertionFailedException
*/
public function __construct(
private int $id,
private string $name,
private int $level,
private int $type,
private Icon $icon,
) {
Assertion::maxLength($name, self::MAX_NAME_LENGTH, 'Severity::name');
Assertion::notEmpty($name, 'Severity::name');
Assertion::min($level, 0, 'Severity::level');
Assertion::max($level, 100, 'Severity::level');
Assertion::inArray(
$type,
[self::HOST_SEVERITY_TYPE_ID, self::SERVICE_SEVERITY_TYPE_ID],
'Severity::type'
);
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @return int
*/
public function getLevel(): int
{
return $this->level;
}
/**
* @return Icon
*/
public function getIcon(): Icon
{
return $this->icon;
}
/**
* @return int
*/
public function getType(): int
{
return $this->type;
}
/**
* @return string
*/
public function getTypeAsString(): string
{
return self::TYPES_AS_STRING[$this->type];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Severity/RealTime/Infrastructure/Repository/DbReadSeverityRepository.php | centreon/src/Core/Severity/RealTime/Infrastructure/Repository/DbReadSeverityRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Severity\RealTime\Infrastructure\Repository;
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\Severity\RealTime\Application\Repository\ReadSeverityRepositoryInterface;
use Core\Severity\RealTime\Domain\Model\Severity;
use Utility\SqlConcatenator;
/**
* @phpstan-type _severity array{
* severity_id: int,
* id: int,
* name: string,
* type: int,
* level: int,
* icon_id: int,
* icon_id: int,
* icon_name: string,
* icon_path: string,
* icon_directory: string|null
* }
*/
class DbReadSeverityRepository extends AbstractRepositoryDRB implements ReadSeverityRepositoryInterface
{
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([
'id' => 's.id',
'name' => 's.name',
'level' => 's.level',
]);
}
/**
* @inheritDoc
*/
public function findAllByTypeId(int $typeId): array
{
$this->info(
'Fetching severities from the database by typeId',
[
'typeId' => $typeId,
]
);
$request = 'SELECT SQL_CALC_FOUND_ROWS
1 AS REALTIME,
severity_id,
s.id,
s.name,
s.type,
s.level,
s.icon_id,
img_id AS `icon_id`,
img_name AS `icon_name`,
img_path AS `icon_path`,
imgd.dir_name AS `icon_directory`
FROM `:dbstg`.severities s
INNER JOIN `:db`.view_img img
ON s.icon_id = img.img_id
LEFT JOIN `:db`.view_img_dir_relation imgdr
ON imgdr.img_img_id = img.img_id
INNER JOIN `:db`.view_img_dir imgd
ON imgd.dir_id = imgdr.dir_dir_parent_id';
$searchRequest = $this->sqlRequestTranslator->translateSearchParameterToSql();
$request .= $searchRequest === null ? ' WHERE ' : $searchRequest . ' AND ';
$request .= 's.type = :typeId AND img.img_id = s.icon_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(':typeId', $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);
}
$severities = [];
while ($record = $statement->fetch(\PDO::FETCH_ASSOC)) {
/** @var _severity $record */
$severities[] = DbSeverityFactory::createFromRecord($record);
}
return $severities;
}
/**
* @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 severities from the database by typeId and access groups',
[
'typeId' => $typeId,
'accessGroupIds' => $accessGroupIds,
]
);
if ($typeId === Severity::SERVICE_SEVERITY_TYPE_ID) {
// if service severities are not filtered in ACLs, then user has access to ALL service severities
if (! $this->hasRestrictedAccessToServiceSeverities($accessGroupIds)) {
$this->info('Service severities access not filtered');
return $this->findAllByTypeId($typeId);
}
$severitiesAcls = <<<'SQL'
INNER JOIN `:db`.acl_resources_sc_relations arsr
ON s.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;
} else {
// if host severities are not filtered in ACLs, then user has access to ALL host severities
if (! $this->hasRestrictedAccessToHostSeverities($accessGroupIds)) {
$this->info('Host severities access not filtered');
return $this->findAllByTypeId($typeId);
}
$severitiesAcls = <<<'SQL'
INNER JOIN `:db`.acl_resources_hc_relations arhr
ON s.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;
}
$request = <<<SQL
SELECT SQL_CALC_FOUND_ROWS
1 AS REALTIME,
severity_id,
s.id,
s.name,
s.type,
s.level,
s.icon_id,
img_id AS `icon_id`,
img_name AS `icon_name`,
img_path AS `icon_path`,
imgd.dir_name AS `icon_directory`
FROM `:dbstg`.severities s
INNER JOIN `:db`.view_img img
ON s.icon_id = img.img_id
LEFT JOIN `:db`.view_img_dir_relation imgdr
ON imgdr.img_img_id = img.img_id
INNER JOIN `:db`.view_img_dir imgd
ON imgd.dir_id = imgdr.dir_dir_parent_id
{$severitiesAcls}
SQL;
$searchRequest = $this->sqlRequestTranslator->translateSearchParameterToSql();
$request .= $searchRequest === null ? ' WHERE ' : $searchRequest . ' AND ';
$request .= 's.type = :typeId AND img.img_id = s.icon_id';
foreach ($accessGroupIds as $key => $id) {
$bindValues[":access_group_id_{$key}"] = $id;
}
$request .= ' AND ag.acl_group_id IN (' . implode(', ', array_keys($bindValues)) . ')';
// 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(':typeId', $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);
}
$severities = [];
while ($record = $statement->fetch(\PDO::FETCH_ASSOC)) {
/** @var _severity $record */
$severities[] = DbSeverityFactory::createFromRecord($record);
}
return $severities;
}
/**
* @inheritDoc
*/
public function findByResourceAndTypeId(int $resourceId, int $parentResourceId, int $typeId): ?Severity
{
$request = 'SELECT
1 AS REALTIME,
resources.severity_id,
s.id,
s.name,
s.level,
s.type,
s.icon_id,
img_name AS `icon_name`,
img_path AS `icon_path`,
imgd.dir_name AS `icon_directory`
FROM `:dbstg`.resources
INNER JOIN `:dbstg`.severities s
ON s.severity_id = resources.severity_id
INNER JOIN `:db`.view_img img
ON s.icon_id = img.img_id
LEFT JOIN `:db`.view_img_dir_relation imgdr
ON imgdr.img_img_id = img.img_id
INNER JOIN `:db`.view_img_dir imgd
ON imgd.dir_id = imgdr.dir_dir_parent_id
WHERE resources.id = :resourceId AND resources.parent_id = :parentResourceId AND s.type = :typeId';
$statement = $this->db->prepare($this->translateDbName($request));
$statement->bindValue(':resourceId', $resourceId, \PDO::PARAM_INT);
$statement->bindValue(':parentResourceId', $parentResourceId, \PDO::PARAM_INT);
$statement->bindValue(':typeId', $typeId, \PDO::PARAM_INT);
$statement->execute();
if (($record = $statement->fetch(\PDO::FETCH_ASSOC))) {
/** @var _severity $record */
return DbSeverityFactory::createFromRecord($record);
}
return null;
}
/**
* Determine if service severities are filtered for given access group ids:
* - true: accessible service severities are filtered
* - false: accessible service severities are not filtered.
*
* @param int[] $accessGroupIds
*
* @phpstan-param non-empty-array<int> $accessGroupIds
*
* @return bool
*/
private function hasRestrictedAccessToServiceSeverities(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 severities are filtered for given access group ids:
* - true: accessible host severities are filtered
* - false: accessible host severities are not filtered.
*
* @param int[] $accessGroupIds
*
* @phpstan-param non-empty-array<int> $accessGroupIds
*
* @return bool
*/
private function hasRestrictedAccessToHostSeverities(array $accessGroupIds): bool
{
$concatenator = new SqlConcatenator();
$concatenator->defineSelect(
'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'
);
$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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.