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/Security/Domain/Authentication/Interfaces/AuthenticationServiceInterface.php | centreon/src/Security/Domain/Authentication/Interfaces/AuthenticationServiceInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Security\Domain\Authentication\Interfaces;
use Centreon\Domain\Authentication\Exception\AuthenticationException;
use Core\Security\Authentication\Domain\Model\AuthenticationTokens;
use Security\Domain\Authentication\Exceptions\ProviderException;
interface AuthenticationServiceInterface
{
/**
* Check authentication token.
*
* @param string $token
*
* @throws ProviderException
* @throws AuthenticationException
*
* @return bool
*/
public function isValidToken(string $token): bool;
/**
* Delete a session.
*
* @param string $sessionToken
*
* @throws AuthenticationException
*/
public function deleteSession(string $sessionToken): void;
/**
* @param AuthenticationTokens $authenticationToken
*
* @throws AuthenticationException
*/
public function updateAuthenticationTokens(AuthenticationTokens $authenticationToken): void;
/**
* @param string $token
*
* @throws AuthenticationException
*
* @return AuthenticationTokens|null
*/
public function findAuthenticationTokensByToken(string $token): ?AuthenticationTokens;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Security/Domain/Authentication/Interfaces/ProviderConfigurationInterface.php | centreon/src/Security/Domain/Authentication/Interfaces/ProviderConfigurationInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Security\Domain\Authentication\Interfaces;
interface ProviderConfigurationInterface
{
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Security/Domain/Authentication/Interfaces/ProviderServiceInterface.php | centreon/src/Security/Domain/Authentication/Interfaces/ProviderServiceInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Security\Domain\Authentication\Interfaces;
use Core\Security\Authentication\Application\Provider\ProviderAuthenticationInterface;
use Security\Domain\Authentication\Exceptions\ProviderException;
use Security\Domain\Authentication\Model\ProviderConfiguration;
/**
* @deprecated
*/
interface ProviderServiceInterface
{
/**
* Find a provider by configuration id.
*
* @param int $providerConfigurationId
*
* @throws ProviderException
*
* @return ProviderAuthenticationInterface|null
*/
public function findProviderByConfigurationId(int $providerConfigurationId): ?ProviderAuthenticationInterface;
/**
* Find a provider by the provider name.
*
* @param string $providerAuthenticationName
*
* @throws ProviderException
*
* @return ProviderAuthenticationInterface|null
*/
public function findProviderByConfigurationName(
string $providerAuthenticationName,
): ?ProviderAuthenticationInterface;
/**
* @param string $providerConfigurationName
*
* @throws ProviderException
*
* @return ProviderConfiguration|null
*/
public function findProviderConfigurationByConfigurationName(
string $providerConfigurationName,
): ?ProviderConfiguration;
/**
* @param string $sessionToken
*
* @throws ProviderException
*
* @return ProviderAuthenticationInterface|null
*/
public function findProviderBySession(string $sessionToken): ?ProviderAuthenticationInterface;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Security/Domain/Authentication/Interfaces/LocalProviderInterface.php | centreon/src/Security/Domain/Authentication/Interfaces/LocalProviderInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Security\Domain\Authentication\Interfaces;
use Core\Security\Authentication\Domain\Exception\AuthenticationException;
use Core\Security\Authentication\Domain\Model\NewProviderToken;
use Core\Security\ProviderConfiguration\Domain\Model\Configuration;
interface LocalProviderInterface extends ProviderInterface
{
/**
* @param array<string, mixed> $data
*
* @throws AuthenticationException
*/
public function authenticateOrFail(array $data): void;
/**
* Return the provider token.
*
* @param string $token
*
* @return NewProviderToken
*/
public function getProviderToken(string $token): NewProviderToken;
/**
* Return the provider refresh token.
*
* @param string $token
*
* @return NewProviderToken|null
*/
public function getProviderRefreshToken(string $token): ?NewProviderToken;
/**
* Get the provider's configuration (ex: client_id, client_secret, grant_type, ...).
*
* @return Configuration
*/
public function getConfiguration(): Configuration;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Security/Domain/Authentication/Interfaces/WebSSOProviderInterface.php | centreon/src/Security/Domain/Authentication/Interfaces/WebSSOProviderInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Security\Domain\Authentication\Interfaces;
interface WebSSOProviderInterface extends ProviderInterface
{
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Security/Domain/Authentication/Interfaces/SessionRepositoryInterface.php | centreon/src/Security/Domain/Authentication/Interfaces/SessionRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Security\Domain\Authentication\Interfaces;
use Security\Domain\Authentication\Model\Session;
interface SessionRepositoryInterface
{
/**
* Clear all information about the session token.
*
* @param string $sessionToken
*/
public function deleteSession(string $sessionToken): void;
/**
* Delete all expired sessions.
*/
public function deleteExpiredSession(): void;
/**
* Insert token into session table.
*
* @param Session $session
*/
public function addSession(Session $session): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Security/Domain/Authentication/Interfaces/ProviderInterface.php | centreon/src/Security/Domain/Authentication/Interfaces/ProviderInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Security\Domain\Authentication\Interfaces;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Security\Authentication\Domain\Model\AuthenticationTokens;
use Core\Security\ProviderConfiguration\Domain\Model\Configuration;
interface ProviderInterface
{
/**
* Get legacy Centreon session.
*
* @return \Centreon
*/
public function getLegacySession(): \Centreon;
/**
* Set legacy Centreon session.
*
* @param \Centreon $legacySession
*/
public function setLegacySession(\Centreon $legacySession): void;
/**
* Indicates whether we can create the authenticated user or not.
*
* @return bool
*/
public function canCreateUser(): bool;
/**
* Indicates whether or not the provider has a mechanism to refresh the token.
*
* @return bool
*/
public function canRefreshToken(): bool;
/**
* Return the provider's name.
*
* @return string
*/
public function getName(): string;
/**
* @return ContactInterface|null
*/
public function getUser(): ?ContactInterface;
/**
* Set the provider's configuration to initialize it (ex: client_id, client_secret, grant_type, ...).
*
* @param Configuration $configuration
*/
public function setConfiguration(Configuration $configuration): void;
/**
* Refresh the provider token.
*
* @param AuthenticationTokens $authenticationTokens
*
* @return AuthenticationTokens|null Return the new AuthenticationTokens object if success otherwise null
*/
public function refreshToken(AuthenticationTokens $authenticationTokens): ?AuthenticationTokens;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Security/Domain/Authentication/Interfaces/AuthenticationTokenServiceInterface.php | centreon/src/Security/Domain/Authentication/Interfaces/AuthenticationTokenServiceInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Security\Domain\Authentication\Interfaces;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Security\Authentication\Domain\Model\AuthenticationTokens;
interface AuthenticationTokenServiceInterface
{
/**
* Find authentication tokens by contact.
*
* @param ContactInterface $contact
*
* @throws \Security\Domain\Authentication\Exceptions\AuthenticationTokenException
*
* @return AuthenticationTokens|null
*/
public function findByContact(ContactInterface $contact): ?AuthenticationTokens;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Security/Domain/Authentication/Interfaces/ProviderRepositoryInterface.php | centreon/src/Security/Domain/Authentication/Interfaces/ProviderRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Security\Domain\Authentication\Interfaces;
use Core\Security\ProviderConfiguration\Domain\Model\Configuration;
use Security\Domain\Authentication\Model\ProviderConfiguration;
interface ProviderRepositoryInterface
{
/**
* Find the provider's configuration.
*
* @param int $id Id of the provider configuration
*
* @throws \Exception
*
* @return Configuration|null
*/
public function findProviderConfiguration(int $id): ?Configuration;
/**
* Find the provider configuration by name.
*
* @param string $providerConfigurationName
*
* @return ProviderConfiguration|null
*/
public function findProviderConfigurationByConfigurationName(
string $providerConfigurationName,
): ?ProviderConfiguration;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Security/Domain/Authentication/Interfaces/AuthenticationRepositoryInterface.php | centreon/src/Security/Domain/Authentication/Interfaces/AuthenticationRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Security\Domain\Authentication\Interfaces;
use Core\Security\Authentication\Domain\Model\AuthenticationTokens;
use Core\Security\Authentication\Domain\Model\NewProviderToken;
use Core\Security\Authentication\Domain\Model\ProviderToken;
interface AuthenticationRepositoryInterface
{
/**
* @param string $sessionToken Session token
* @param int $providerConfigurationId Provider configuration id
* @param int $contactId Contact id
* @param ProviderToken $providerToken Provider token
* @param ProviderToken|null $providerRefreshToken Provider refresh token
*/
public function addAuthenticationTokens(
string $sessionToken,
int $providerConfigurationId,
int $contactId,
ProviderToken $providerToken,
?ProviderToken $providerRefreshToken,
): void;
/**
* Find the authentication token using the session token.
*
* @param string $token Session token
*
* @return AuthenticationTokens|null
*/
public function findAuthenticationTokensByToken(string $token): ?AuthenticationTokens;
/**
* Updates the provider authentication tokens.
*
* @param AuthenticationTokens $authenticationTokens Provider tokens
*/
public function updateAuthenticationTokens(AuthenticationTokens $authenticationTokens): void;
/**
* @param ProviderToken $providerToken
*/
public function updateProviderToken(ProviderToken $providerToken): void;
/**
* Updates the provider token.
*
* @param NewProviderToken $providerToken
*/
public function updateProviderTokenExpirationDate(NewProviderToken $providerToken): void;
/**
* Delete a security token.
*
* @param string $token
*/
public function deleteSecurityToken(string $token): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Security/Infrastructure/Authentication/API/Model_2110/ApiAuthenticationFactory.php | centreon/src/Security/Infrastructure/Authentication/API/Model_2110/ApiAuthenticationFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Security\Infrastructure\Authentication\API\Model_2110;
use Centreon\Domain\Authentication\UseCase\AuthenticateApiResponse;
class ApiAuthenticationFactory
{
/**
* @param AuthenticateApiResponse $response
*
* @return \stdClass
*/
public static function createFromResponse(AuthenticateApiResponse $response): \stdClass
{
$newApiAuthentication = self::createEmptyClass();
$newApiAuthentication->contact['id'] = (int) $response->getApiAuthentication()['contact']['id'];
$newApiAuthentication->contact['name'] = $response->getApiAuthentication()['contact']['name'];
$newApiAuthentication->contact['alias'] = $response->getApiAuthentication()['contact']['alias'];
$newApiAuthentication->contact['email'] = $response->getApiAuthentication()['contact']['email'];
$newApiAuthentication->contact['is_admin'] = (bool) $response->getApiAuthentication()['contact']['is_admin'];
$newApiAuthentication->security['token'] = $response->getApiAuthentication()['security']['token'];
return $newApiAuthentication;
}
/**
* @return \stdClass
*/
private static function createEmptyClass(): \stdClass
{
return new class () extends \stdClass {
/** @var array<string,mixed> */
public $contact;
/** @var array<string,string> */
public $security;
};
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Security/Infrastructure/Repository/AuthenticationRepository.php | centreon/src/Security/Infrastructure/Repository/AuthenticationRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Security\Infrastructure\Repository;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Core\Security\Authentication\Domain\Model\AuthenticationTokens;
use Core\Security\Authentication\Domain\Model\NewProviderToken;
use Core\Security\Authentication\Domain\Model\ProviderToken;
use Security\Domain\Authentication\Interfaces\AuthenticationRepositoryInterface;
use Security\Domain\Authentication\Interfaces\AuthenticationTokenRepositoryInterface;
class AuthenticationRepository extends AbstractRepositoryDRB implements
AuthenticationRepositoryInterface,
AuthenticationTokenRepositoryInterface
{
/**
* @param DatabaseConnection $db
*/
public function __construct(
DatabaseConnection $db,
) {
$this->db = $db;
}
/**
* @inheritDoc
*/
public function addAuthenticationTokens(
string $token,
int $providerConfigurationId,
int $contactId,
ProviderToken $providerToken,
?ProviderToken $providerRefreshToken,
): void {
// We avoid to start again a database transaction
$isAlreadyInTransaction = $this->db->inTransaction();
if ($isAlreadyInTransaction === false) {
$this->db->beginTransaction();
}
try {
$this->insertProviderTokens(
$token,
$providerConfigurationId,
$contactId,
$providerToken,
$providerRefreshToken
);
if ($isAlreadyInTransaction === false) {
$this->db->commit();
}
} catch (\Exception $e) {
if ($isAlreadyInTransaction === false) {
$this->db->rollBack();
}
throw $e;
}
}
/**
* {@inheritDoc}
*
* @throws \Assert\AssertionFailedException
*/
public function findAuthenticationTokensByToken(string $token): ?AuthenticationTokens
{
$statement = $this->db->prepare($this->translateDbName('
SELECT sat.user_id, sat.provider_configuration_id,
provider_token.id as pt_id,
provider_token.token AS provider_token,
provider_token.creation_date as provider_token_creation_date,
provider_token.expiration_date as provider_token_expiration_date,
refresh_token.id as rt_id,
refresh_token.token AS refresh_token,
refresh_token.creation_date as refresh_token_creation_date,
refresh_token.expiration_date as refresh_token_expiration_date
FROM `:db`.security_authentication_tokens sat
INNER JOIN `:db`.security_token provider_token ON provider_token.id = sat.provider_token_id
LEFT JOIN `:db`.security_token refresh_token ON refresh_token.id = sat.provider_token_refresh_id
WHERE sat.token = :token
'));
$statement->bindValue(':token', $token, \PDO::PARAM_STR);
$statement->execute();
if ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
$expirationDate = $result['provider_token_expiration_date'] !== null
? (new \DateTimeImmutable())->setTimestamp((int) $result['provider_token_expiration_date'])
: null;
$providerToken = new ProviderToken(
(int) $result['pt_id'],
$result['provider_token'],
(new \DateTimeImmutable())->setTimestamp((int) $result['provider_token_creation_date']),
$expirationDate
);
$providerRefreshToken = null;
if ($result['refresh_token'] !== null) {
$expirationDate = $result['refresh_token_expiration_date'] !== null
? (new \DateTimeImmutable())->setTimestamp((int) $result['refresh_token_expiration_date'])
: null;
$providerRefreshToken = new ProviderToken(
(int) $result['rt_id'],
$result['refresh_token'],
(new \DateTimeImmutable())->setTimestamp((int) $result['refresh_token_creation_date']),
$expirationDate
);
}
return new AuthenticationTokens(
(int) $result['user_id'],
(int) $result['provider_configuration_id'],
$token,
$providerToken,
$providerRefreshToken
);
}
return null;
}
/**
* @inheritDoc
*/
public function findAuthenticationTokensByContact(ContactInterface $contact): ?AuthenticationTokens
{
$statement = $this->db->prepare($this->translateDbName('
SELECT sat.user_id, sat.provider_configuration_id,
provider_token.token AS provider_token,
provider_token.creation_date as provider_token_creation_date,
provider_token.expiration_date as provider_token_expiration_date,
refresh_token.token AS refresh_token,
refresh_token.creation_date as refresh_token_creation_date,
refresh_token.expiration_date as refresh_token_expiration_date
FROM `:db`.security_authentication_tokens sat
INNER JOIN `:db`.security_token provider_token ON provider_token.id = sat.provider_token_id
LEFT JOIN `:db`.security_token refresh_token ON refresh_token.id = sat.provider_token_refresh_id
WHERE sat.user_id = :user_id
'));
$statement->bindValue(':user_id', $contact->getId(), \PDO::PARAM_INT);
$statement->execute();
if ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
$expirationDate = $result['provider_token_expiration_date'] !== null
? (new \DateTimeImmutable())->setTimestamp((int) $result['provider_token_expiration_date'])
: null;
$providerToken = new NewProviderToken(
$result['provider_token'],
(new \DateTimeImmutable())->setTimestamp((int) $result['provider_token_creation_date']),
$expirationDate
);
$providerRefreshToken = null;
if ($result['refresh_token'] !== null) {
$expirationDate = $result['refresh_token_expiration_date'] !== null
? (new \DateTimeImmutable())->setTimestamp((int) $result['refresh_token_expiration_date'])
: null;
$providerRefreshToken = new NewProviderToken(
$result['refresh_token'],
(new \DateTimeImmutable())->setTimestamp((int) $result['refresh_token_creation_date']),
$expirationDate
);
}
return new AuthenticationTokens(
(int) $result['user_id'],
(int) $result['provider_configuration_id'],
'fake_value',
$providerToken,
$providerRefreshToken
);
}
return null;
}
/**
* @inheritDoc
*/
public function updateAuthenticationTokens(AuthenticationTokens $authenticationTokens): void
{
if ($authenticationTokens->getProviderToken() instanceof ProviderToken) {
$this->updateProviderToken($authenticationTokens->getProviderToken());
}
if ($authenticationTokens->getProviderRefreshToken() instanceof ProviderToken) {
$this->updateProviderToken($authenticationTokens->getProviderRefreshToken());
}
}
/**
* @inheritDoc
*/
public function updateProviderToken(ProviderToken $providerToken): void
{
$updateStatement = $this->db->prepare(
$this->translateDbName(
<<<'SQL'
UPDATE `:db`.security_token
SET creation_date = :creation_date,
expiration_date = :expiration_date,
token = :token
WHERE id = :token_id
SQL
)
);
$updateStatement->bindValue(
':creation_date',
$providerToken->getCreationDate()->getTimestamp(),
\PDO::PARAM_INT
);
$updateStatement->bindValue(
':expiration_date',
$providerToken->getExpirationDate()->getTimestamp(),
\PDO::PARAM_INT
);
$updateStatement->bindValue(':token', $providerToken->getToken(), \PDO::PARAM_STR);
$updateStatement->bindValue(':token_id', $providerToken->getId(), \PDO::PARAM_INT);
$updateStatement->execute();
}
/**
* @inheritDoc
*/
public function updateProviderTokenExpirationDate(NewProviderToken $providerToken): void
{
$updateStatement = $this->db->prepare(
$this->translateDbName(
'UPDATE `:db`.security_token SET expiration_date = :expiredAt WHERE token = :token'
)
);
$updateStatement->bindValue(
':expiredAt',
$providerToken->getExpirationDate()?->getTimestamp(),
\PDO::PARAM_INT
);
$updateStatement->bindValue(':token', $providerToken->getToken(), \PDO::PARAM_STR);
$updateStatement->execute();
}
public function deleteSecurityToken(string $token): void
{
$deleteSecurityTokenStatement = $this->db->prepare(
$this->translateDbName(
'DELETE FROM `:db`.security_token WHERE token = :token'
)
);
$deleteSecurityTokenStatement->bindValue(':token', $token, \PDO::PARAM_STR);
$deleteSecurityTokenStatement->execute();
}
/**
* Insert session, security and refresh tokens.
*
* @param string $token
* @param int $providerConfigurationId
* @param int $contactId
* @param ProviderToken $providerToken
* @param ProviderToken|null $providerRefreshToken
*/
private function insertProviderTokens(
string $token,
int $providerConfigurationId,
int $contactId,
ProviderToken $providerToken,
?ProviderToken $providerRefreshToken,
): void {
$this->insertSecurityToken($providerToken);
$securityTokenId = (int) $this->db->lastInsertId();
$securityRefreshTokenId = null;
if ($providerRefreshToken !== null) {
$this->insertSecurityToken($providerRefreshToken);
$securityRefreshTokenId = (int) $this->db->lastInsertId();
}
$this->insertSecurityAuthenticationToken(
$token,
$contactId,
$securityTokenId,
$securityRefreshTokenId,
$providerConfigurationId
);
}
/**
* Insert provider token into security_token table.
*
* @param ProviderToken $providerToken
*/
private function insertSecurityToken(ProviderToken $providerToken): void
{
$insertSecurityTokenStatement = $this->db->prepare(
$this->translateDbName(
'INSERT INTO `:db`.security_token (`token`, `creation_date`, `expiration_date`) '
. 'VALUES (:token, :createdAt, :expireAt)'
)
);
$insertSecurityTokenStatement->bindValue(':token', $providerToken->getToken(), \PDO::PARAM_STR);
$insertSecurityTokenStatement->bindValue(
':createdAt',
$providerToken->getCreationDate()->getTimestamp(),
\PDO::PARAM_INT
);
$insertSecurityTokenStatement->bindValue(
':expireAt',
$providerToken->getExpirationDate() !== null ? $providerToken->getExpirationDate()->getTimestamp() : null,
\PDO::PARAM_INT
);
$insertSecurityTokenStatement->execute();
}
/**
* Insert tokens and configuration id in security_authentication_tokens table.
*
* @param string $sessionId
* @param int $contactId
* @param int $securityTokenId
* @param int|null $securityRefreshTokenId
* @param int $providerConfigurationId
*/
private function insertSecurityAuthenticationToken(
string $sessionId,
int $contactId,
int $securityTokenId,
?int $securityRefreshTokenId,
int $providerConfigurationId,
): void {
$insertSecurityAuthenticationStatement = $this->db->prepare(
$this->translateDbName(
'INSERT INTO `:db`.security_authentication_tokens '
. '(`token`, `provider_token_id`, `provider_token_refresh_id`, `provider_configuration_id`, `user_id`) '
. 'VALUES (:sessionTokenId, :tokenId, :refreshTokenId, :configurationId, :userId)'
)
);
$insertSecurityAuthenticationStatement->bindValue(':sessionTokenId', $sessionId, \PDO::PARAM_STR);
$insertSecurityAuthenticationStatement->bindValue(':tokenId', $securityTokenId, \PDO::PARAM_INT);
$insertSecurityAuthenticationStatement->bindValue(':refreshTokenId', $securityRefreshTokenId, \PDO::PARAM_INT);
$insertSecurityAuthenticationStatement->bindValue(
':configurationId',
$providerConfigurationId,
\PDO::PARAM_INT
);
$insertSecurityAuthenticationStatement->bindValue(':userId', $contactId, \PDO::PARAM_INT);
$insertSecurityAuthenticationStatement->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Security/Infrastructure/Repository/SessionRepository.php | centreon/src/Security/Infrastructure/Repository/SessionRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Security\Infrastructure\Repository;
use Centreon\Domain\Repository\AbstractRepositoryDRB;
use Centreon\Infrastructure\DatabaseConnection;
use Security\Domain\Authentication\Interfaces\SessionRepositoryInterface;
use Security\Domain\Authentication\Model\Session;
class SessionRepository extends AbstractRepositoryDRB implements SessionRepositoryInterface
{
/**
* @param DatabaseConnection $db
*/
public function __construct(
DatabaseConnection $db,
) {
$this->db = $db;
}
/**
* @inheritDoc
*/
public function deleteSession(string $token): void
{
$deleteSessionStatement = $this->db->prepare(
$this->translateDbName(
'DELETE FROM `:db`.session WHERE session_id = :token'
)
);
$deleteSessionStatement->bindValue(':token', $token, \PDO::PARAM_STR);
$deleteSessionStatement->execute();
}
/**
* @inheritDoc
*/
public function deleteExpiredSession(): void
{
$sessionIdStatement = $this->db->query(
'SELECT session_id FROM `session`
WHERE last_reload <
(SELECT UNIX_TIMESTAMP(NOW() - INTERVAL (`value` * 60) SECOND)
FROM `options`
wHERE `key` = \'session_expire\')
OR last_reload IS NULL
OR session_id NOT IN (SELECT token FROM security_authentication_tokens)'
);
if (
$sessionIdStatement !== false
&& ($results = $sessionIdStatement->fetchAll(\PDO::FETCH_ASSOC))
) {
foreach ($results as $result) {
$this->deleteSession($result['session_id']);
}
}
}
/**
* @inheritDoc
*/
public function addSession(Session $session): void
{
$insertSessionStatement = $this->db->prepare(
$this->translateDbName(
'INSERT INTO `:db`.session (`session_id` , `user_id` , `last_reload`, `ip_address`) '
. 'VALUES (:sessionId, :userId, :lastReload, :ipAddress)'
)
);
$insertSessionStatement->bindValue(':sessionId', $session->getToken(), \PDO::PARAM_STR);
$insertSessionStatement->bindValue(':userId', $session->getContactId(), \PDO::PARAM_INT);
$insertSessionStatement->bindValue(':lastReload', time(), \PDO::PARAM_INT);
$insertSessionStatement->bindValue(':ipAddress', $session->getClientIp(), \PDO::PARAM_STR);
$insertSessionStatement->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Security/Infrastructure/Repository/Model/ProviderConfigurationFactoryRdb.php | centreon/src/Security/Infrastructure/Repository/Model/ProviderConfigurationFactoryRdb.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Security\Infrastructure\Repository\Model;
use Core\Security\ProviderConfiguration\Domain\Model\Configuration;
class ProviderConfigurationFactoryRdb
{
/**
* @param array<string,mixed> $data
*
* @return Configuration
*/
public static function create(array $data): Configuration
{
$mandatoryFields = ['id', 'type', 'name', 'is_active', 'is_forced'];
foreach ($mandatoryFields as $mandatoryField) {
if (! array_key_exists($mandatoryField, $data)) {
throw new \InvalidArgumentException(
sprintf(_("Missing mandatory parameter: '%s'"), $mandatoryField)
);
}
}
return new Configuration(
(int) $data['id'],
$data['type'],
$data['name'],
$data['custom_configuration'],
(bool) $data['is_active'],
(bool) $data['is_forced']
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/polyfill.php | centreon/tests/php/polyfill.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
// add gnupg class polyfill
if (! class_exists('gnupg')) {
class gnupg
{
public const SIG_MODE_CLEAR = null;
public function import($keydata = null): array
{
return [];
}
public function setsignmode(?int $signmode = null): bool
{
return true;
}
public function verify($licensedata, $status, &$plaintext)
{
return true;
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/bootstrap.php | centreon/tests/php/bootstrap.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
// mock path constants to redirect to base centreon directory
$mockedPathConstants = ['_CENTREON_PATH_', '_CENTREON_ETC_', '_CENTREON_LOG_', '_CENTREON_CACHEDIR_'];
foreach ($mockedPathConstants as $mockedPathConstant) {
if (! defined($mockedPathConstant)) {
define($mockedPathConstant, realpath(__DIR__ . '/../../') . '/');
}
}
$mockedPreRequisiteConstants = [
'_CENTREON_PHP_VERSION_' => '8.2',
'_CENTREON_MARIA_DB_MIN_VERSION_' => '10.5',
];
foreach ($mockedPreRequisiteConstants as $mockedPreRequisiteConstant => $value) {
if (! defined($mockedPreRequisiteConstant)) {
define($mockedPreRequisiteConstant, $value);
}
}
// mock variable constants to redirect to base centreon directory
$mockedVarConstants = ['hostCentreon', 'hostCentstorage', 'user', 'password', 'db', 'dbcstg', 'port'];
foreach ($mockedVarConstants as $mockedVarConstant) {
if (! defined($mockedVarConstant)) {
define($mockedVarConstant, '');
}
}
// Disable warnings for PEAR.
error_reporting(E_ALL & ~E_STRICT);
require_once realpath(__DIR__ . '/polyfill.php');
$loader = require realpath(__DIR__ . '/../../vendor/autoload.php');
Doctrine\Common\Annotations\AnnotationRegistry::registerLoader([$loader, 'loadClass']);
if (! function_exists('loadDependencyInjector')) {
// Mock DB manager
Tests\Centreon\DependencyInjector::getInstance()[Centreon\ServiceProvider::CENTREON_DB_MANAGER]
= new Centreon\Test\Mock\CentreonDBManagerService();
function loadDependencyInjector()
{
return Tests\Centreon\DependencyInjector::getInstance();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/CentreonRemote/ServiceProviderTest.php | centreon/tests/php/CentreonRemote/ServiceProviderTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\CentreonRemote;
use Centreon\Domain\Repository\CfgCentreonBrokerRepository;
use Centreon\Domain\Service\BrokerConfigurationService;
use Centreon\Infrastructure\Service\CentcoreConfigService;
use Centreon\Infrastructure\Service\CentreonDBManagerService;
use Centreon\Test\Mock\CentreonDB;
use CentreonACL;
use CentreonRemote\Domain\Exporter\ConfigurationExporter;
use CentreonRemote\Domain\Service\ConfigurationWizard\LinkedPollerConfigurationService;
use CentreonRemote\Domain\Service\ConfigurationWizard\PollerConfigurationRequestBridge;
use CentreonRemote\Domain\Service\ConfigurationWizard\PollerConnectionConfigurationService;
use CentreonRemote\Domain\Service\ConfigurationWizard\RemoteConnectionConfigurationService;
use CentreonRemote\Domain\Service\InformationsService;
use CentreonRemote\Domain\Service\NotifyMasterService;
use CentreonRemote\Domain\Service\TaskService;
use CentreonRemote\Infrastructure\Service\ExporterCacheService;
use CentreonRemote\Infrastructure\Service\ExporterService;
use CentreonRemote\Infrastructure\Service\ExportService;
use CentreonRemote\ServiceProvider;
use CentreonRestHttp;
use Pimple\Container;
use Pimple\Psr11\ServiceLocator;
beforeEach(function (): void {
$this->provider = new ServiceProvider();
$this->container = new Container();
$this->container['centreon.acl'] = $this->createMock(CentreonACL::class);
$this->container['centreon.config'] = $this->createMock(CentcoreConfigService::class);
$this->container['realtime_db'] = new CentreonDB();
$this->container['configuration_db'] = new CentreonDB();
$this->container['configuration_db']->addResultSet('SELECT * FROM informations WHERE `key` = :key LIMIT 1', []);
$this->container['rest_http'] = $this->createMock(CentreonRestHttp::class);
$locator = new ServiceLocator($this->container, ['realtime_db', 'configuration_db']);
$this->container[\Centreon\ServiceProvider::CENTREON_DB_MANAGER] = new CentreonDBManagerService($locator);
$this->container[\Centreon\ServiceProvider::CENTREON_WEBSERVICE] = new class () {
public function add(): self
{
return $this;
}
};
$this->container[\Centreon\ServiceProvider::CENTREON_CLAPI] = new class () {
public function add(): self
{
return $this;
}
};
$this->container['yml.config'] = function (): array {
return [];
};
$this->container[\Centreon\ServiceProvider::CENTREON_BROKER_REPOSITORY] = new CfgCentreonBrokerRepository(
$this->container['configuration_db']
);
$this->container['centreon.broker_configuration_service'] = new BrokerConfigurationService();
$this->provider->register($this->container);
});
it('check services by list', function (): void {
$checkList = [
'centreon.notifymaster' => NotifyMasterService::class,
'centreon.taskservice' => TaskService::class,
'centreon_remote.informations_service' => InformationsService::class,
'centreon_remote.remote_connection_service' => RemoteConnectionConfigurationService::class,
'centreon_remote.poller_connection_service' => PollerConnectionConfigurationService::class,
'centreon_remote.poller_config_service' => LinkedPollerConfigurationService::class,
'centreon_remote.poller_config_bridge' => PollerConfigurationRequestBridge::class,
'centreon_remote.export' => ExportService::class,
'centreon_remote.exporter' => ExporterService::class,
'centreon_remote.exporter.cache' => ExporterCacheService::class,
];
// check list of services
foreach ($checkList as $serviceName => $className) {
$this->assertTrue($this->container->offsetExists($serviceName));
$service = $this->container->offsetGet($serviceName);
expect($service)->toBeInstanceOf($className);
}
});
it('check exporters by list', function (): void {
$checkList = [
ConfigurationExporter::class,
];
$exporter = $this->container['centreon_remote.exporter'];
// check list of exporters
foreach ($checkList as $className) {
$name = $className::getName();
expect($exporter->has($name))->toBeTrue();
$data = $exporter->get($className::getName());
expect($data['name'])->toBe($name);
expect($data['classname'])->toBe($className);
$object = $data['factory']($this->container);
expect($object)->toBeInstanceOf($className);
}
});
it('test provider order', function (): void {
expect($this->provider::order())->toBeGreaterThanOrEqual(1);
expect($this->provider::order())->toBeLessThanOrEqual(20);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/CentreonRemote/Infrastructure/Export/ExportParserJsonTest.php | centreon/tests/php/CentreonRemote/Infrastructure/Export/ExportParserJsonTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Tests\CentreonRemote\Infrastructure\Export;
use CentreonRemote\Infrastructure\Export\ExportParserJson;
use Symfony\Component\Filesystem\Filesystem;
beforeEach(function (): void {
$this->fileSystem = new Filesystem();
$this->fileSystem->mkdir('/tmp');
$this->parser = new ExportParserJson();
});
afterEach(function (): void {
$this->fileSystem->remove('/tmp/test.json');
$this->fileSystem->remove('/tmp/test2.json');
});
it('should parse non existent file', function (): void {
expect($this->parser->parse('/tmp/test.json'))->toBe([]);
});
it('should parse file', function (): void {
$this->fileSystem->dumpFile('/tmp/test.json', '{"key": "value"}');
expect($this->parser->parse('/tmp/test.json'))->toBe(['key' => 'value']);
});
it('should call the callback for a file with macro', function (): void {
$this->fileSystem->dumpFile('/tmp/test2.json', '{"key":"@val@"}');
$result = $this->parser->parse(
'/tmp/test2.json',
function (&$result): void {
$result = str_replace('@val@', 'val', $result);
}
);
expect($result)->toBe(['key' => 'val']);
});
it('should not create manifest file if input is an empty array', function (): void {
$this->parser->dump([], '/tmp/test.json');
expect($this->fileSystem->exists('/tmp/test.json'))->toBeFalse();
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/CentreonRemote/Infrastructure/Export/ExportManifestTest.php | centreon/tests/php/CentreonRemote/Infrastructure/Export/ExportManifestTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Tests\CentreonRemote\Infrastructure\Export;
use CentreonRemote\Infrastructure\Export\ExportCommitment;
use CentreonRemote\Infrastructure\Export\ExportManifest;
use CentreonRemote\Infrastructure\Export\ExportParserJson;
beforeEach(function (): void {
$this->dumpData = [];
$parser = $this->getMockBuilder(ExportParserJson::class)
->onlyMethods(['parse', 'dump'])
->getMock();
$parser->method('parse')
->willReturnCallback(function () {
return [];
});
$parser->method('dump')
->willReturnCallback(function (): void {
$args = func_get_args();
$this->dumpData[$args[1]] = $args[0];
});
$this->commitment = new ExportCommitment(1, [2, 3], null, $parser);
$this->manifest = $this->getMockBuilder(ExportManifest::class)
->onlyMethods(['getFile'])
->setConstructorArgs([$this->commitment, '18.10'])
->getMock();
$this->manifest->method('getFile')
->willReturn(__FILE__);
});
test('it returns null for missing data', function (): void {
expect($this->manifest->get('missing-data'))->toBeNull();
});
test('it dumps the correct data', function (): void {
$date = date('l jS \of F Y h:i:s A');
$this->manifest->dump([
'date' => $date,
'remote_server' => $this->commitment->getRemote(),
'pollers' => $this->commitment->getPollers(),
'import' => null,
]);
expect($this->dumpData)->toEqual([
$this->manifest->getFile() => [
'version' => '18.10',
'date' => $date,
'remote_server' => $this->commitment->getRemote(),
'pollers' => $this->commitment->getPollers(),
'import' => null,
],
]);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Adaptation/Database/ExpressionBuilder/Adapter/Dbal/DbalExpressionBuilderAdapterTest.php | centreon/tests/php/Adaptation/Database/ExpressionBuilder/Adapter/Dbal/DbalExpressionBuilderAdapterTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Adaptation\Database\ExpressionBuilder\Adapter\Dbal;
use Adaptation\Database\ExpressionBuilder\Adapter\Dbal\DbalExpressionBuilderAdapter;
use Adaptation\Database\ExpressionBuilder\Enum\ComparisonOperatorEnum;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Query\Expression\ExpressionBuilder;
beforeEach(function (): void {
$connection = \Mockery::mock(Connection::class);
$dbalExpressionBuilder = new ExpressionBuilder($connection);
$this->dbalExpressionBuilderAdapterTest = new DbalExpressionBuilderAdapter($dbalExpressionBuilder);
});
it('test with the method comparison', function (): void {
$expr = $this->dbalExpressionBuilderAdapterTest->comparison('field1', ComparisonOperatorEnum::EQUAL, ':value1');
expect($expr)->toBeString()->toBe('field1 = :value1');
});
it('test with the method equal', function (): void {
$expr = $this->dbalExpressionBuilderAdapterTest->equal('field1', ':value1');
expect($expr)->toBeString()->toBe('field1 = :value1');
});
it('test with the method notEqual', function (): void {
$expr = $this->dbalExpressionBuilderAdapterTest->notEqual('field1', ':value1');
expect($expr)->toBeString()->toBe('field1 <> :value1');
});
it('test with the method lowerThan', function (): void {
$expr = $this->dbalExpressionBuilderAdapterTest->lowerThan('field1', ':value1');
expect($expr)->toBeString()->toBe('field1 < :value1');
});
it('test with the method lowerThanEqual', function (): void {
$expr = $this->dbalExpressionBuilderAdapterTest->lowerThanEqual('field1', ':value1');
expect($expr)->toBeString()->toBe('field1 <= :value1');
});
it('test with the method greaterThan', function (): void {
$expr = $this->dbalExpressionBuilderAdapterTest->greaterThan('field1', ':value1');
expect($expr)->toBeString()->toBe('field1 > :value1');
});
it('test with the method greaterThanEqual', function (): void {
$expr = $this->dbalExpressionBuilderAdapterTest->greaterThanEqual('field1', ':value1');
expect($expr)->toBeString()->toBe('field1 >= :value1');
});
it('test with the method isNull', function (): void {
$expr = $this->dbalExpressionBuilderAdapterTest->isNull('field1');
expect($expr)->toBeString()->toBe('field1 IS NULL');
});
it('test with the method isNotNull', function (): void {
$expr = $this->dbalExpressionBuilderAdapterTest->isNotNull('field1');
expect($expr)->toBeString()->toBe('field1 IS NOT NULL');
});
it('test with the method like', function (): void {
$expr = $this->dbalExpressionBuilderAdapterTest->like('field1', ':value1');
expect($expr)->toBeString()->toBe('field1 LIKE :value1');
});
it('test with the method like with escape', function (): void {
$expr = $this->dbalExpressionBuilderAdapterTest->like('field1', ':value1', '$');
expect($expr)->toBeString()->toBe('field1 LIKE :value1 ESCAPE $');
});
it('test with the method notLike', function (): void {
$expr = $this->dbalExpressionBuilderAdapterTest->notLike('field1', ':value1');
expect($expr)->toBeString()->toBe('field1 NOT LIKE :value1');
});
it('test with the method notLike with escape', function (): void {
$expr = $this->dbalExpressionBuilderAdapterTest->notLike('field1', ':value1', '$');
expect($expr)->toBeString()->toBe('field1 NOT LIKE :value1 ESCAPE $');
});
it('test with the method in with string', function (): void {
$expr = $this->dbalExpressionBuilderAdapterTest->in('field1', ':value1');
expect($expr)->toBeString()->toBe('field1 IN (:value1)');
});
it('test with the method in with array', function (): void {
$expr = $this->dbalExpressionBuilderAdapterTest->in('field1', [':value1', ':value2']);
expect($expr)->toBeString()->toBe('field1 IN (:value1, :value2)');
});
it('test with the method notIn with string', function (): void {
$expr = $this->dbalExpressionBuilderAdapterTest->notIn('field1', ':value1');
expect($expr)->toBeString()->toBe('field1 NOT IN (:value1)');
});
it('test with the method notIn with array', function (): void {
$expr = $this->dbalExpressionBuilderAdapterTest->notIn('field1', [':value1', ':value2']);
expect($expr)->toBeString()->toBe('field1 NOT IN (:value1, :value2)');
});
it('test with the method and', function (): void {
$expr = $this->dbalExpressionBuilderAdapterTest->and(
'field1 = :value1',
'field2 = :value2',
'field3 = :value3'
);
expect($expr)->toBeString()->toBe('(field1 = :value1) AND (field2 = :value2) AND (field3 = :value3)');
});
it('test with the method and with expressions', function (): void {
$expr = $this->dbalExpressionBuilderAdapterTest->and(
$this->dbalExpressionBuilderAdapterTest->equal('field1', ':value1'),
$this->dbalExpressionBuilderAdapterTest->equal('field2', ':value2'),
$this->dbalExpressionBuilderAdapterTest->equal('field3', ':value3')
);
expect($expr)->toBeString()->toBe('(field1 = :value1) AND (field2 = :value2) AND (field3 = :value3)');
});
it('test with the method or', function (): void {
$expr = $this->dbalExpressionBuilderAdapterTest->or(
'field1 = :value1',
'field2 = :value2',
'field3 = :value3'
);
expect($expr)->toBeString()->toBe('(field1 = :value1) OR (field2 = :value2) OR (field3 = :value3)');
});
it('test with the method or with expressions', function (): void {
$expr = $this->dbalExpressionBuilderAdapterTest->or(
$this->dbalExpressionBuilderAdapterTest->equal('field1', ':value1'),
$this->dbalExpressionBuilderAdapterTest->equal('field2', ':value2'),
$this->dbalExpressionBuilderAdapterTest->equal('field3', ':value3')
);
expect($expr)->toBeString()->toBe('(field1 = :value1) OR (field2 = :value2) OR (field3 = :value3)');
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Adaptation/Database/QueryBuilder/Adapter/Dbal/DbalQueryBuilderAdapterTest.php | centreon/tests/php/Adaptation/Database/QueryBuilder/Adapter/Dbal/DbalQueryBuilderAdapterTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Adaptation\Database\QueryBuilder\Adapter\Dbal;
use Adaptation\Database\Connection\Model\ConnectionConfig;
use Adaptation\Database\QueryBuilder\Adapter\Dbal\DbalQueryBuilderAdapter;
use Adaptation\Database\QueryBuilder\Exception\QueryBuilderException;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Query\QueryBuilder;
use Doctrine\DBAL\SQL\Builder\DefaultSelectSQLBuilder;
use Doctrine\DBAL\SQL\Builder\DefaultUnionSQLBuilder;
beforeEach(function (): void {
// prepare instanciation of ConnectionConfig with a mock (mandatory)
$connectionConfig = new ConnectionConfig(
host: 'fake_host',
user: 'fake_user',
password: 'fake_password',
databaseNameConfiguration: 'fake_databaseName',
databaseNameRealTime: 'fake_databaseNameStorage'
);
// prepare instanciation of DbalQueryBuilderAdapter with mocking of dbal Connection (mandatory)
$dbalConnection = \Mockery::mock(Connection::class);
$platform = \Mockery::mock(AbstractPlatform::class);
$platform->shouldReceive('getUnionSelectPartSQL')
->andReturnArg(0);
$platform->shouldReceive('getUnionAllSQL')
->andReturn('UNION ALL');
$platform->shouldReceive('getUnionDistinctSQL')
->andReturn('UNION');
$platform->shouldReceive('createSelectSQLBuilder')
->andReturn(new DefaultSelectSQLBuilder($platform, null, null));
$platform->shouldReceive('createUnionSQLBuilder')
->andReturn(new DefaultUnionSQLBuilder($platform));
$dbalConnection->shouldReceive('getDatabasePlatform')
->andReturn($platform);
// instanciation of DbalQueryBuilderAdapter
$dbalQueryBuilder = new QueryBuilder($dbalConnection);
$this->dbalQueryBuilderAdapterTest = new DbalQueryBuilderAdapter($dbalQueryBuilder, $connectionConfig);
});
it('expr with error because no database connection', function (): void {
$this->dbalQueryBuilderAdapterTest->expr();
})->throws(QueryBuilderException::class);
it('select with one parameter', function (): void {
$query = $this->dbalQueryBuilderAdapterTest->select('field1')->getQuery();
expect($query)->toBeString()->toBe('SELECT field1');
});
it('select with several parameters', function (): void {
$query = $this->dbalQueryBuilderAdapterTest->select('field1', 'field2', 'alias.field3')->getQuery();
expect($query)->toBeString()->toBe('SELECT field1, field2, alias.field3');
});
it('select distinct', function (): void {
$query = $this->dbalQueryBuilderAdapterTest->select('field1')->distinct()->getQuery();
expect($query)->toBeString()->toBe('SELECT DISTINCT field1');
});
it('addSelect with one parameter', function (): void {
$query = $this->dbalQueryBuilderAdapterTest->select('field1')->addSelect('field2')->getQuery();
expect($query)->toBeString()->toBe('SELECT field1, field2');
});
it('addSelect with several parameters', function (): void {
$query = $this->dbalQueryBuilderAdapterTest->select('field1')->addSelect('field2', 'field3')->getQuery();
expect($query)->toBeString()->toBe('SELECT field1, field2, field3');
});
it('delete', function (): void {
$query = $this->dbalQueryBuilderAdapterTest->delete('table')->getQuery();
expect($query)->toBeString()->toBe('DELETE FROM table');
});
it('update', function (): void {
$query = $this->dbalQueryBuilderAdapterTest->update('table')->getQuery();
expect($query)->toBeString()->toBe('UPDATE table SET ');
});
it('update with an alias', function (): void {
$query = $this->dbalQueryBuilderAdapterTest->update('table foo')->getQuery();
expect($query)->toBeString()->toBe('UPDATE table foo SET ');
});
it('update with set one field', function (): void {
$query = $this->dbalQueryBuilderAdapterTest->update('table')->set('field1', 'value1')->getQuery();
expect($query)->toBeString()->toBe('UPDATE table SET field1 = value1');
});
it('update with set several fields', function (): void {
$sets = ['field1' => 'value1', 'field2' => 'value2'];
$this->dbalQueryBuilderAdapterTest->update('table');
foreach ($sets as $column => $value) {
$this->dbalQueryBuilderAdapterTest->set($column, $value);
}
$query = $this->dbalQueryBuilderAdapterTest->getQuery();
expect($query)->toBeString()->toBe('UPDATE table SET field1 = value1, field2 = value2');
});
it('insert ', function (): void {
$query = $this->dbalQueryBuilderAdapterTest->insert('table')->getQuery();
expect($query)->toBeString()->toBe('INSERT INTO table () VALUES()');
});
it('insert with fields', function (): void {
$query = $this->dbalQueryBuilderAdapterTest->insert('table')->values(
['field1' => 'value1', 'field2' => 'value2']
)->getQuery();
expect($query)->toBeString()->toBe('INSERT INTO table (field1, field2) VALUES(value1, value2)');
});
it('insert with a field added', function (): void {
$query = $this->dbalQueryBuilderAdapterTest->insert('table')->values(
['field1' => 'value1', 'field2' => 'value2']
)->setValue('field3', 'value3')->getQuery();
expect($query)->toBeString()->toBe('INSERT INTO table (field1, field2, field3) VALUES(value1, value2, value3)');
});
it('insert with a field updated', function (): void {
$query = $this->dbalQueryBuilderAdapterTest->insert('table')->values(
['field1' => 'value1', 'field2' => 'value2']
)->setValue('field1', 'value3')->getQuery();
expect($query)->toBeString()->toBe('INSERT INTO table (field1, field2) VALUES(value3, value2)');
});
it('from ', function (): void {
$query = $this->dbalQueryBuilderAdapterTest->select('field1')->from('table')->getQuery();
expect($query)->toBeString()->toBe('SELECT field1 FROM table');
});
it('from with an alias', function (): void {
$query = $this->dbalQueryBuilderAdapterTest->select('field1')->from('table', 'foo')->getQuery();
expect($query)->toBeString()->toBe('SELECT field1 FROM table foo');
});
it('join ', function (): void {
$query = $this->dbalQueryBuilderAdapterTest
->select('field1')
->from('table', 'foo')
->join('foo', 'table2', 'bar', 'foo.id = bar.id')
->getQuery();
expect($query)->toBeString()->toBe('SELECT field1 FROM table foo INNER JOIN table2 bar ON foo.id = bar.id');
});
it('inner join', function (): void {
$query = $this->dbalQueryBuilderAdapterTest
->select('field1')
->from('table', 'foo')
->innerJoin('foo', 'table2', 'bar', 'foo.id = bar.id')
->getQuery();
expect($query)->toBeString()->toBe('SELECT field1 FROM table foo INNER JOIN table2 bar ON foo.id = bar.id');
});
it('left join', function (): void {
$query = $this->dbalQueryBuilderAdapterTest
->select('field1')
->from('table', 'foo')
->leftJoin('foo', 'table2', 'bar', 'foo.id = bar.id')
->getQuery();
expect($query)->toBeString()->toBe('SELECT field1 FROM table foo LEFT JOIN table2 bar ON foo.id = bar.id');
});
it('right join', function (): void {
$query = $this->dbalQueryBuilderAdapterTest
->select('field1')
->from('table', 'foo')
->rightJoin('foo', 'table2', 'bar', 'foo.id = bar.id')
->getQuery();
expect($query)->toBeString()->toBe('SELECT field1 FROM table foo RIGHT JOIN table2 bar ON foo.id = bar.id');
});
it('where', function (): void {
$query = $this->dbalQueryBuilderAdapterTest
->select('field1')
->from('table', 'foo')
->where('field1 = value1')
->getQuery();
expect($query)->toBeString()->toBe('SELECT field1 FROM table foo WHERE field1 = value1');
});
it('andWhere', function (): void {
$query = $this->dbalQueryBuilderAdapterTest
->select('field1')
->from('table', 'foo')
->where('field1 = value1')
->andWhere('field2 = value2')
->getQuery();
expect($query)->toBeString()->toBe('SELECT field1 FROM table foo WHERE (field1 = value1) AND (field2 = value2)');
});
it('orWhere', function (): void {
$query = $this->dbalQueryBuilderAdapterTest
->select('field1')
->from('table', 'foo')
->where('field1 = value1')
->orWhere('field2 = value2')
->getQuery();
expect($query)->toBeString()->toBe('SELECT field1 FROM table foo WHERE (field1 = value1) OR (field2 = value2)');
});
it('groupBy', function (): void {
$query = $this->dbalQueryBuilderAdapterTest
->select('field1')
->from('table', 'foo')
->where('field1 = value1')
->groupBy('field1')
->getQuery();
expect($query)->toBeString()->toBe('SELECT field1 FROM table foo WHERE field1 = value1 GROUP BY field1');
});
it('addGroupBy', function (): void {
$query = $this->dbalQueryBuilderAdapterTest
->select('field1')
->from('table', 'foo')
->where('field1 = value1')
->groupBy('field1')
->addGroupBy('field2')
->getQuery();
expect($query)->toBeString()->toBe('SELECT field1 FROM table foo WHERE field1 = value1 GROUP BY field1, field2');
});
it('having', function (): void {
$query = $this->dbalQueryBuilderAdapterTest
->select('field1')
->from('table', 'foo')
->groupBy('field1')
->having('field1 = value1')
->getQuery();
expect($query)->toBeString()->toBe('SELECT field1 FROM table foo GROUP BY field1 HAVING field1 = value1');
});
it('andHaving', function (): void {
$query = $this->dbalQueryBuilderAdapterTest
->select('field1')
->from('table', 'foo')
->groupBy('field1')
->having('field1 = value1')
->andHaving('field2 = value2')
->getQuery();
expect($query)->toBeString()->toBe(
'SELECT field1 FROM table foo GROUP BY field1 HAVING (field1 = value1) AND (field2 = value2)'
);
});
it('orHaving', function (): void {
$query = $this->dbalQueryBuilderAdapterTest
->select('field1')
->from('table', 'foo')
->groupBy('field1')
->having('field1 = value1')
->orHaving('field2 = value2')
->getQuery();
expect($query)->toBeString()->toBe(
'SELECT field1 FROM table foo GROUP BY field1 HAVING (field1 = value1) OR (field2 = value2)'
);
});
it('orderBy with order', function (): void {
$query = $this->dbalQueryBuilderAdapterTest
->select('field1')
->from('table', 'foo')
->orderBy('field1', 'DESC')
->getQuery();
expect($query)->toBeString()->toBe('SELECT field1 FROM table foo ORDER BY field1 DESC');
});
it('orderBy without order', function (): void {
$query = $this->dbalQueryBuilderAdapterTest
->select('field1')
->from('table', 'foo')
->orderBy('field1')
->getQuery();
expect($query)->toBeString()->toBe('SELECT field1 FROM table foo ORDER BY field1');
});
it('addOrderBy with order', function (): void {
$query = $this->dbalQueryBuilderAdapterTest
->select('field1')
->from('table', 'foo')
->orderBy('field1', 'DESC')
->addOrderBy('field2', 'ASC')
->getQuery();
expect($query)->toBeString()->toBe('SELECT field1 FROM table foo ORDER BY field1 DESC, field2 ASC');
});
it('addOrderBy without order', function (): void {
$query = $this->dbalQueryBuilderAdapterTest
->select('field1')
->from('table', 'foo')
->orderBy('field1')
->addOrderBy('field2')
->getQuery();
expect($query)->toBeString()->toBe('SELECT field1 FROM table foo ORDER BY field1, field2');
});
it('limit', function (): void {
$query = $this->dbalQueryBuilderAdapterTest
->select('field1')
->from('table', 'foo')
->orderBy('field1')
->limit(10)
->getQuery();
expect($query)->toBeString()->toBe('SELECT field1 FROM table foo ORDER BY field1 LIMIT 10');
});
it('offset', function (): void {
$query = $this->dbalQueryBuilderAdapterTest
->select('field1')
->from('table', 'foo')
->orderBy('field1')
->limit(10)
->offset(5)
->getQuery();
expect($query)->toBeString()->toBe('SELECT field1 FROM table foo ORDER BY field1 LIMIT 10 OFFSET 5');
});
it('resetWhere', function (): void {
$query = $this->dbalQueryBuilderAdapterTest
->select('field1')
->from('table', 'foo')
->where('field1 = value1')
->getQuery();
expect($query)->toBeString()->toBe('SELECT field1 FROM table foo WHERE field1 = value1');
$query = $this->dbalQueryBuilderAdapterTest->resetWhere()->getQuery();
expect($query)->toBeString()->toBe('SELECT field1 FROM table foo');
});
it('resetGroupBy', function (): void {
$query = $this->dbalQueryBuilderAdapterTest
->select('field1')
->from('table', 'foo')
->where('field1 = value1')
->groupBy('field1')
->getQuery();
expect($query)->toBeString()->toBe('SELECT field1 FROM table foo WHERE field1 = value1 GROUP BY field1');
$query = $this->dbalQueryBuilderAdapterTest->resetGroupBy()->getQuery();
expect($query)->toBeString()->toBe('SELECT field1 FROM table foo WHERE field1 = value1');
});
it('resetHaving', function (): void {
$query = $this->dbalQueryBuilderAdapterTest
->select('field1')
->from('table', 'foo')
->groupBy('field1')
->having('field1 = value1')
->getQuery();
expect($query)->toBeString()->toBe('SELECT field1 FROM table foo GROUP BY field1 HAVING field1 = value1');
$query = $this->dbalQueryBuilderAdapterTest->resetHaving()->getQuery();
expect($query)->toBeString()->toBe('SELECT field1 FROM table foo GROUP BY field1');
});
it('resetOrderBy', function (): void {
$query = $this->dbalQueryBuilderAdapterTest
->select('field1')
->from('table', 'foo')
->orderBy('field1')
->getQuery();
expect($query)->toBeString()->toBe('SELECT field1 FROM table foo ORDER BY field1');
$query = $this->dbalQueryBuilderAdapterTest->resetOrderBy()->getQuery();
expect($query)->toBeString()->toBe('SELECT field1 FROM table foo');
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Adaptation/Database/Connection/Collection/QueryParametersTest.php | centreon/tests/php/Adaptation/Database/Connection/Collection/QueryParametersTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Adaptation\Database\Connection\Collection;
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Core\Common\Domain\Exception\CollectionException;
it('add a query parameter with a good type', function (): void {
$queryParameters = new QueryParameters();
$param = QueryParameter::string('name_string', 'value');
$queryParameters->add('name_string', $param);
expect($queryParameters->length())->toBe(1)
->and($queryParameters->get('name_string'))->toBe($param);
});
it('add a query parameter with a bad type', function (): void {
$param = new \stdClass();
$queryParameters = new QueryParameters();
$queryParameters->add('name', $param);
})->throws(CollectionException::class);
it('create with good type', function (): void {
$param = [
'name_string' => QueryParameter::string('name_string', 'value'),
'name_int' => QueryParameter::int('name_int', 1),
];
$queryParameters = QueryParameters::create($param);
expect($queryParameters->length())->toBe(2)
->and($queryParameters->get('name_string'))->toBe($param['name_string'])
->and($queryParameters->get('name_int'))->toBe($param['name_int']);
});
it('create with bad type', function (): void {
$param = [
'name_string' => QueryParameter::string('name_string', 'value'),
'name_int' => new \stdClass(),
];
QueryParameters::create($param);
})->throws(CollectionException::class);
it('get query parameters with int type', function (): void {
$param = [
'name_string' => QueryParameter::string('name_string', 'value'),
'name_int' => QueryParameter::int('name_int', 1),
'name_null' => QueryParameter::null('name_null'),
'name_bool' => QueryParameter::bool('name_bool', true),
'name_large_object' => QueryParameter::largeObject(
'name_large_object',
'hjghjgjhgkhjgkhghgh7d8f7sdf7sdf7sd7fds'
),
];
$queryParameters = QueryParameters::create($param);
expect($queryParameters->getIntQueryParameters()->length())->toBe(1)
->and($queryParameters->getIntQueryParameters()->has('name_int'))->toBeTrue();
});
it('get query parameters with string type', function (): void {
$param = [
'name_string' => QueryParameter::string('name_string', 'value'),
'name_int' => QueryParameter::int('name_int', 1),
'name_null' => QueryParameter::null('name_null'),
'name_bool' => QueryParameter::bool('name_bool', true),
'name_large_object' => QueryParameter::largeObject(
'name_large_object',
'hjghjgjhgkhjgkhghgh7d8f7sdf7sdf7sd7fds'
),
];
$queryParameters = QueryParameters::create($param);
expect($queryParameters->getStringQueryParameters()->length())->toBe(1)
->and($queryParameters->getStringQueryParameters()->has('name_string'))->toBeTrue();
});
it('get query parameters with bool type', function (): void {
$param = [
'name_string' => QueryParameter::string('name_string', 'value'),
'name_int' => QueryParameter::int('name_int', 1),
'name_null' => QueryParameter::null('name_null'),
'name_bool' => QueryParameter::bool('name_bool', true),
'name_large_object' => QueryParameter::largeObject(
'name_large_object',
'hjghjgjhgkhjgkhghgh7d8f7sdf7sdf7sd7fds'
),
];
$queryParameters = QueryParameters::create($param);
expect($queryParameters->getBoolQueryParameters()->length())->toBe(1)
->and($queryParameters->getBoolQueryParameters()->has('name_bool'))->toBeTrue();
});
it('get query parameters with null type', function (): void {
$param = [
'name_string' => QueryParameter::string('name_string', 'value'),
'name_int' => QueryParameter::int('name_int', 1),
'name_null' => QueryParameter::null('name_null'),
'name_bool' => QueryParameter::bool('name_bool', true),
'name_large_object' => QueryParameter::largeObject(
'name_large_object',
'hjghjgjhgkhjgkhghgh7d8f7sdf7sdf7sd7fds'
),
];
$queryParameters = QueryParameters::create($param);
expect($queryParameters->getNullQueryParameters()->length())->toBe(1)
->and($queryParameters->getNullQueryParameters()->has('name_null'))->toBeTrue();
});
it('get query parameters with large object type', function (): void {
$param = [
'name_string' => QueryParameter::string('name_string', 'value'),
'name_int' => QueryParameter::int('name_int', 1),
'name_null' => QueryParameter::null('name_null'),
'name_bool' => QueryParameter::bool('name_bool', true),
'name_large_object' => QueryParameter::largeObject(
'name_large_object',
'hjghjgjhgkhjgkhghgh7d8f7sdf7sdf7sd7fds'
),
];
$queryParameters = QueryParameters::create($param);
expect($queryParameters->getLargeObjectQueryParameters()->length())->toBe(1)
->and($queryParameters->getLargeObjectQueryParameters()->has('name_large_object'))->toBeTrue();
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Adaptation/Database/Connection/Collection/BatchInsertParametersTest.php | centreon/tests/php/Adaptation/Database/Connection/Collection/BatchInsertParametersTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Adaptation\Database\Connection\Collection;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Core\Common\Domain\Exception\CollectionException;
it('add a query parameters with a good type', function (): void {
$queryParameters = new \Adaptation\Database\Connection\Collection\BatchInsertParameters();
$batchInsertParam1 = \Adaptation\Database\Connection\Collection\QueryParameters::create([
QueryParameter::int('contact_id', 110),
QueryParameter::string('contact_name', 'foo_name'),
QueryParameter::string('contact_alias', 'foo_alias'),
]);
$queryParameters->add('batch_insert_param_1', $batchInsertParam1);
expect($queryParameters->length())->toBe(1)
->and($queryParameters->get('batch_insert_param_1'))->toBe($batchInsertParam1);
});
it('add a query parameters with a bad type', function (): void {
$queryParameters = new \Adaptation\Database\Connection\Collection\BatchInsertParameters();
$queryParameters->add('batch_insert_param_1', new \stdClass());
})->throws(CollectionException::class);
it('create with good type', function (): void {
$batchInsertParam1 = \Adaptation\Database\Connection\Collection\QueryParameters::create([
QueryParameter::int('contact_id', 110),
QueryParameter::string('contact_name', 'foo_name'),
QueryParameter::string('contact_alias', 'foo_alias'),
]);
$batchInsertParam2 = \Adaptation\Database\Connection\Collection\QueryParameters::create([
QueryParameter::int('contact_id', 111),
QueryParameter::string('contact_name', 'bar_name'),
QueryParameter::string('contact_alias', 'bar_alias'),
]);
$batchInsertParam3 = \Adaptation\Database\Connection\Collection\QueryParameters::create([
QueryParameter::int('contact_id', 112),
QueryParameter::string('contact_name', 'baz_name'),
QueryParameter::string('contact_alias', 'baz_alias'),
]);
$batchQueryParameters = \Adaptation\Database\Connection\Collection\BatchInsertParameters::create([
'batch_insert_param_1' => $batchInsertParam1,
'batch_insert_param_2' => $batchInsertParam2,
'batch_insert_param_3' => $batchInsertParam3,
]);
expect($batchQueryParameters->length())->toBe(3)
->and($batchQueryParameters->get('batch_insert_param_1'))->toBe($batchInsertParam1)
->and($batchQueryParameters->get('batch_insert_param_2'))->toBe($batchInsertParam2)
->and($batchQueryParameters->get('batch_insert_param_3'))->toBe($batchInsertParam3);
});
it('create with bad type', function (): void {
\Adaptation\Database\Connection\Collection\BatchInsertParameters::create([
new \stdClass(),
new \stdClass(),
new \stdClass(),
]);
})->throws(CollectionException::class);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Adaptation/Database/Connection/ValueObject/QueryParameterTest.php | centreon/tests/php/Adaptation/Database/Connection/ValueObject/QueryParameterTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Adaptation\Database\Connection\ValueObject;
use Adaptation\Database\Connection\Enum\QueryParameterTypeEnum;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Core\Common\Domain\Exception\ValueObjectException;
it('success instanciation with create (with type)', function (): void {
$param = QueryParameter::create('name', 'value', QueryParameterTypeEnum::STRING);
expect($param->getName())->toBe('name')
->and($param->getValue())->toBe('value')
->and($param->getType())->toBe(QueryParameterTypeEnum::STRING);
});
it('failed instanciation with create (with no type)', function (): void {
$param = QueryParameter::create('name', 'value');
expect($param->getName())->toBe('name')
->and($param->getValue())->toBe('value')
->and($param->getType())->toBeNull();
});
it('failed instanciation with create (empty name) ', function (): void {
QueryParameter::create('', 'value');
})->throws(ValueObjectException::class);
it('failed instanciation with create (bad type for string) ', function (): void {
QueryParameter::create('name', new \stdClass());
})->throws(ValueObjectException::class);
it('failed instanciation with create (bad type for large object) ', function (): void {
QueryParameter::create('name', 0, QueryParameterTypeEnum::LARGE_OBJECT);
})->throws(ValueObjectException::class);
it('success instanciation with string type', function (): void {
$param = QueryParameter::string('name', 'value');
expect($param->getName())->toBe('name')
->and($param->getValue())->toBe('value')
->and($param->getType())->toBe(QueryParameterTypeEnum::STRING);
$param = QueryParameter::string('age', '25');
expect($param->getName())->toBe('age')
->and($param->getValue())->toBe('25')
->and($param->getType())->toBe(QueryParameterTypeEnum::STRING);
$param = QueryParameter::string('active', 'false');
expect($param->getName())->toBe('active')
->and($param->getValue())->toBe('false')
->and($param->getType())->toBe(QueryParameterTypeEnum::STRING);
$param = QueryParameter::string('price', '9.99');
expect($param->getName())->toBe('price')
->and($param->getValue())->toBe('9.99')
->and($param->getType())->toBe(QueryParameterTypeEnum::STRING);
});
it('failed instanciation with string type (empty name) ', function (): void {
QueryParameter::string('', 'value');
})->throws(ValueObjectException::class);
it('failed instanciation with string type (bad value) ', function (): void {
QueryParameter::string('name', 0);
})->throws(\TypeError::class);
it('success instanciation with int type', function (): void {
$param = QueryParameter::int('name', 1);
expect($param->getName())->toBe('name')
->and($param->getValue())->toBe(1)
->and($param->getType())->toBe(QueryParameterTypeEnum::INTEGER);
});
it('failed instanciation with int type (empty name) ', function (): void {
QueryParameter::int('', 1);
})->throws(ValueObjectException::class);
it('failed instanciation with int type (bad value) ', function (): void {
QueryParameter::int('name', 'value');
})->throws(\TypeError::class);
it('success instanciation with bool type', function (): void {
$param = QueryParameter::bool('name', true);
expect($param->getName())->toBe('name')
->and($param->getValue())->toBe(true)
->and($param->getType())->toBe(QueryParameterTypeEnum::BOOLEAN);
});
it('failed instanciation with bool type (empty name) ', function (): void {
QueryParameter::bool('', true);
})->throws(ValueObjectException::class);
it('failed instanciation with bool type (bad value) ', function (): void {
QueryParameter::bool('name', 1);
})->throws(\TypeError::class);
it('success instanciation with null type', function (): void {
$param = QueryParameter::null('name');
expect($param->getName())->toBe('name')
->and($param->getValue())->toBeNull()
->and($param->getType())->toBe(QueryParameterTypeEnum::NULL);
});
it('failed instanciation with null type (empty name) ', function (): void {
QueryParameter::null('');
})->throws(ValueObjectException::class);
it('success instanciation with large object type', function (): void {
$param = QueryParameter::largeObject('name', 'value');
expect($param->getName())->toBe('name')
->and($param->getValue())->toBe('value')
->and($param->getType())->toBe(QueryParameterTypeEnum::LARGE_OBJECT);
});
it('failed instanciation with large object type (empty name) ', function (): void {
QueryParameter::largeObject('', 'value');
})->throws(ValueObjectException::class);
it('failed instanciation with large object type (bad value) ', function (): void {
QueryParameter::largeObject('name', 1);
})->throws(ValueObjectException::class);
it('json serialize', function (): void {
$param = QueryParameter::string('name', 'value');
expect($param->jsonSerialize())->toBe(
[
'name' => 'name',
'value' => 'value',
'type' => QueryParameterTypeEnum::STRING,
]
);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Adaptation/Database/Connection/Adapter/Pdo/Transformer/PdoParameterTypeTransformerTest.php | centreon/tests/php/Adaptation/Database/Connection/Adapter/Pdo/Transformer/PdoParameterTypeTransformerTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Adaptation\Database\Connection\Adapter\Pdo\Transformer;
use Adaptation\Database\Connection\Adapter\Pdo\Transformer\PdoParameterTypeTransformer;
use Adaptation\Database\Connection\Enum\QueryParameterTypeEnum;
use Core\Common\Domain\Exception\TransformerException;
it('transform from query parameters', function (QueryParameterTypeEnum $queryType, int $pdoType): void {
$type = PdoParameterTypeTransformer::transformFromQueryParameterType($queryType);
expect($type)->toBeInt()->toBe($pdoType);
})->with([
[QueryParameterTypeEnum::STRING, \PDO::PARAM_STR],
[QueryParameterTypeEnum::INTEGER, \PDO::PARAM_INT],
[QueryParameterTypeEnum::LARGE_OBJECT, \PDO::PARAM_LOB],
[QueryParameterTypeEnum::NULL, \PDO::PARAM_NULL],
[QueryParameterTypeEnum::BOOLEAN, \PDO::PARAM_BOOL],
]);
it('reverse to query parameters', function (int $pdoType, QueryParameterTypeEnum $queryType): void {
$type = PdoParameterTypeTransformer::reverseToQueryParameterType($pdoType);
expect($type)->toBe($queryType);
})->with([
[\PDO::PARAM_STR, QueryParameterTypeEnum::STRING],
[\PDO::PARAM_INT, QueryParameterTypeEnum::INTEGER],
[\PDO::PARAM_LOB, QueryParameterTypeEnum::LARGE_OBJECT],
[\PDO::PARAM_NULL, QueryParameterTypeEnum::NULL],
[\PDO::PARAM_BOOL, QueryParameterTypeEnum::BOOLEAN],
]);
it('reverse to query parameters with a bad pdo type', function (): void {
$type = PdoParameterTypeTransformer::reverseToQueryParameterType(999999);
})->throws(TransformerException::class);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Adaptation/Database/Connection/Adapter/Dbal/DbalConnectionAdapterTest.php | centreon/tests/php/Adaptation/Database/Connection/Adapter/Dbal/DbalConnectionAdapterTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Adaptation\Database\Connection\Adapter\Dbal;
use Adaptation\Database\Connection\Adapter\Dbal\DbalConnectionAdapter;
use Adaptation\Database\Connection\Collection\BatchInsertParameters;
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Adaptation\Database\Connection\Model\ConnectionConfig;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Adaptation\Database\ExpressionBuilder\Adapter\Dbal\DbalExpressionBuilderAdapter;
use Adaptation\Database\ExpressionBuilder\ExpressionBuilderInterface;
use Adaptation\Database\QueryBuilder\Adapter\Dbal\DbalQueryBuilderAdapter;
use Adaptation\Database\QueryBuilder\QueryBuilderInterface;
function getEnvironmentVariable(string $nameEnvVar): ?string
{
$envVarValue = getenv($nameEnvVar, true) ?: getenv($nameEnvVar);
return (is_string($envVarValue) && ! empty($envVarValue)) ? $envVarValue : null;
}
$dbHost = getEnvironmentVariable('MYSQL_HOST');
$dbUser = getEnvironmentVariable('MYSQL_USER');
$dbPassword = getEnvironmentVariable('MYSQL_PASSWORD');
$dbConfigCentreon = null;
if ($dbHost !== null && $dbUser !== null && $dbPassword !== null) {
$dbConfigCentreon = new ConnectionConfig(
host: $dbHost,
user: $dbUser,
password: $dbPassword,
databaseNameConfiguration: 'centreon',
databaseNameRealTime: 'centreon_storage',
port: 3306
);
}
function hasConnectionDb(ConnectionConfig $connectionConfig): bool
{
try {
new \PDO(
$connectionConfig->getMysqlDsn(),
$connectionConfig->getUser(),
$connectionConfig->getPassword(),
[\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION]
);
return true;
} catch (\PDOException) {
return false;
}
}
// ************************************** With centreon database connection *******************************************
if ($dbConfigCentreon instanceof ConnectionConfig && hasConnectionDb($dbConfigCentreon)) {
it(
'DbalConnectionAdapter::createFromConfig factory with a good connection',
function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
/** @var \PDO $pdo */
$pdo = $db->getNativeConnection();
expect($db)->toBeInstanceOf(DbalConnectionAdapter::class);
$stmt = $pdo->prepare('select database()');
$stmt->execute();
$dbName = $stmt->fetchColumn();
expect($dbName)->toBe('centreon')
->and($pdo->getAttribute(\PDO::ATTR_STATEMENT_CLASS)[0])->toBe(\PDOStatement::class);
}
);
it(
'DbalConnectionAdapter::createFromConfig factory with a bad connection',
function () use ($dbHost, $dbUser, $dbPassword): void {
$dbConfigCentreon = new ConnectionConfig(
host: $dbHost,
user: $dbUser,
password: $dbPassword,
databaseNameConfiguration: 'bad_connection',
databaseNameRealTime: 'bad_connection_storage',
port: 3306
);
DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
}
)->throws(ConnectionException::class);
it(
'create query builder with success',
function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$queryBuilder = $db->createQueryBuilder();
expect($queryBuilder)
->toBeInstanceOf(QueryBuilderInterface::class)
->toBeInstanceOf(DbalQueryBuilderAdapter::class);
}
);
it(
'create expression builder with success',
function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$expressionBuilder = $db->createExpressionBuilder();
expect($expressionBuilder)
->toBeInstanceOf(ExpressionBuilderInterface::class)
->toBeInstanceOf(DbalExpressionBuilderAdapter::class);
}
);
it(
'get connection config',
function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$connectionConfig = $db->getConnectionConfig();
expect($connectionConfig)->toBeInstanceOf(ConnectionConfig::class)
->and($connectionConfig->getHost())->toBe($dbConfigCentreon->getHost())
->and($connectionConfig->getUser())->toBe($dbConfigCentreon->getUser())
->and($connectionConfig->getPassword())->toBe($dbConfigCentreon->getPassword())
->and($connectionConfig->getDatabaseNameConfiguration())->toBe($dbConfigCentreon->getDatabaseNameConfiguration())
->and($connectionConfig->getPort())->toBe($dbConfigCentreon->getPort());
}
);
it(
'get the database name of the current connection',
function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$dbName = $db->getDatabaseName();
expect($dbName)->toBe('centreon');
}
);
it('get native connection', function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
/** @var \PDO $pdo */
$pdo = $db->getNativeConnection();
expect($pdo)->toBeInstanceOf(\PDO::class);
});
it('get last insert id', function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
/** @var \PDO $pdo */
$pdo = $db->getNativeConnection();
$insert = $pdo->exec(
"INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(110, 'foo_name', 'foo_alias')"
);
expect($insert)->toBeInt()->toBe(1);
$lastInsertId = $db->getLastInsertId();
expect($lastInsertId)->toBeString()->toBe('110');
// clean up the database
$delete = $pdo->exec('DELETE FROM contact WHERE contact_id = 110');
expect($delete)->toBeInt()->toBe(1);
});
it('is connected', function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
expect($db->isConnected())->toBeTrue();
});
it('quote string', function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
/** @var \PDO $pdo */
$pdo = $db->getNativeConnection();
$quotedString = $pdo->quote('foo');
expect($quotedString)->toBeString()->toBe("'foo'");
});
// --------------------------------------- CUD METHODS -----------------------------------------
// -- executeStatement()
it(
'execute statement with a correct query without query parameters',
function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
/** @var \PDO $pdo */
$pdo = $db->getNativeConnection();
$inserted = $db->executeStatement(
"INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(110, 'foo_name', 'foo_alias')"
);
expect($inserted)->toBeInt()->toBe(1);
// clean up the database
$deleted = $pdo->exec('DELETE FROM contact WHERE contact_id = 110');
expect($deleted)->toBeInt()->toBe(1);
}
);
it(
'execute statement with a correct query with query parameters',
function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
/** @var \PDO $pdo */
$pdo = $db->getNativeConnection();
$queryParameters = QueryParameters::create(
[
QueryParameter::int('id', 110),
QueryParameter::string('name', 'foo_name'),
QueryParameter::string('alias', 'foo_alias'),
]
);
$inserted = $db->executeStatement(
'INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(:id, :name, :alias)',
$queryParameters
);
expect($inserted)->toBeInt()->toBe(1);
// clean up the database
$deleted = $pdo->exec('DELETE FROM contact WHERE contact_id = 110');
expect($deleted)->toBeInt()->toBe(1);
}
);
it(
'execute statement with a correct query with query parameters with ":" before keys',
function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
/** @var \PDO $pdo */
$pdo = $db->getNativeConnection();
$queryParameters = QueryParameters::create(
[
QueryParameter::int(':id', 110),
QueryParameter::string(':name', 'foo_name'),
QueryParameter::string(':alias', 'foo_alias'),
]
);
$inserted = $db->executeStatement(
'INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(:id, :name, :alias)',
$queryParameters
);
expect($inserted)->toBeInt()->toBe(1);
// clean up the database
$deleted = $pdo->exec('DELETE FROM contact WHERE contact_id = 110');
expect($deleted)->toBeInt()->toBe(1);
}
);
it('execute statement with a SELECT query', function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->executeStatement('SELECT * FROM contact');
})->throws(ConnectionException::class);
it('execute statement with an empty query', function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->executeStatement('');
})->throws(ConnectionException::class);
it(
'execute statement with an incorrect query',
function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->executeStatement('foo');
}
)->throws(ConnectionException::class);
it(
'execute statement with an incorrect query parameters',
function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$queryParameters = QueryParameters::create(
[
QueryParameter::int('id', 110),
QueryParameter::string('name', 'foo_name'),
]
);
$db->executeStatement(
'INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(:id, :name, :alias)',
$queryParameters
);
}
)->throws(ConnectionException::class);
// -- insert()
it(
'insert with a correct query with query parameters',
function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
/** @var \PDO $pdo */
$pdo = $db->getNativeConnection();
$queryParameters = QueryParameters::create(
[
QueryParameter::int('id', 110),
QueryParameter::string('name', 'foo_name'),
QueryParameter::string('alias', 'foo_alias'),
]
);
$inserted = $db->insert(
'INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(:id, :name, :alias)',
$queryParameters
);
expect($inserted)->toBeInt()->toBe(1);
// clean up the database
$deleted = $pdo->exec('DELETE FROM contact WHERE contact_id = 110');
expect($deleted)->toBeInt()->toBe(1);
}
);
it('insert with a SELECT query', function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->insert(
'SELECT * FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('contact_id', 110)])
);
})->throws(ConnectionException::class);
it('insert with an empty query', function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->insert('', QueryParameters::create([QueryParameter::int('contact_id', 110)]));
})->throws(ConnectionException::class);
it('insert with an incorrect query', function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->insert('foo', QueryParameters::create([QueryParameter::int('contact_id', 110)]));
})->throws(ConnectionException::class);
it(
'insert with an incorrect query parameters',
function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$queryParameters = QueryParameters::create(
[
QueryParameter::int('id', 110),
QueryParameter::string('name', 'foo_name'),
]
);
$db->insert(
'INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(:id, :name, :alias)',
$queryParameters
);
}
)->throws(ConnectionException::class);
// -- batchInsert()
it(
'batch insert with a correct query with batch query parameters',
function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
/** @var \PDO $pdo */
$pdo = $db->getNativeConnection();
$batchQueryParameters = BatchInsertParameters::create([
QueryParameters::create([
QueryParameter::int('contact_id', 110),
QueryParameter::string('contact_name', 'foo_name'),
QueryParameter::string('contact_alias', 'foo_alias'),
]),
QueryParameters::create([
QueryParameter::int('contact_id', 111),
QueryParameter::string('contact_name', 'bar_name'),
QueryParameter::string('contact_alias', 'bar_alias'),
]),
QueryParameters::create([
QueryParameter::int('contact_id', 112),
QueryParameter::string('contact_name', 'baz_name'),
QueryParameter::string('contact_alias', 'baz_alias'),
]),
]);
$inserted = $db->batchInsert(
'contact',
['contact_id', 'contact_name', 'contact_alias'],
$batchQueryParameters
);
expect($inserted)->toBeInt()->toBe(3);
// clean up the database
$deleted = $pdo->exec('DELETE FROM contact WHERE contact_id IN (110,111,112)');
expect($deleted)->toBeInt()->toBe(3);
}
);
it(
'batch insert with a correct query with empty batch query parameters',
function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->batchInsert(
'contact',
['contact_id', 'contact_name', 'contact_alias'],
BatchInsertParameters::create([])
);
}
)->throws(ConnectionException::class);
it(
'batch insert with an incorrect batch query parameters',
function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$batchQueryParameters = BatchInsertParameters::create([
QueryParameters::create([
QueryParameter::int('contact_id', 110),
QueryParameter::string('contact_name', 'foo_name'),
]),
QueryParameters::create([
QueryParameter::int('contact_id', 111),
QueryParameter::string('contact_name', 'bar_name'),
]),
QueryParameters::create([
QueryParameter::int('contact_id', 112),
QueryParameter::string('contact_name', 'baz_name'),
]),
]);
$db->batchInsert(
'contact',
['contact_id', 'contact_name', 'contact_alias'],
$batchQueryParameters
);
}
)->throws(ConnectionException::class);
// -- update()
it(
'update with a correct query with query parameters',
function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
/** @var \PDO $pdo */
$pdo = $db->getNativeConnection();
$inserted = $db->executeStatement(
"INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(110, 'foo_name', 'foo_alias')"
);
expect($inserted)->toBeInt()->toBe(1);
$queryParameters = QueryParameters::create(
[
QueryParameter::string('name', 'bar_name'),
QueryParameter::string('alias', 'bar_alias'),
QueryParameter::int('id', 110),
]
);
$updated = $db->update(
'UPDATE contact SET contact_name = :name, contact_alias = :alias WHERE contact_id = :id',
$queryParameters
);
expect($updated)->toBeInt()->toBe(1);
// clean up the database
$delete = $pdo->exec('DELETE FROM contact WHERE contact_id = 110');
expect($delete)->toBeInt()->toBe(1);
}
);
it('update with a SELECT query', function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->update(
'SELECT * FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('contact_id', 110)])
);
})->throws(ConnectionException::class);
it('update with an empty query', function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->update('', QueryParameters::create([QueryParameter::int('contact_id', 110)]));
})->throws(ConnectionException::class);
it('update with an incorrect query', function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->update('foo', QueryParameters::create([QueryParameter::int('contact_id', 110)]));
})->throws(ConnectionException::class);
it(
'update with an incorrect query parameters',
function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$queryParameters = QueryParameters::create(
[
QueryParameter::string('name', 'bar_name'),
QueryParameter::string('alias', 'bar_alias'),
]
);
$db->update(
'UPDATE contact SET contact_name = :name, contact_alias = :alias WHERE contact_id = :id',
$queryParameters
);
}
)->throws(ConnectionException::class);
// -- delete()
it(
'delete with a correct query with query parameters',
function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$inserted = $db->executeStatement(
"INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(110, 'foo_name', 'foo_alias')"
);
expect($inserted)->toBeInt()->toBe(1);
$queryParameters = QueryParameters::create([QueryParameter::int('id', 110)]);
$deleted = $db->delete('DELETE FROM contact WHERE contact_id = :id', $queryParameters);
expect($deleted)->toBeInt()->toBe(1);
}
);
it('delete with a SELECT query', function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->delete(
'SELECT * FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('contact_id', 110)])
);
})->throws(ConnectionException::class);
it('delete with an empty query', function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->delete('', QueryParameters::create([QueryParameter::int('contact_id', 110)]));
})->throws(ConnectionException::class);
it('delete with an incorrect query', function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->delete('foo', QueryParameters::create([QueryParameter::int('contact_id', 110)]));
})->throws(ConnectionException::class);
it(
'delete with an incorrect query parameters',
function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$queryParameters = QueryParameters::create(
[
QueryParameter::string('name', 'foo_name'),
QueryParameter::string('alias', 'foo_alias'),
]
);
$db->delete(
'DELETE FROM contact WHERE contact_id = :id AND contact_name = :name AND contact_alias = :alias',
$queryParameters
);
}
)->throws(ConnectionException::class);
// ---------------------------------------- FETCH METHODS ----------------------------------------------
// -- fetchNumeric()
it(
'fetchNumeric with a correct query with query parameters',
function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$contact = $db->fetchNumeric(
'SELECT * FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('id', 1)])
);
expect($contact)->toBeArray()
->and($contact[0])->toBe(1);
}
);
it('fetchNumeric with a correct query with query parameters with ":" before keys', function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$contact = $db->fetchNumeric(
'SELECT * FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int(':id', 1)])
);
expect($contact)->toBeArray()
->and($contact[0])->toBe(1);
});
it('fetchNumeric with a CUD query', function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->fetchNumeric(
'DELETE FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('id', 1)])
);
})->throws(ConnectionException::class);
it('fetchNumeric with an empty query', function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->fetchNumeric('', QueryParameters::create([QueryParameter::int('id', 1)]));
})->throws(ConnectionException::class);
it('fetchNumeric with an incorrect query', function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->fetchNumeric('foo', QueryParameters::create([QueryParameter::int('id', 1)]));
})->throws(ConnectionException::class);
it(
'fetchNumeric with an incorrect query parameters',
function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->fetchNumeric(
'SELECT * FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::string('name', 'foo_name')])
);
}
)->throws(ConnectionException::class);
// -- fetchAssociative()
it(
'fetchAssociative with a correct query with query parameters',
function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$contact = $db->fetchAssociative(
'SELECT * FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('id', 1)])
);
expect($contact)->toBeArray()
->and($contact['contact_id'])->toBe(1);
}
);
it('fetchAssociative with a correct query with query parameters with ":" before keys', function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$contact = $db->fetchAssociative(
'SELECT * FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int(':id', 1)])
);
expect($contact)->toBeArray()
->and($contact['contact_id'])->toBe(1);
});
it('fetchAssociative with a CUD query', function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->fetchAssociative(
'DELETE FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('id', 1)])
);
})->throws(ConnectionException::class);
it('fetchAssociative with an empty query', function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->fetchAssociative('', QueryParameters::create([QueryParameter::int('id', 1)]));
})->throws(ConnectionException::class);
it(
'fetchAssociative with an incorrect query',
function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->fetchAssociative('foo', QueryParameters::create([QueryParameter::int('id', 1)]));
}
)->throws(ConnectionException::class);
it(
'fetchAssociative with an incorrect query parameters',
function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->fetchAssociative(
'SELECT * FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::string('name', 'foo_name')])
);
}
)->throws(ConnectionException::class);
// -- fetchOne()
it(
'fetchOne with a correct query with query parameters',
function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$alias = $db->fetchOne(
'SELECT contact_alias FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('id', 1)])
);
expect($alias)->toBeString()->toBe('admin');
}
);
it('fetchOne with a correct query with query parameters with ":" before keys', function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$alias = $db->fetchOne(
'SELECT contact_alias FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int(':id', 1)])
);
expect($alias)->toBeString()->toBe('admin');
});
it('fetchOne with a CUD query', function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->fetchOne(
'DELETE FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('id', 1)])
);
})->throws(ConnectionException::class);
it('fetchOne with an empty query', function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->fetchOne('', QueryParameters::create([QueryParameter::int('id', 1)]));
})->throws(ConnectionException::class);
it('fetchOne with an incorrect query', function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->fetchOne('foo', QueryParameters::create([QueryParameter::int('id', 1)]));
})->throws(ConnectionException::class);
it(
'fetchOne with an incorrect query parameters',
function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->fetchOne(
'SELECT contact_alias FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::string('name', 'foo_name')])
);
}
)->throws(ConnectionException::class);
// -- fetchFirstColumn()
it(
'fetchFirstColumn with a correct query with query parameters',
function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$contact = $db->fetchFirstColumn(
'SELECT contact_id FROM contact ORDER BY :id',
QueryParameters::create([QueryParameter::int('id', 1)])
);
expect($contact)->toBeArray()
->and($contact[0])->toBeInt()->toBe(1);
}
);
it('fetchFirstColumn with a correct query with query parameters with ":" before keys', function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$contact = $db->fetchFirstColumn(
'SELECT contact_id FROM contact ORDER BY :id',
QueryParameters::create([QueryParameter::int(':id', 1)])
);
expect($contact)->toBeArray()
->and($contact[0])->toBeInt()->toBe(1);
});
it(
'fetchFirstColumn with a correct query with query parameters and another column',
function () use ($dbConfigCentreon): void {
$db = DbalConnectionAdapter::createFromConfig(connectionConfig: $dbConfigCentreon);
$contact = $db->fetchFirstColumn('SELECT contact_alias FROM contact ORDER BY contact_id');
expect($contact)->toBeArray()
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Adaptation/Database/Connection/Adapter/Dbal/Transformer/DbalParameterTypeTransformerTest.php | centreon/tests/php/Adaptation/Database/Connection/Adapter/Dbal/Transformer/DbalParameterTypeTransformerTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Adaptation\Database\Connection\Adapter\Dbal\Transformer;
use Adaptation\Database\Connection\Adapter\Dbal\Transformer\DbalParameterTypeTransformer;
use Adaptation\Database\Connection\Enum\QueryParameterTypeEnum;
use Core\Common\Domain\Exception\TransformerException;
use Doctrine\DBAL\ParameterType;
use Doctrine\DBAL\ParameterType as DbalParameterType;
it('transform from query parameter type', function (): void {
$queryParameterTypeEnum = QueryParameterTypeEnum::STRING;
$dbalParameterType = DbalParameterTypeTransformer::transformFromQueryParameterType($queryParameterTypeEnum);
expect($dbalParameterType)->toBe(DbalParameterType::STRING);
$queryParameterTypeEnum = QueryParameterTypeEnum::INTEGER;
$dbalParameterType = DbalParameterTypeTransformer::transformFromQueryParameterType($queryParameterTypeEnum);
expect($dbalParameterType)->toBe(DbalParameterType::INTEGER);
$queryParameterTypeEnum = QueryParameterTypeEnum::BOOLEAN;
$dbalParameterType = DbalParameterTypeTransformer::transformFromQueryParameterType($queryParameterTypeEnum);
expect($dbalParameterType)->toBe(DbalParameterType::BOOLEAN);
$queryParameterTypeEnum = QueryParameterTypeEnum::NULL;
$dbalParameterType = DbalParameterTypeTransformer::transformFromQueryParameterType($queryParameterTypeEnum);
expect($dbalParameterType)->toBe(DbalParameterType::NULL);
$queryParameterTypeEnum = QueryParameterTypeEnum::LARGE_OBJECT;
$dbalParameterType = DbalParameterTypeTransformer::transformFromQueryParameterType($queryParameterTypeEnum);
expect($dbalParameterType)->toBe(DbalParameterType::LARGE_OBJECT);
});
it('reverse to query parameter type', function (): void {
$dbalParameterType = DbalParameterType::STRING;
$queryParameterTypeEnum = DbalParameterTypeTransformer::reverseToQueryParameterType($dbalParameterType);
expect($queryParameterTypeEnum)->toBe(QueryParameterTypeEnum::STRING);
$dbalParameterType = DbalParameterType::INTEGER;
$queryParameterTypeEnum = DbalParameterTypeTransformer::reverseToQueryParameterType($dbalParameterType);
expect($queryParameterTypeEnum)->toBe(QueryParameterTypeEnum::INTEGER);
$dbalParameterType = DbalParameterType::BOOLEAN;
$queryParameterTypeEnum = DbalParameterTypeTransformer::reverseToQueryParameterType($dbalParameterType);
expect($queryParameterTypeEnum)->toBe(QueryParameterTypeEnum::BOOLEAN);
$dbalParameterType = DbalParameterType::NULL;
$queryParameterTypeEnum = DbalParameterTypeTransformer::reverseToQueryParameterType($dbalParameterType);
expect($queryParameterTypeEnum)->toBe(QueryParameterTypeEnum::NULL);
$dbalParameterType = DbalParameterType::LARGE_OBJECT;
$queryParameterTypeEnum = DbalParameterTypeTransformer::reverseToQueryParameterType($dbalParameterType);
expect($queryParameterTypeEnum)->toBe(QueryParameterTypeEnum::LARGE_OBJECT);
});
it('reverse to query parameter type with exception', function (): void {
DbalParameterTypeTransformer::reverseToQueryParameterType(ParameterType::ASCII);
})->throws(TransformerException::class);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Adaptation/Database/Connection/Adapter/Dbal/Transformer/DbalParametersTransformerTest.php | centreon/tests/php/Adaptation/Database/Connection/Adapter/Dbal/Transformer/DbalParametersTransformerTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Adaptation\Database\Connection\Adapter\Dbal\Transformer;
use Adaptation\Database\Connection\Adapter\Dbal\Transformer\DbalParametersTransformer;
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\Enum\QueryParameterTypeEnum;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Doctrine\DBAL\ParameterType as DbalParameterType;
it('transform from query parameters', function (): void {
[$params, $types] = DbalParametersTransformer::transformFromQueryParameters(
QueryParameters::create(
[
QueryParameter::create('host_id', 1, QueryParameterTypeEnum::INTEGER),
QueryParameter::create('host_name', 'foo_server', QueryParameterTypeEnum::STRING),
QueryParameter::create('host_enabled', true, QueryParameterTypeEnum::BOOLEAN),
QueryParameter::create('host_blob', 'fsfqsd4f5qsdff325154', QueryParameterTypeEnum::LARGE_OBJECT),
QueryParameter::create('host_null', null, QueryParameterTypeEnum::NULL),
]
)
);
expect($params)->toBeArray()->toBe(
[
'host_id' => 1,
'host_name' => 'foo_server',
'host_enabled' => true,
'host_blob' => 'fsfqsd4f5qsdff325154',
'host_null' => null,
]
)
->and($types)->toBeArray()->toBe(
[
'host_id' => DbalParameterType::INTEGER,
'host_name' => DbalParameterType::STRING,
'host_enabled' => DbalParameterType::BOOLEAN,
'host_blob' => DbalParameterType::LARGE_OBJECT,
'host_null' => DbalParameterType::NULL,
]
);
});
it('transform from query parameters with : before key', function (): void {
[$params, $types] = DbalParametersTransformer::transformFromQueryParameters(
QueryParameters::create(
[
QueryParameter::create(':host_id', 1, QueryParameterTypeEnum::INTEGER),
QueryParameter::create(':host_name', 'foo_server', QueryParameterTypeEnum::STRING),
QueryParameter::create(':host_enabled', true, QueryParameterTypeEnum::BOOLEAN),
QueryParameter::create(':host_blob', 'fsfqsd4f5qsdff325154', QueryParameterTypeEnum::LARGE_OBJECT),
QueryParameter::create(':host_null', null, QueryParameterTypeEnum::NULL),
]
)
);
expect($params)->toBeArray()->toBe(
[
'host_id' => 1,
'host_name' => 'foo_server',
'host_enabled' => true,
'host_blob' => 'fsfqsd4f5qsdff325154',
'host_null' => null,
]
)
->and($types)->toBeArray()->toBe(
[
'host_id' => DbalParameterType::INTEGER,
'host_name' => DbalParameterType::STRING,
'host_enabled' => DbalParameterType::BOOLEAN,
'host_blob' => DbalParameterType::LARGE_OBJECT,
'host_null' => DbalParameterType::NULL,
]
);
});
it('reverse to query parameters', function (): void {
$queryParameters = DbalParametersTransformer::reverseToQueryParameters(
[
'host_id' => 1,
'host_name' => 'foo_server',
'host_enabled' => true,
'host_blob' => 'fsfqsd4f5qsdff325154',
'host_null' => null,
],
[
'host_id' => DbalParameterType::INTEGER,
'host_name' => DbalParameterType::STRING,
'host_enabled' => DbalParameterType::BOOLEAN,
'host_blob' => DbalParameterType::LARGE_OBJECT,
'host_null' => DbalParameterType::NULL,
]
);
expect($queryParameters)->toBeInstanceOf(QueryParameters::class)
->and($queryParameters->toArray())->toBeArray()->toHaveKeys(
[
'host_id',
'host_name',
'host_enabled',
'host_blob',
'host_null',
]
)
->and($queryParameters->get('host_id'))->toBeInstanceOf(QueryParameter::class)
->and($queryParameters->get('host_id')->getName())->toBe('host_id')
->and($queryParameters->get('host_id')->getValue())->toBe(1)
->and($queryParameters->get('host_id')->getType())->toBe(QueryParameterTypeEnum::INTEGER)
->and($queryParameters->get('host_name'))->toBeInstanceOf(QueryParameter::class)
->and($queryParameters->get('host_name')->getName())->toBe('host_name')
->and($queryParameters->get('host_name')->getValue())->toBe('foo_server')
->and($queryParameters->get('host_name')->getType())->toBe(QueryParameterTypeEnum::STRING)
->and($queryParameters->get('host_enabled'))->toBeInstanceOf(QueryParameter::class)
->and($queryParameters->get('host_enabled')->getName())->toBe('host_enabled')
->and($queryParameters->get('host_enabled')->getValue())->toBe(true)
->and($queryParameters->get('host_enabled')->getType())->toBe(QueryParameterTypeEnum::BOOLEAN)
->and($queryParameters->get('host_blob'))->toBeInstanceOf(QueryParameter::class)
->and($queryParameters->get('host_blob')->getName())->toBe('host_blob')
->and($queryParameters->get('host_blob')->getValue())->toBe('fsfqsd4f5qsdff325154')
->and($queryParameters->get('host_blob')->getType())->toBe(QueryParameterTypeEnum::LARGE_OBJECT)
->and($queryParameters->get('host_null'))->toBeInstanceOf(QueryParameter::class)
->and($queryParameters->get('host_null')->getName())->toBe('host_null')
->and($queryParameters->get('host_null')->getValue())->toBeNull()
->and($queryParameters->get('host_null')->getType())->toBe(QueryParameterTypeEnum::NULL);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/mock/PEAR.php | centreon/tests/php/mock/PEAR.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Test\Mock;
/**
* Mock class for PEAR
*
* @author Centreon
* @version 1.0.0
* @package centreon-license-manager
* @subpackage test
*/
class PEAR
{
/**
* Test if it's a PEAR Error
*
* @param mixed $obj
* @return false It's in error
*/
public static function isError(mixed $obj): false
{
return false;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/mock/Centreon.php | centreon/tests/php/mock/Centreon.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Test\Mock;
/**
* Mock class for resultset
*
* @author Centreon
* @version 1.0.0
* @package centreon-license-manager
* @subpackage test
*/
class Centreon extends \Centreon
{
/** @var CentreonUser */
public $user;
/**
* Centreon constructor
*
* @param $userInfos
*/
public function __construct($userInfos = null)
{
$userInfos = [
'contact_id' => '1',
'contact_name' => 'John Doe',
'contact_alias' => 'johny',
'contact_email' => 'john.doe@mail.loc',
'contact_lang' => 'en',
'contact_passwd' => '123',
'contact_autologin_key' => '123',
'contact_admin' => '1',
'default_page' => '',
'contact_location' => '0',
'contact_js_effects' => '0',
'contact_theme' => 'light',
];
$this->user = new CentreonUser($userInfos);
}
/**
* @return void
*/
public function generateSession(): void
{
$_SESSION['centreon'] = $this;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/mock/Mock.php | centreon/tests/php/mock/Mock.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Test\Mock;
/**
* Abstract class for mock
*
* @author Centreon
* @version 1.0.0
* @package centreon-test-lib
* @subpackage test
*/
abstract class Mock
{
protected int $incrementalId = 1;
private static array $countFunction = [];
/**
* Constructor
*/
public function __construct()
{
}
/**
* Return real result
*
* @param $expectedResult
* @param int $stackTraceId
*
* @return array|mixed $result
*/
protected function realResult($expectedResult, int $stackTraceId = 1)
{
global $customResult;
if (! isset($customResult) || ! is_array($customResult)) {
return $expectedResult;
}
$stacktrace = debug_backtrace();
$calledMethod = $stacktrace[$stackTraceId]['function'];
if (isset(self::$countFunction[$calledMethod])) {
self::$countFunction[$calledMethod]++;
} else {
self::$countFunction[$calledMethod] = 0;
}
$result = $expectedResult;
if (array_key_exists($calledMethod, $customResult)) {
if (! is_array($customResult[$calledMethod])
|| (! array_key_exists('any', $customResult[$calledMethod]) && ! array_key_exists('at', $customResult[$calledMethod]))) {
$result = $customResult[$calledMethod];
} elseif (isset($customResult[$calledMethod]['at'])
&& array_key_exists(self::$countFunction[$calledMethod], $customResult[$calledMethod]['at'])) {
$result = $customResult[$calledMethod]['at'][self::$countFunction[$calledMethod]];
} elseif (array_key_exists('any', $customResult[$calledMethod])) {
$result = $customResult[$calledMethod]['any'];
}
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/mock/CentreonDBStatement.php | centreon/tests/php/mock/CentreonDBStatement.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Test\Mock;
/**
* Mock class for resultset
*
* @author Centreon
* @version 1.0.0
* @package centreon-test-lib
* @subpackage test
*/
class CentreonDBStatement extends \CentreonDBStatement
{
/** @var array<int|string, mixed> */
public $fetchObjectName;
protected string $query;
/** @var array<CentreonDBResultSet> */
protected array $resultsets;
protected CentreonDB $db;
/** @var array<int|string, mixed>|null */
protected ?array $params = null;
/** @var CentreonDBResultSet|null */
protected ?CentreonDBResultSet $currentResultSet = null;
/**
* Constructor
*
* @param string $query
* @param array<CentreonDBResultSet> $resultsets
* @param CentreonDB $db
*/
public function __construct($query, array $resultsets, CentreonDB $db)
{
$this->query = $query;
$this->resultsets = $resultsets;
$this->db = $db;
}
/**
* Bind column
* {@inheritDoc}
*/
public function bindColumn(
string|int $column,
mixed &$var,
int $type = \PDO::PARAM_STR,
int $maxLength = 0,
mixed $driverOptions = null,
): bool {
return true;
}
/**
* Bind parameter
*/
public function bindParam(
string|int $param,
mixed &$var,
int $type = \PDO::PARAM_STR,
int $maxLength = 0,
mixed $driverOptions = null,
): bool {
$this->bindValue($param, $var);
return true;
}
/**
* Bind value
*/
public function bindValue(
string|int $param,
mixed $value,
int $type = \PDO::PARAM_STR,
): bool {
if (is_null($this->params)) {
$this->params = [];
}
if (is_int($param)) {
$this->params[$param - 1] = $value;
} else {
$this->params[$param] = $value;
}
return true;
}
/**
* Execute statement
*
* @param array|null $parameters
*
* @throws \Exception
* @return bool
*/
public function execute($parameters = null): bool
{
$matching = null;
foreach ($this->resultsets as $resultset) {
$result = $resultset->match($this->params);
if ($result === 2 && is_null($this->currentResultSet)) {
$this->currentResultSet = $resultset;
} elseif ($result === 1 && is_null($matching)) {
$matching = $resultset;
}
}
if (is_null($this->currentResultSet)) {
$this->currentResultSet = $matching;
}
if (is_null($this->currentResultSet)) {
throw new \Exception('The query has not match');
}
// trigger callback
$this->currentResultSet->executeCallback($this->params);
// log queries if query will be executed in transaction
$this->db->transactionLogQuery($this->query, $this->currentResultSet, $this->params);
return true;
}
/**
* Count of updated lines
*
* @return int
*/
public function rowCount(): int
{
return $this->currentResultSet->rowCount();
}
/**
* Return a result
*
* @return false|array
*/
public function fetchRow(): false|array
{
if (! is_null($this->currentResultSet)) {
return $this->currentResultSet->fetchRow();
}
return false;
}
/**
* Return a result
*
* @param int $mode
* @param int $cursorOrientation
* @param int $cursorOffset
*
* @return false|array
*/
public function fetch(
int $mode = \PDO::FETCH_DEFAULT,
int $cursorOrientation = \PDO::FETCH_ORI_NEXT,
int $cursorOffset = 0,
): false|array {
return $this->fetchRow();
}
/**
* Reset the position of resultset
*/
public function resetResultSet(): void
{
if (! is_null($this->currentResultSet)) {
$this->currentResultSet->fetchRow();
}
}
/**
* Get count of rows
*
* @return int
*/
public function numRows(): int
{
if (! is_null($this->currentResultSet)) {
return $this->currentResultSet->numRows();
}
return 0;
}
/**
* Close cursor
*/
public function closeCursor(): bool
{
return true;
}
/**
* Return a result
*
* @param int $mode
* @param mixed ...$args
*
* @return array
*/
public function fetchAll(int $mode = \PDO::FETCH_DEFAULT, mixed ...$args): array
{
$results = [];
while ($row = $this->fetch()) {
$results[] = $row;
}
return $results;
}
/**
* Set fetch mode
*
* @param int $mode
* @param mixed ...$args
*
* @return true
*/
public function setFetchMode($mode, ...$args): true
{
$this->fetchObjectName = $args;
return true;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/mock/CentreonUser.php | centreon/tests/php/mock/CentreonUser.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Test\Mock;
/**
* Mock class for resultset
*
* @author Centreon
* @version 1.0.0
* @package centreon-license-manager
* @subpackage test
*/
class CentreonUser extends \CentreonUser
{
/** @var mixed|null */
public $user_id;
/** @var string|null */
public $name;
/** @var string|null */
public $alias;
/** @var string|null */
public $email;
/** @var mixed|null */
public $lang;
/** @var string */
public $charset = 'UTF-8';
/** @var mixed|null */
public $passwd;
/** @var mixed|null */
public $token;
/** @var mixed|null */
public $admin;
/** @var int */
public $version = 3;
/** @var mixed|null */
public $default_page;
/** @var mixed|null */
public $gmt;
/** @var mixed|null */
public $js_effects;
/** @var null */
public $is_admin = null;
/** @var mixed|null */
public $theme;
/**
* CentreonUser constructor
*
* @param $user
*/
public function __construct($user)
{
$this->user_id = $user['contact_id'] ?? null;
$this->name = isset($user['contact_name'])
? html_entity_decode($user['contact_name'], ENT_QUOTES, 'UTF-8') : null;
$this->alias = isset($user['contact_alias'])
? html_entity_decode($user['contact_alias'], ENT_QUOTES, 'UTF-8') : null;
$this->email = isset($user['contact_email'])
? html_entity_decode($user['contact_email'], ENT_QUOTES, 'UTF-8') : null;
$this->lang = $user['contact_lang'] ?? null;
$this->passwd = $user['contact_passwd'] ?? null;
$this->token = $user['contact_autologin_key'] ?? null;
$this->admin = $user['contact_admin'] ?? null;
$this->default_page = $user['default_page'] ?? null;
$this->gmt = $user['contact_location'] ?? null;
$this->js_effects = $user['contact_js_effects'] ?? null;
$this->theme = $user['contact_theme'] ?? null;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/mock/CentreonDBAdapter.php | centreon/tests/php/mock/CentreonDBAdapter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Test\Mock;
use Centreon\Infrastructure\CentreonLegacyDB\CentreonDBAdapter as BaseCentreonDBAdapter;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
/**
* Mock class for dbconn
*
* @author Centreon
* @version 1.0.0
* @package centreon-test-lib
* @subpackage test
*/
class CentreonDBAdapter extends BaseCentreonDBAdapter
{
/** @var array */
protected array $mocks = [];
public function getRepository($repository): ServiceEntityRepository
{
if (array_key_exists($repository, $this->mocks)) {
return $this->mocks[$repository];
}
return parent::getRepository($repository);
}
public function resetResultSet(): static
{
$this->mocks = [];
/** @var CentreonDB $db */
$db = $this->getCentreonDBInstance();
$db->resetResultSet();
return $this;
}
public function getMocks(): array
{
return $this->mocks;
}
public function addResultSet($query, $result, $params = null, ?callable $callback = null): static
{
/** @var CentreonDB $db */
$db = $this->getCentreonDBInstance();
$db->addResultSet($query, $result, $params, $callback);
return $this;
}
public function setCommitCallback(?callable $callback = null): static
{
/** @var CentreonDB $db */
$db = $this->getCentreonDBInstance();
$db->setCommitCallback($callback);
return $this;
}
public function setLastInsertId(?int $id = null): static
{
/** @var CentreonDB $db */
$db = $this->getCentreonDBInstance();
$db->setLastInsertId($id);
return $this;
}
public function addRepositoryMock(string $className, object $repository): static
{
$this->mocks[$className] = $repository;
return $this;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/mock/CentreonDBManagerService.php | centreon/tests/php/mock/CentreonDBManagerService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Test\Mock;
use Centreon\Infrastructure\CentreonLegacyDB\CentreonDBAdapter as BaseCentreonDBAdapter;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
use Centreon\Infrastructure\Service\CentreonDBManagerService as BaseCentreonDBManagerService;
/**
* Mock class for dbconn
*
* @author Centreon
* @version 1.0.0
* @package centreon-test-lib
* @subpackage test
*/
class CentreonDBManagerService extends BaseCentreonDBManagerService
{
protected CentreonDBAdapter $manager;
public function __construct()
{
$this->manager = new CentreonDBAdapter(new CentreonDB());
}
public function getAdapter(string $alias): BaseCentreonDBAdapter
{
return $this->manager;
}
public function getDefaultAdapter(): BaseCentreonDBAdapter
{
return $this->manager;
}
public function getRepository($repository): ServiceEntityRepository
{
return $this->manager->getRepository($repository);
}
public function resetResultSet(): CentreonDBAdapter
{
return $this->manager->resetResultSet();
}
public function addResultSet($query, $result, $params = null, ?callable $callback = null): CentreonDBAdapter
{
return $this->manager->addResultSet($query, $result, $params, $callback);
}
public function setCommitCallback(?callable $callback = null): CentreonDBAdapter
{
return $this->manager->setCommitCallback($callback);
}
public function addRepositoryMock(string $className, object $repository): CentreonDBAdapter
{
return $this->manager->addRepositoryMock($className, $repository);
}
public function setLastInsertId(?int $id = null): static
{
$this->manager->setLastInsertId($id);
return $this;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/mock/RestNotFoundException.php | centreon/tests/php/mock/RestNotFoundException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Test\Mock;
class RestNotFoundException extends \Exception
{
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/mock/CentreonDBResultSet.php | centreon/tests/php/mock/CentreonDBResultSet.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Test\Mock;
/**
* Mock class for resultset
*
* @author Centreon
* @version 1.0.0
* @package centreon-test-lib
* @subpackage test
*/
class CentreonDBResultSet extends CentreonDBStatement
{
protected array $resultset = [];
protected int $pos = 0;
/** @var callable */
protected $callback;
/**
* Constructor
*
* @param array $resultset The resultset for a query
* @param null $params The parameters of query, if not set :
* * the query has not parameters
* * the result is generic for the query
* @param callable|null $callback execute a callback when a query is executed
*/
public function __construct($resultset, $params = null, ?callable $callback = null)
{
$this->resultset = $resultset;
$this->params = $params;
$this->callback = $callback;
if ($this->params !== null) {
ksort($this->params);
}
}
/**
* Execute the callback comes from the test case object
*
* @param mixed|null $values
*/
public function executeCallback(mixed $values = null): void
{
if ($this->callback !== null) {
call_user_func($this->callback, $values);
}
}
/**
* Return a result
*
* @return array|false
*/
public function fetchRow(): array|false
{
if (! isset($this->resultset[$this->pos])) {
return false;
}
return $this->resultset[$this->pos++];
}
/**
* Return a result
*
* @param int $mode
* @param int $cursorOrientation
* @param int $cursorOffset
*
* @return array|false
*/
public function fetch(
int $mode = \PDO::FETCH_DEFAULT,
int $cursorOrientation = \PDO::FETCH_ORI_NEXT,
int $cursorOffset = 0,
): array|false {
return $this->fetchRow();
}
/**
* Return all results
*
* @param int $mode
* @param mixed ...$args
*
* @return array
*/
public function fetchAll(int $mode = \PDO::FETCH_DEFAULT, mixed ...$args): array
{
$this->pos = count($this->resultset);
return $this->resultset;
}
/**
* Reset the position of resultset
*/
public function resetResultSet(): void
{
$this->pos = 0;
}
/**
* Get resultset stack
*/
public function getResultSet(): array
{
return $this->resultset;
}
/**
* Return the number of rows of the result set
*
* @return int
*/
public function numRows(): int
{
return $this->rowCount();
}
/**
* Count of updated lines
*
* @return int
*/
public function rowCount(): int
{
return count($this->resultset);
}
/**
* If the queries match
*
* @param array|null $params The parameters of current query
*
* @return int The level of match
* * 0 - Not match
* * 1 - Match by default (the result set params is null by the query has $params)
* * 2 - Exact match
*/
public function match(?array $params = null): int
{
if ($this->params === $params) {
return 2;
}
if ($this->params === null) {
return 1;
}
if ($params !== null) {
ksort($params);
}
return 0;
}
public function closeCursor(): true
{
return true;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/mock/CentreonLog.php | centreon/tests/php/mock/CentreonLog.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Test\Mock;
/**
* Mock class for Log
*
* @author Centreon
* @version 1.0.0
* @subpackage test
*/
class CentreonLog
{
public function insertLog($id, $str, $print = 0, $page = 0, $option = 0)
{
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/mock/CentreonDB.php | centreon/tests/php/mock/CentreonDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Test\Mock;
/**
* Mock class for dbconn
*
* @author Centreon
* @version 1.0.0
* @package centreon-test-lib
* @subpackage test
*/
class CentreonDB extends \CentreonDB
{
/** @var array */
protected array $queries = [];
/** @var callable */
protected $commitCallback;
/** @var array|null */
protected ?array $transactionQueries = null;
/** @var string|false */
protected string|false $lastInsertId = false;
public function __construct()
{
}
/**
* Stub for function query
*
* {@inheritDoc}
* @throws \Exception
* @return CentreonDBStatement|false The resultset
*/
public function query($queryString, $parameters = null, ...$parametersArgs): CentreonDBStatement|false
{
return $this->execute($queryString, null);
}
/**
* Stub escape function
*
* @param string $str The string to escape
* @param bool $htmlSpecialChars
*
* @return string The string escaped
*/
public static function escape($str, $htmlSpecialChars = false): string
{
return $str;
}
/**
* Stub quote function
*
* @param string $string The string to escape
* @param int $type
*
* @return string|false The string escaped
*/
public function quote(string $string, int $type = \PDO::PARAM_STR): string|false
{
return "'" . $string . "'";
}
/**
* Reset result sets
*/
public function resetResultSet(): void
{
$this->queries = [];
$this->commitCallback = null;
}
/**
* Add a resultset to the mock
*
* @param string $query The query to catch
* @param array $result The resultset
* @param array|null $params The parameters of query, if not set :
* * the query has not parameters
* * the result is generic for the query
* @param callable|null $callback execute a callback when a query is executed
*
* @return CentreonDB
*/
public function addResultSet(string $query, array $result, ?array $params = null, ?callable $callback = null): CentreonDB
{
if (! isset($this->queries[$query])) {
$this->queries[$query] = [];
}
$this->queries[$query][] = new CentreonDBResultSet($result, $params, $callback);
return $this;
}
/**
* Add a callback set to test exception in commit of transaction
*
* @param callable|null $callback execute a callback when a query is executed
*
* @return CentreonDB
*/
public function setCommitCallback(?callable $callback = null): CentreonDB
{
$this->commitCallback = $callback;
return $this;
}
/**
* @param string $query
* @param array $options
*
* @throws \Exception
* @return CentreonDBStatement|false
*/
public function prepare(string $query, array $options = []): CentreonDBStatement|false
{
if (! isset($this->queries[$query])) {
throw new \Exception('Query is not set.' . "\nQuery : " . $query);
}
return new CentreonDBStatement($query, $this->queries[$query], $this);
}
/**
* Execute a query with values
*
* @param string $query The query to execute
* @param null $values The list of values for the query
*
* @throws \Exception
* @return CentreonDBResultSet The resultset
*/
public function execute($query, $values = null): CentreonDBResultSet
{
if (! array_key_exists($query, $this->queries)) {
throw new \Exception('Query is not set.' . "\nQuery : " . $query);
}
// find good query
$matching = null;
foreach ($this->queries[$query] as $resultSet) {
$result = $resultSet->match($values);
if ($result === 2) {
return $resultSet;
}
if ($result === 1 && $matching === null) {
$matching = $resultSet;
}
}
if ($matching === null) {
throw new \Exception('Query is not set.' . "\nQuery : " . $query);
}
// trigger callback
$matching->executeCallback($values);
// log queries if query will be execute in transaction
$this->transactionLogQuery($query, $matching, $values);
return $matching;
}
/**
* @param mixed $val
*
* @return void
*/
public function autoCommit($val): void
{
return;
}
/**
* @return bool
*/
public function beginTransaction(): bool
{
$this->transactionQueries = [];
return true;
}
/**
* @throws \Exception
* @return bool
*/
public function commit(): bool
{
if ($this->commitCallback !== null) {
// copy and reset the property transactionQueries
$queries = $this->transactionQueries;
$this->transactionQueries = null;
call_user_func($this->commitCallback, [$queries]);
}
return true;
}
/**
* @return bool
*/
public function rollback(): bool
{
return true;
}
/**
* @param false|string $id
*/
public function setLastInsertId(false|string $id = false): void
{
$this->lastInsertId = $id;
}
/**
* @param string|null $name
*
* @return string|false
*/
public function lastInsertId(?string $name = null): string|false
{
return $this->lastInsertId;
}
/**
* Log queries if query will be execute in transaction
*
* @param string $query
* @param array|null $values
* @param CentreonDBResultSet $matching
*/
public function transactionLogQuery(string $query, CentreonDBResultSet $matching, ?array $values = null): void
{
if ($this->transactionQueries !== null) {
$this->transactionQueries[] = [
'query' => $query,
'params' => $values,
'result' => $matching,
];
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/mock/Object/CentreonMedia.php | centreon/tests/php/mock/Object/CentreonMedia.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Test\Mock\Object;
class CentreonMedia extends BaseObject
{
public function addDirectory()
{
return $this->getIncrementedId();
}
public function getDirectoryName(): string
{
return 'directory_name';
}
public function addImage()
{
return $this->getIncrementedId();
}
public function setMediaDirectory($newMediaDirectory)
{
}
public function getMediaDirectory(): string
{
return 'directory_name';
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/mock/Object/CentreonHost.php | centreon/tests/php/mock/Object/CentreonHost.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Test\Mock\Object;
class CentreonHost extends BaseObject
{
private static int $countHostFunction = 0;
public function getHostId($host_name)
{
return $this->getIncrementedId();
}
public function update($hostId, $hostProperties)
{
}
public function insert($hostProperties)
{
return $this->getIncrementedId();
}
public function insertMacro($hostId, $macroInput, $macroValue, $macroPassword, $macroDescription)
{
}
public function deleteHostByName($host_name)
{
}
public function setTemplates($hostId, $hostTemplates)
{
}
public function insertRelHostService()
{
}
public function getHostByAddress($host_ip, $filter): array
{
self::$countHostFunction++;
if (self::$countHostFunction <= 2) {
return [
[
'host_id' => self::$countHostFunction,
'host_name' => '10.30.2.' . self::$countHostFunction,
],
];
}
return [];
}
public function getServices($hostId): array
{
return ['180' => 'Ping'];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/mock/Object/CentreonTimeperiod.php | centreon/tests/php/mock/Object/CentreonTimeperiod.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Test\Mock\Object;
class CentreonTimeperiod extends BaseObject
{
public function getTimperiodIdByName($tp_name)
{
return $this->getIncrementedId();
}
public function update($tp_id, $timeperiod)
{
}
public function deleteTimeperiodByName($tp_name)
{
}
public function setTimeperiodException($tp_id, $exceptions)
{
}
public function deleteTimeperiodException($tp_id)
{
}
public function deleteTimeperiodInclude($tp_id)
{
}
public function setTimeperiodDependency($tp_id, $dependencies)
{
}
public function getLinkedHostsByName(): array
{
return [];
}
public function getLinkedServicesByName(): array
{
return [];
}
public function getLinkedContactsByName(): array
{
return [];
}
public function getLinkedTimeperiodsByName(): array
{
return [];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/mock/Object/CentreonResources.php | centreon/tests/php/mock/Object/CentreonResources.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Test\Mock\Object;
class CentreonResources extends BaseObject
{
public function getResourceByName($db, $resourceName): array
{
return [
'resource_id' => 1,
'resource_name' => $resourceName,
'resource_line' => '/usr/lib/centreon/plugins',
'resource_comment' => 'Centreon Plugin Path',
'resource_activate' => 1,
];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/mock/Object/CentreonCommand.php | centreon/tests/php/mock/Object/CentreonCommand.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Test\Mock\Object;
class CentreonCommand extends BaseObject
{
public function getCommandIdByName($commandName)
{
return match ($commandName) {
'check_centreon_ping' => null,
default => $this->getIncrementedId(),
};
}
public function insert($parameters): void
{
$this->incrementalId++;
}
public function update($command_id, $command)
{
}
public function deleteCommandByName($command_name)
{
}
public function getLinkedHostsbyName()
{
}
public function getLinkedServicesbyName()
{
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/mock/Object/CentreonRestHttp.php | centreon/tests/php/mock/Object/CentreonRestHttp.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Test\Mock\Object;
class CentreonRestHttp extends BaseObject
{
public function call(): array
{
return ['company' => 'token'];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/mock/Object/CentreonService.php | centreon/tests/php/mock/Object/CentreonService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Test\Mock\Object;
class CentreonService extends BaseObject
{
public function getServiceTemplateId($service_description)
{
return $this->getIncrementedId();
}
public function update($serviceId, $serviceProperties)
{
}
public function insert($serviceProperties)
{
return $this->getIncrementedId();
}
public function insertMacro($hostId, $macroInput, $macroValue, $macroPassword, $macroDescription)
{
}
public function deleteServiceByDescription($service_description)
{
}
public function getParameters($serviceId, $parameters)
{
}
public function setServiceDescription($serviceId, $serviceDescription)
{
}
public function setServicealias($serviceId, $serviceAlias)
{
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/mock/Object/CentreonHosttemplates.php | centreon/tests/php/mock/Object/CentreonHosttemplates.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Test\Mock\Object;
class CentreonHosttemplates extends CentreonHost
{
public function getLinkedHostsbyName()
{
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/mock/Object/CentreonServicetemplates.php | centreon/tests/php/mock/Object/CentreonServicetemplates.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Test\Mock\Object;
class CentreonServicetemplates extends CentreonService
{
public function getServiceIdsLinkedToSTAndCreatedByHT()
{
}
public function getLinkedHostsByServiceDescription()
{
}
public function getLinkedServicesbyName()
{
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/mock/Object/BaseObject.php | centreon/tests/php/mock/Object/BaseObject.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Test\Mock\Object;
class BaseObject
{
protected int $incrementalId = 1;
private static array $countFunction = [];
protected function realResult($expectedResult)
{
global $customResult;
$stacktrace = debug_backtrace();
$calledMethod = $stacktrace[2]['function'];
if (isset(self::$countFunction[$calledMethod])) {
self::$countFunction[$calledMethod]++;
} else {
self::$countFunction[$calledMethod] = 0;
}
$result = $expectedResult;
if (array_key_exists($calledMethod, $customResult)) {
if (! is_array($customResult[$calledMethod])) {
$result = $customResult[$calledMethod];
} elseif (isset($customResult[$calledMethod]['at'])
&& array_key_exists(self::$countFunction[$calledMethod], $customResult[$calledMethod]['at'])) {
$result = $customResult[$calledMethod]['at'][self::$countFunction[$calledMethod]];
} elseif (array_key_exists('any', $customResult[$calledMethod])) {
$result = $customResult[$calledMethod]['any'];
}
}
return $result;
}
protected function getIncrementedId()
{
return $this->realResult($this->incrementalId++);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/mock/DependencyInjector/FinderProvider.php | centreon/tests/php/mock/DependencyInjector/FinderProvider.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Test\Mock\DependencyInjector;
use Pimple\Container;
use Symfony\Component\Finder\Finder;
class FinderProvider implements ServiceProviderInterface
{
private Finder $finder;
public function __construct(Finder $finder)
{
$this->finder = $finder;
}
public function register(Container $container): void
{
$container['finder'] = $this->finder;
}
public function terminate(Container $container): void
{
$container['finder'] = null;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/mock/DependencyInjector/ServiceProviderInterface.php | centreon/tests/php/mock/DependencyInjector/ServiceProviderInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Test\Mock\DependencyInjector;
use Pimple\Container;
interface ServiceProviderInterface
{
public function register(Container $container);
public function terminate(Container $container);
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/mock/DependencyInjector/ServiceContainerInterface.php | centreon/tests/php/mock/DependencyInjector/ServiceContainerInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Test\Mock\DependencyInjector;
interface ServiceContainerInterface
{
public function registerProvider(ServiceProviderInterface $serviceProvider);
public function terminate();
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/mock/DependencyInjector/FilesystemProvider.php | centreon/tests/php/mock/DependencyInjector/FilesystemProvider.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Test\Mock\DependencyInjector;
use Pimple\Container;
use Symfony\Component\Filesystem\Filesystem;
class FilesystemProvider implements ServiceProviderInterface
{
private Filesystem $filesystem;
public function __construct(Filesystem $filesystem)
{
$this->filesystem = $filesystem;
}
public function register(Container $container): void
{
$container['filesystem'] = $this->filesystem;
}
public function terminate(Container $container): void
{
$container['filesystem'] = null;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/mock/DependencyInjector/ServiceContainer.php | centreon/tests/php/mock/DependencyInjector/ServiceContainer.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Test\Mock\DependencyInjector;
use Pimple\Container;
class ServiceContainer extends Container
{
private array $providers = [];
public function registerProvider(ServiceProviderInterface $provider): void
{
$this->providers[] = $provider;
$provider->register($this);
}
public function terminate(): void
{
foreach ($this->providers as $provider) {
$provider->terminate($this);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/mock/DependencyInjector/ConfigurationDBProvider.php | centreon/tests/php/mock/DependencyInjector/ConfigurationDBProvider.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Test\Mock\DependencyInjector;
use Centreon\Test\Mock\CentreonDB;
use Pimple\Container;
class ConfigurationDBProvider implements ServiceProviderInterface
{
private CentreonDB $db;
public function __construct(CentreonDB $db)
{
$this->db = $db;
}
public function register(Container $container): void
{
$container['configuration_db'] = $this->db;
}
public function terminate(Container $container): void
{
$container['configuration_db'] = null;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/CentreonLegacy/ServiceProviderTest.php | centreon/tests/php/CentreonLegacy/ServiceProviderTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy;
use Centreon\Test\Mock;
use PHPUnit\Framework\TestCase;
use Pimple\Container;
/**
* @group CentreonLegacy
* @group ServiceProvider
*/
class ServiceProviderTest extends TestCase
{
protected $container;
protected $provider;
protected function setUp(): void
{
global $conf_centreon, $centreon_path;
$conf_centreon = [];
$centreon_path = '_PATH_';
$this->provider = new ServiceProvider();
$this->container = new Container();
$this->container['configuration_db'] = new Mock\CentreonDB();
$this->provider->register($this->container);
}
/**
* @covers \CentreonLegacy\ServiceProvider::register
* @covers \CentreonLegacy\ServiceProvider::registerConfiguration
* @covers \CentreonLegacy\ServiceProvider::registerModule
* @covers \CentreonLegacy\ServiceProvider::registerWidget
*/
public function testCheckServicesByList(): void
{
$checkList = [
ServiceProvider::CONFIGURATION => Core\Configuration\Configuration::class,
ServiceProvider::CENTREON_LEGACY_UTILS => Core\Utils\Utils::class,
ServiceProvider::CENTREON_LEGACY_MODULE_HEALTHCHECK => Core\Module\Healthcheck::class,
ServiceProvider::CENTREON_LEGACY_MODULE_INFORMATION => Core\Module\Information::class,
ServiceProvider::CENTREON_LEGACY_MODULE_LICENSE => Core\Module\License::class,
ServiceProvider::CENTREON_LEGACY_LICENSE => Core\Module\License::class, // alias
ServiceProvider::CENTREON_LEGACY_WIDGET_INFORMATION => Core\Widget\Information::class,
];
// check list of services
foreach ($checkList as $serviceName => $className) {
$this->assertTrue($this->container->offsetExists($serviceName));
$service = $this->container->offsetGet($serviceName);
$this->assertInstanceOf($className, $service);
}
}
/**
* Check CentreonRestHttp service
*/
public function testRegisterRestHttp(): void
{
$this->assertTrue($this->container->offsetExists(ServiceProvider::CENTREON_REST_HTTP));
$service = $this->container->offsetGet(ServiceProvider::CENTREON_REST_HTTP);
$this->assertInstanceOf(\Closure::class, $service);
}
/**
* @covers \CentreonLegacy\ServiceProvider::registerModule
* @covers \CentreonLegacy\ServiceProvider::registerWidget
*/
public function testCheckServicesByModuleList(): void
{
// mock some of services
$this->container[ServiceProvider::CENTREON_LEGACY_UTILS] = $this->createMock(Core\Utils\Utils::class);
$this->container[ServiceProvider::CENTREON_LEGACY_MODULE_INFORMATION] = $this->createMock(Core\Module\Information::class);
$this->container[ServiceProvider::CENTREON_LEGACY_WIDGET_INFORMATION] = $this->createMock(Core\Widget\Information::class);
$moduleName = 'mod-name';
$moduleId = 'mod-id';
$checkList = [
ServiceProvider::CENTREON_LEGACY_MODULE_INSTALLER => [
'class' => Core\Module\Installer::class,
'attr' => [
$moduleName,
],
],
ServiceProvider::CENTREON_LEGACY_MODULE_UPGRADER => [
'class' => Core\Module\Upgrader::class,
'attr' => [
$moduleName,
$moduleId,
],
],
ServiceProvider::CENTREON_LEGACY_MODULE_REMOVER => [
'class' => Core\Module\Remover::class,
'attr' => [
$moduleName,
$moduleId,
],
],
ServiceProvider::CENTREON_LEGACY_WIDGET_INSTALLER => [
'class' => Core\Widget\Installer::class,
'attr' => [
$moduleName,
],
],
ServiceProvider::CENTREON_LEGACY_WIDGET_UPGRADER => [
'class' => Core\Widget\Upgrader::class,
'attr' => [
$moduleName,
],
],
ServiceProvider::CENTREON_LEGACY_WIDGET_REMOVER => [
'class' => Core\Widget\Remover::class,
'attr' => [
$moduleName,
],
],
];
// check list of services
foreach ($checkList as $serviceName => $data) {
$className = $data['class'];
$this->assertTrue($this->container->offsetExists($serviceName));
$callable = $this->container->offsetGet($serviceName);
$service = call_user_func_array($callable, $data['attr']);
$this->assertInstanceOf($className, $service);
}
}
/**
* @covers \CentreonLegacy\ServiceProvider::order
*/
public function testOrder(): void
{
$this->assertEquals(0, $this->provider::order());
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/CentreonLegacy/Core/Utils/FactoryTest.php | centreon/tests/php/CentreonLegacy/Core/Utils/FactoryTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Utils;
use Centreon\Test\Mock\DependencyInjector\ServiceContainer;
use CentreonLegacy\Core\Utils;
use CentreonLegacy\ServiceProvider;
use PHPUnit\Framework\TestCase;
/**
* @group CentreonLegacy
* @group CentreonLegacy\Utils
*/
class FactoryTest extends TestCase
{
/** @var ServiceContainer */
public $container;
public function setUp(): void
{
$this->container = new ServiceContainer();
$this->container[ServiceProvider::CENTREON_LEGACY_UTILS] = $this
->getMockBuilder(Utils\Utils::class)
->disableOriginalConstructor()
->getMock();
}
public function tearDown(): void
{
$this->container->terminate();
$this->container = null;
}
public function testNewUtils(): void
{
$factory = new Factory($this->container);
$this->assertInstanceOf(Utils\Utils::class, $factory->newUtils());
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/CentreonLegacy/Core/Utils/UtilsTest.php | centreon/tests/php/CentreonLegacy/Core/Utils/UtilsTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Tests\CentreonLegacy\Core\Utils;
use Centreon\Test\Mock;
use Centreon\Test\Mock\DependencyInjector\ServiceContainer;
use CentreonLegacy\Core\Configuration\Configuration;
use CentreonLegacy\Core\Utils\Utils;
use CentreonLegacy\ServiceProvider;
use PHPUnit\Framework\TestCase;
use Pimple\Psr11\Container;
use VirtualFileSystem\FileSystem;
use VirtualFileSystem\Structure\File;
/**
* @group CentreonLegacy
* @group CentreonLegacy\Utils
*/
class UtilsTest extends TestCase
{
/** @var FileSystem */
public $fileSystem;
/** @var ServiceContainer */
public $container;
/** @var Utils */
public $service;
public function setUp(): void
{
// mount VFS
$this->fileSystem = new FileSystem();
$this->fileSystem->createDirectory('/tmp');
$this->container = new ServiceContainer();
$this->container[ServiceProvider::CONFIGURATION] = $this->createMock(Configuration::class);
$this->container['configuration_db'] = new Mock\CentreonDB();
$this->container['configuration_db']->addResultSet("SELECT 'OK';", []);
$this->service = new Utils(new Container($this->container));
}
public function tearDown(): void
{
$this->container->terminate();
$this->container = null;
}
/**
* @covers \CentreonLegacy\Core\Utils\Utils::objectIntoArray
*/
public function testObjectIntoArray(): void
{
$object = new \stdClass();
$object->message = 'test';
$object->subMessage = ['test'];
$value = [
'message' => 'test',
'subMessage' => [
'test',
],
];
$result = $this->service->objectIntoArray($object);
$this->assertEquals($result, $value);
}
/**
* @covers \CentreonLegacy\Core\Utils\Utils::objectIntoArray
*/
public function testObjectIntoArrayWithSkippedKeys(): void
{
$object = new \stdClass();
$object->message = 'test';
$object->subMessage = ['test'];
$value = [
'message' => 'test',
];
$result = $this->service->objectIntoArray($object, ['subMessage']);
$this->assertEquals($result, $value);
}
/**
* @covers \CentreonLegacy\Core\Utils\Utils::objectIntoArray
*/
public function testObjectIntoArrayWithEmptyObject(): void
{
$result = $this->service->objectIntoArray(new \stdClass());
$this->assertEmpty($result);
}
public function testBuildPath(): void
{
$endPath = '.';
$result = $this->service->buildPath($endPath);
$this->assertStringEndsWith('www', $result);
}
public function testRequireConfiguration(): void
{
$configurationFile = '';
$type = '';
$result = $this->service->requireConfiguration($configurationFile, $type);
$this->assertEmpty($result);
}
/**
* Unable to find the wrapper "vfs" can't be tested
*
* @todo the method must be refactored
*/
public function testExecutePhpFileWithUnexistsFile(): void
{
$fileName = $this->fileSystem->path('/tmp/conf2.php');
$this->expectException(\Exception::class);
$this->service->executePhpFile($fileName);
}
public function testExecuteSqlFile(): void
{
$file = $this->fileSystem->createFile('/tmp/conf.sql', "SELECT 'OK';");
$this->assertInstanceOf(File::class, $file);
$fileName = $this->fileSystem->path('/tmp/conf.sql');
$this->assertIsString($fileName);
try {
$isException = false;
$this->service->executeSqlFile($fileName);
} catch (\Exception) {
$isException = true;
}
$this->assertFalse($isException);
}
public function testExecuteSqlFileWithWithUnexistsFileAndRealtimeDb(): void
{
$fileName = $this->fileSystem->path('/tmp/conf2.sql');
$result = null;
try {
$this->service->executeSqlFile($fileName, [], true);
} catch (\Exception $ex) {
$result = $ex;
}
$this->assertInstanceOf(\Exception::class, $result);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/CentreonLegacy/Core/Module/FactoryTest.php | centreon/tests/php/CentreonLegacy/Core/Module/FactoryTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Module;
use Centreon\Test\Mock\DependencyInjector\ServiceContainer;
use CentreonLegacy\ServiceProvider;
use Pimple\Container;
/**
* Class
*
* @class FactoryTest
* @package CentreonLegacy\Core\Module
*/
class FactoryTest extends \PHPUnit\Framework\TestCase
{
/** @var ServiceContainer */
public $container;
public function setUp(): void
{
$this->container = new ServiceContainer();
$this->container[ServiceProvider::CENTREON_LEGACY_MODULE_INFORMATION] = $this
->getMockBuilder(Information::class)
->disableOriginalConstructor()
->getMock();
$this->container[ServiceProvider::CENTREON_LEGACY_MODULE_LICENSE] = $this
->getMockBuilder(License::class)
->disableOriginalConstructor()
->getMock();
$this->container[ServiceProvider::CENTREON_LEGACY_MODULE_INSTALLER] = function (Container $container) {
return function ($moduleName) {
return $this->getMockBuilder(Installer::class)
->disableOriginalConstructor()
->getMock();
};
};
$this->container[ServiceProvider::CENTREON_LEGACY_MODULE_UPGRADER] = function (Container $container) {
return function ($moduleName, $moduleId) {
return $this->getMockBuilder(Upgrader::class)
->disableOriginalConstructor()
->getMock();
};
};
$this->container[ServiceProvider::CENTREON_LEGACY_MODULE_REMOVER] = function (Container $container) {
return function ($moduleName, $moduleId) {
return $this->getMockBuilder(Remover::class)
->disableOriginalConstructor()
->getMock();
};
};
}
public function tearDown(): void
{
$this->container->terminate();
$this->container = null;
}
public function testNewInformation(): void
{
$factory = new Factory($this->container);
$this->assertInstanceOf(Information::class, $factory->newInformation());
}
public function testNewInstaller(): void
{
$factory = new Factory($this->container);
$this->assertInstanceOf(Installer::class, $factory->newInstaller('MyModule'));
}
public function testNewUpgrader(): void
{
$factory = new Factory($this->container);
$this->assertInstanceOf(Upgrader::class, $factory->newUpgrader('MyModule', 1));
}
public function testNewRemover(): void
{
$factory = new Factory($this->container);
$this->assertInstanceOf(Remover::class, $factory->newRemover('MyModule', 1));
}
public function testNewLicense(): void
{
$factory = new Factory($this->container);
$this->assertInstanceOf(License::class, $factory->newLicense());
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/CentreonLegacy/Core/Module/LicenseTest.php | centreon/tests/php/CentreonLegacy/Core/Module/LicenseTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Module;
use Centreon\Test\Mock\DependencyInjector\ServiceContainer;
use CentreonLegacy\ServiceProvider;
use PHPUnit\Framework\TestCase;
use Pimple\Psr11\Container;
/**
* @group CentreonLegacy
* @group CentreonLegacy\Module
*/
class LicenseTest extends TestCase
{
/** @var ServiceContainer */
public $container;
/** @var License */
public $service;
public function setUp(): void
{
$this->container = new ServiceContainer();
$this->container[ServiceProvider::CENTREON_LEGACY_MODULE_HEALTHCHECK] = $this->createMock(Healthcheck::class);
$this->service = new License(new Container($this->container));
}
public function tearDown(): void
{
$this->container->terminate();
$this->container = null;
}
public function testGetLicenseExpiration(): void
{
$module = 'mod';
$value = null;
$result = $this->service->getLicenseExpiration($module);
$this->assertEquals($result, $value);
}
public function testGetLicenseExpirationWithException(): void
{
$module = 'mod';
$value = null;
$this->container[ServiceProvider::CENTREON_LEGACY_MODULE_HEALTHCHECK] = $this
->getMockBuilder(Healthcheck::class)
->disableOriginalConstructor()
->onlyMethods([
'check',
])
->getMock();
$this->container[ServiceProvider::CENTREON_LEGACY_MODULE_HEALTHCHECK]
->method('check')
->will($this->returnCallback(function (): void {
throw new \Exception();
}));
$result = $this->service->getLicenseExpiration($module);
$this->assertEquals($result, $value);
}
public function testGetLicenseExpirationWithExpirationDate(): void
{
$module = 'mod';
$value = date(\DateTime::ISO8601);
$this->container[ServiceProvider::CENTREON_LEGACY_MODULE_HEALTHCHECK] = $this
->getMockBuilder(Healthcheck::class)
->disableOriginalConstructor()
->onlyMethods([
'getLicenseExpiration',
])
->getMock();
$this->container[ServiceProvider::CENTREON_LEGACY_MODULE_HEALTHCHECK]
->method('getLicenseExpiration')
->will($this->returnCallback(function () use ($value) {
return new \DateTime($value);
}));
$result = $this->service->getLicenseExpiration($module);
$this->assertEquals($result, $value);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/CentreonLegacy/Core/Module/InstallerTest.php | centreon/tests/php/CentreonLegacy/Core/Module/InstallerTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Module;
use Centreon\Test\Mock\CentreonDB;
use Centreon\Test\Mock\DependencyInjector\ConfigurationDBProvider;
use Centreon\Test\Mock\DependencyInjector\FilesystemProvider;
use Centreon\Test\Mock\DependencyInjector\ServiceContainer;
use Pimple\Psr11\Container;
class InstallerTest extends \PHPUnit\Framework\TestCase
{
private $container;
private $db;
private $information;
private $utils;
public function setUp(): void
{
$this->container = new ServiceContainer();
$this->db = new CentreonDB();
$configuration = ['name' => 'MyModule', 'rname' => 'MyModule', 'mod_release' => '1.0.0', 'is_removeable' => 1, 'infos' => 'my module for unit test', 'author' => 'unit test', 'svc_tools' => null, 'host_tools' => null];
$this->information = $this->getMockBuilder(Information::class)
->disableOriginalConstructor()
->onlyMethods(['getConfiguration'])
->getMock();
$this->information->expects($this->any())
->method('getConfiguration')
->willReturn($configuration);
$this->utils = $this->getMockBuilder(\CentreonLegacy\Core\Utils\Utils::class)
->disableOriginalConstructor()
->getMock();
}
public function tearDown(): void
{
$this->container->terminate();
$this->container = null;
}
public function testInstall(): void
{
$filesystem = $this->getMockBuilder(\Symfony\Component\Filesystem\Filesystem::class)
->disableOriginalConstructor()
->onlyMethods(['exists'])
->getMock();
$filesystem->expects($this->any())
->method('exists')
->willReturn(true);
$this->container->registerProvider(new FilesystemProvider($filesystem));
$query = 'INSERT INTO modules_informations '
. '(`name` , `rname` , `mod_release` , `is_removeable` , `infos` , `author` , '
. '`svc_tools`, `host_tools`)'
. 'VALUES ( :name , :rname , :mod_release , :is_removeable , :infos , :author , '
. ':svc_tools , :host_tools )';
$this->db->addResultSet(
$query,
[]
);
$this->db->addResultSet(
'SELECT MAX(id) as id FROM modules_informations',
[['id' => 1]]
);
$this->container->registerProvider(new ConfigurationDBProvider($this->db));
$installer = new Installer(new Container($this->container), $this->information, 'MyModule', $this->utils);
$id = $installer->install();
$this->assertEquals($id, 1);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/CentreonLegacy/Core/Module/RemoverTest.php | centreon/tests/php/CentreonLegacy/Core/Module/RemoverTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Module;
use Centreon\Test\Mock\CentreonDB;
use Centreon\Test\Mock\DependencyInjector\ConfigurationDBProvider;
use Centreon\Test\Mock\DependencyInjector\FilesystemProvider;
use Centreon\Test\Mock\DependencyInjector\ServiceContainer;
use Pimple\Psr11\Container;
class RemoverTest extends \PHPUnit\Framework\TestCase
{
private $container;
private $db;
private $information;
private $utils;
public function setUp(): void
{
$this->container = new ServiceContainer();
$this->db = new CentreonDB();
$configuration = ['name' => 'MyModule', 'rname' => 'MyModule', 'mod_release' => '1.0.0', 'is_removeable' => 1, 'infos' => 'my module for unit test', 'author' => 'unit test', 'svc_tools' => null, 'host_tools' => null];
$this->information = $this->getMockBuilder(Information::class)
->disableOriginalConstructor()
->onlyMethods(['getConfiguration'])
->getMock();
$this->information->expects($this->any())
->method('getConfiguration')
->willReturn($configuration);
$this->utils = $this->getMockBuilder(\CentreonLegacy\Core\Utils\Utils::class)
->disableOriginalConstructor()
->getMock();
}
public function tearDown(): void
{
$this->container->terminate();
$this->container = null;
}
public function testRemove(): void
{
$filesystem = $this->getMockBuilder(\Symfony\Component\Filesystem\Filesystem::class)
->disableOriginalConstructor()
->onlyMethods(['exists'])
->getMock();
$filesystem->expects($this->any())
->method('exists')
->willReturn(true);
$this->container->registerProvider(new FilesystemProvider($filesystem));
$this->db->addResultSet(
'DELETE FROM modules_informations WHERE id = :id ',
[]
);
$this->container->registerProvider(new ConfigurationDBProvider($this->db));
$remover = new Remover(new Container($this->container), $this->information, 'MyModule', $this->utils);
$removed = $remover->remove();
$this->assertEquals($removed, true);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/CentreonLegacy/Core/Module/InformationTest.php | centreon/tests/php/CentreonLegacy/Core/Module/InformationTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Module;
use Centreon\Test\Mock\CentreonDB;
use Centreon\Test\Mock\DependencyInjector\ConfigurationDBProvider;
use Centreon\Test\Mock\DependencyInjector\FilesystemProvider;
use Centreon\Test\Mock\DependencyInjector\FinderProvider;
use Centreon\Test\Mock\DependencyInjector\ServiceContainer;
use Pimple\Psr11\Container;
class InformationTest extends \PHPUnit\Framework\TestCase
{
private $container;
private $db;
private $license;
private $utils;
public function setUp(): void
{
$this->container = new ServiceContainer();
$this->db = new CentreonDB();
$this->license = $this->getMockBuilder(License::class)
->disableOriginalConstructor()
->getMock();
$this->utils = $this->getMockBuilder(\CentreonLegacy\Core\Utils\Utils::class)
->disableOriginalConstructor()
->getMock();
}
public function tearDown(): void
{
$this->container->terminate();
$this->container = null;
}
public function testGetConfiguration(): void
{
$expectedResult = ['name' => 'MyModule', 'rname' => 'MyModule', 'mod_release' => '1.0.0'];
$moduleConfiguration = ['MyModule' => ['name' => 'MyModule', 'rname' => 'MyModule', 'mod_release' => '1.0.0']];
$this->utils->expects($this->any())
->method('requireConfiguration')
->willReturn($moduleConfiguration);
$information = new Information(new Container($this->container), $this->license, $this->utils);
$configuration = $information->getConfiguration('MyModule');
$this->assertEquals($configuration, $expectedResult);
}
public function testGetNameById(): void
{
$this->db->addResultSet(
'SELECT name FROM modules_informations WHERE id = :id',
[['name' => 'MyModule']]
);
$this->container->registerProvider(new ConfigurationDBProvider($this->db));
$information = new Information(new Container($this->container), $this->license, $this->utils);
$name = $information->getNameById(1);
$this->assertEquals($name, 'MyModule');
}
public function testGetList(): void
{
$expectedResult = ['MyModule1' => ['id' => 1, 'name' => 'MyModule1', 'rname' => 'MyModule1', 'mod_release' => '1.0.0', 'license_expiration' => '2020-10-10 12:00:00', 'source_available' => true, 'is_installed' => true, 'upgradeable' => false, 'installed_version' => '1.0.0', 'available_version' => '1.0.0'], 'MyModule2' => ['id' => 2, 'name' => 'MyModule2', 'rname' => 'MyModule2', 'mod_release' => '2.0.0', 'license_expiration' => '2020-10-10 12:00:00', 'source_available' => true, 'is_installed' => true, 'upgradeable' => true, 'installed_version' => '1.0.0', 'available_version' => '2.0.0']];
$this->db->addResultSet(
'SELECT * FROM modules_informations ',
[['id' => 1, 'name' => 'MyModule1', 'mod_release' => '1.0.0'], ['id' => 2, 'name' => 'MyModule2', 'mod_release' => '1.0.0']]
);
$this->container->registerProvider(new ConfigurationDBProvider($this->db));
$filesystem = $this->getMockBuilder(\Symfony\Component\Filesystem\Filesystem::class)
->disableOriginalConstructor()
->onlyMethods(['exists'])
->getMock();
$filesystem->expects($this->any())
->method('exists')
->willReturn(true);
$this->container->registerProvider(new FilesystemProvider($filesystem));
$finder = $this->getMockBuilder(\Symfony\Component\Finder\Finder::class)
->disableOriginalConstructor()
->onlyMethods(['directories', 'depth', 'in', 'getIterator'])
->getMock();
$finder->expects($this->any())
->method('directories')
->willReturn($finder);
$finder->expects($this->any())
->method('depth')
->willReturn($finder);
$finder->expects($this->any())
->method('in')
->willReturn($finder);
$finder->expects($this->any())
->method('getIterator')
->willReturn(new \ArrayIterator([
new \SplFileInfo('MyModule1'),
new \SplFileInfo('MyModule2'),
]));
$this->container->registerProvider(new FinderProvider($finder));
$moduleConfiguration1 = ['MyModule1' => ['name' => 'MyModule1', 'rname' => 'MyModule1', 'mod_release' => '1.0.0']];
$moduleConfiguration2 = ['MyModule2' => ['name' => 'MyModule2', 'rname' => 'MyModule2', 'mod_release' => '2.0.0']];
$this->utils->expects($this->exactly(2))
->method('requireConfiguration')
->will(
$this->onConsecutiveCalls(
$moduleConfiguration1,
$moduleConfiguration2
)
);
$this->license->expects($this->any())
->method('getLicenseExpiration')
->willReturn('2020-10-10 12:00:00');
$information = new Information(new Container($this->container), $this->license, $this->utils);
$list = $information->getList();
$this->assertEquals($list, $expectedResult);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/CentreonLegacy/Core/Module/HealthcheckTest.php | centreon/tests/php/CentreonLegacy/Core/Module/HealthcheckTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Module;
use Centreon\Test\Mock\DependencyInjector\ServiceContainer;
use CentreonLegacy\Core\Configuration\Configuration;
use CentreonLegacy\ServiceProvider;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Pimple\Psr11\Container;
use VirtualFileSystem\FileSystem;
/**
* @group CentreonLegacy
* @group CentreonLegacy\Module
*/
class HealthcheckTest extends TestCase
{
/** @var FileSystem */
public $fileSystem;
/** @var MockObject&ServiceContainer */
public $container;
/** @var MockObject&Healthcheck */
public $service;
public function setUp(): void
{
// mount VFS
$this->fileSystem = new FileSystem();
$this->fileSystem->createDirectory('/tmp');
$this->fileSystem->createDirectory('/tmp/checklist');
$this->fileSystem->createFile('/tmp/checklist/requirements.php', '');
$this->fileSystem->createDirectory('/tmp1');
$this->fileSystem->createDirectory('/tmp1/checklist');
$this->container = new ServiceContainer();
$this->container[ServiceProvider::CONFIGURATION] = $this
->getMockBuilder(Configuration::class)
->disableOriginalConstructor()
->onlyMethods([
'getModulePath',
])
->getMock();
$this->container[ServiceProvider::CONFIGURATION]
->method('getModulePath')
->will(
$this->returnCallback(function () {
return $this->fileSystem->path('/');
})
);
$this->service = $this->getMockBuilder(Healthcheck::class)
->setConstructorArgs([
new Container($this->container),
])
->onlyMethods([
'getRequirements',
])
->getMock();
$this->setRequirementMockMethodValue();
}
public function tearDown(): void
{
$this->container->terminate();
$this->container = null;
}
public function testCheckWithDotModuleName(): void
{
try {
$this->service->check('.');
} catch (\Exception $ex) {
$this->assertInstanceOf(Exception\HealthcheckNotFoundException::class, $ex);
}
}
public function testCheckWithMissingModule(): void
{
try {
$this->service->check('mod');
} catch (\Exception $ex) {
$this->assertInstanceOf(Exception\HealthcheckNotFoundException::class, $ex);
}
}
public function testCheckWithWarning(): void
{
$module = 'tmp';
$this->setRequirementMockMethodValue(null, null, true);
try {
$this->service->check($module);
} catch (\Exception $ex) {
$this->assertInstanceOf(Exception\HealthcheckWarningException::class, $ex);
}
}
public function testCheckWithCritical(): void
{
$module = 'tmp';
$valueMessages = [
[
'ErrorMessage' => 'err',
'Solution' => 'none',
],
];
$this->setRequirementMockMethodValue($valueMessages, null, false, true);
try {
$this->service->check($module);
} catch (\Exception $ex) {
$this->assertInstanceOf(Exception\HealthcheckCriticalException::class, $ex);
$this->assertEquals($valueMessages[0], $this->service->getMessages());
}
}
public function testCheckWithoutRequirementsFile(): void
{
$module = 'tmp1';
$this->setRequirementMockMethodValue();
try {
$this->service->check($module);
} catch (\Exception $ex) {
$this->assertInstanceOf(Exception\HealthcheckNotFoundException::class, $ex);
}
}
public function testCheck(): void
{
$module = 'tmp';
$valueTime = time();
$valueCustomAction = [
'action' => 'act',
'name' => 'nm',
];
$this->setRequirementMockMethodValue(null, $valueCustomAction, false, false, $valueTime);
$result = $this->service->check($module);
$this->assertTrue($result);
$this->assertEquals($valueTime, $this->service->getLicenseExpiration()->getTimestamp());
$this->assertEquals(
[
'customAction' => $valueCustomAction['action'],
'customActionName' => $valueCustomAction['name'],
],
$this->service->getCustomAction()
);
}
public function testCheckPrepareResponseWithNotFound(): void
{
$module = 'mod';
$value = [
'status' => 'notfound',
];
$result = $this->service->checkPrepareResponse($module);
$this->assertEquals($result, $value);
}
public function testCheckPrepareResponseWithCritical(): void
{
$module = 'tmp';
$valueMessages = [
[
'ErrorMessage' => 'err',
'Solution' => 'none',
],
];
$value = [
'status' => 'critical',
'message' => [
'ErrorMessage' => $valueMessages[0]['ErrorMessage'],
'Solution' => $valueMessages[0]['Solution'],
],
];
$this->setRequirementMockMethodValue($valueMessages, null, false, true);
$result = $this->service->checkPrepareResponse($module);
$this->assertEquals($result, $value);
}
public function testCheckPrepareResponseWithWarning(): void
{
$module = 'tmp';
$valueMessages = [
[
'ErrorMessage' => 'err',
'Solution' => 'none',
],
];
$value = [
'status' => 'warning',
'message' => [
'ErrorMessage' => $valueMessages[0]['ErrorMessage'],
'Solution' => $valueMessages[0]['Solution'],
],
];
$this->setRequirementMockMethodValue($valueMessages, null, true);
$result = $this->service->checkPrepareResponse($module);
$this->assertEquals($value, $result);
}
public function testCheckPrepareResponseWithException(): void
{
$module = 'tmp';
$valueException = 'test exception';
$value = [
'status' => 'critical',
'message' => [
'ErrorMessage' => $valueException,
'Solution' => '',
],
];
$this->service
->method('getRequirements')
->will($this->returnCallback(
function (
$checklistDir,
&$message,
&$customAction,
&$warning,
&$critical,
&$licenseExpiration,
) use ($valueException): void {
throw new \Exception($valueException);
}
));
$result = $this->service->checkPrepareResponse($module);
$this->assertEquals($result, $value);
}
public function testCheckPrepareResponse(): void
{
$module = 'tmp';
$valueTime = time();
$valueCustomAction = [
'action' => 'act',
'name' => 'nm',
];
$value = [
'status' => 'ok',
'customAction' => $valueCustomAction['action'],
'customActionName' => $valueCustomAction['name'],
'licenseExpiration' => $valueTime,
];
$this->setRequirementMockMethodValue(null, $valueCustomAction, false, false, $valueTime);
$result = $this->service->checkPrepareResponse($module);
$this->assertEquals($result, $value);
}
public function testReset(): void
{
$this->service->reset();
$this->assertEquals(null, $this->service->getMessages());
$this->assertEquals(null, $this->service->getCustomAction());
$this->assertEquals(null, $this->service->getLicenseExpiration());
}
/**
* Set up method getRequirements
*
* @param array $messageV
* @param array $customActionV
* @param bool $warningV
* @param bool $criticalV
* @param int $licenseExpirationV
*/
protected function setRequirementMockMethodValue(
$messageV = null,
$customActionV = null,
$warningV = false,
$criticalV = false,
$licenseExpirationV = null,
) {
$this->service
->method('getRequirements')
->will($this->returnCallback(
function (
$checklistDir,
&$message,
&$customAction,
&$warning,
&$critical,
&$licenseExpiration,
) use ($messageV, $customActionV, $warningV, $criticalV, $licenseExpirationV): void {
$message = $messageV ?: [];
$customAction = $customActionV;
$warning = $warningV;
$critical = $criticalV;
$licenseExpiration = $licenseExpirationV;
}
));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/CentreonLegacy/Core/Module/UpgraderTest.php | centreon/tests/php/CentreonLegacy/Core/Module/UpgraderTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Module;
use Centreon\Test\Mock\CentreonDB;
use Centreon\Test\Mock\DependencyInjector\ConfigurationDBProvider;
use Centreon\Test\Mock\DependencyInjector\FilesystemProvider;
use Centreon\Test\Mock\DependencyInjector\FinderProvider;
use Centreon\Test\Mock\DependencyInjector\ServiceContainer;
use Pimple\Psr11\Container;
class UpgraderTest extends \PHPUnit\Framework\TestCase
{
private $container;
private $db;
private $information;
private $utils;
private static $originalProcessClass;
/**
* Create a hacky Process class for the test
*/
public static function setUpBeforeClass(): void
{
// Save the real Process if it is already loaded
if (class_exists(\Symfony\Component\Process\Process::class, false)) {
self::$originalProcessClass = new \ReflectionClass(\Symfony\Component\Process\Process::class);
}
// HACK: create a fake Process in the Symfony namespace
eval('
namespace Symfony\Component\Process;
class Process {
public function __construct(array $cmd) {}
public function setWorkingDirectory($dir) {}
public function run() {}
public function isSuccessful() { return true; }
}');
}
/**
* Delete mock and restore origin class.
*/
public static function tearDownAfterClass(): void
{
if (self::$originalProcessClass !== null) {
self::$originalProcessClass = null;
}
}
public function setUp(): void
{
$this->container = new ServiceContainer();
$this->db = new CentreonDB();
$this->information = $this->getMockBuilder(Information::class)
->disableOriginalConstructor()
->onlyMethods(['getInstalledInformation', 'getModulePath', 'getConfiguration'])
->getMock();
$installedInformation = ['name' => 'MyModule', 'rname' => 'MyModule', 'mod_release' => '1.0.0', 'is_removeable' => 1, 'infos' => 'my module for unit test', 'author' => 'unit test', 'svc_tools' => null, 'host_tools' => null];
$this->information->expects($this->any())
->method('getInstalledInformation')
->willReturn($installedInformation);
$configuration = ['name' => 'MyModule', 'rname' => 'MyModule', 'mod_release' => '1.0.1', 'is_removeable' => 1, 'infos' => 'my module for unit test', 'author' => 'unit test', 'svc_tools' => null, 'host_tools' => null];
$this->information->expects($this->any())
->method('getConfiguration')
->willReturn($configuration);
$this->information->expects($this->any())
->method('getModulePath')
->willReturn('/MyModule/');
$this->utils = $this->getMockBuilder(\CentreonLegacy\Core\Utils\Utils::class)
->disableOriginalConstructor()
->onlyMethods(['requireConfiguration', 'executeSqlFile', 'executePhpFile'])
->getMock();
$upgradeConfiguration = ['MyModule' => ['name' => 'MyModule', 'rname' => 'MyModule', 'release_from' => '1.0.0', 'release_to' => '1.0.1', 'infos' => 'my module for unit test', 'author' => 'unit test']];
$this->utils->expects($this->any())
->method('requireConfiguration')
->willReturn($upgradeConfiguration);
$this->utils->expects($this->any())
->method('executeSqlFile');
$this->utils->expects($this->any())
->method('executePhpFile');
}
public function tearDown(): void
{
$this->container->terminate();
$this->container = null;
}
public function testUpgrader(): void
{
// HACK:this is done to prevent an error in code execution that says
// the constant is not defined while using the Symfony proccess setWorkingDir method
if (! defined('_CENTREON_PATH_')) {
define('_CENTREON_PATH_', getcwd());
}
$filesystem = $this->getMockBuilder(\Symfony\Component\Filesystem\Filesystem::class)
->disableOriginalConstructor()
->onlyMethods(['exists'])
->getMock();
$filesystem->expects($this->any())
->method('exists')
->will($this->returnCallback([$this, 'mockExists']));
// ->willReturn(true);
$this->container->registerProvider(new FilesystemProvider($filesystem));
$finder = $this->getMockBuilder(\Symfony\Component\Finder\Finder::class)
->disableOriginalConstructor()
->onlyMethods(['directories', 'depth', 'in', 'getIterator'])
->getMock();
$finder->expects($this->any())
->method('directories')
->willReturn($finder);
$finder->expects($this->any())
->method('depth')
->willReturn($finder);
$finder->expects($this->any())
->method('in')
->willReturn($finder);
$finder->expects($this->any())
->method('getIterator')
->willReturn(new \ArrayIterator([new \SplFileInfo('MyModule-1.0.1')]));
$this->container->registerProvider(new FinderProvider($finder));
$query = 'UPDATE modules_informations '
. 'SET `name` = :name , `rname` = :rname , `is_removeable` = :is_removeable , '
. '`infos` = :infos , `author` = :author , '
. '`svc_tools` = :svc_tools , `host_tools` = :host_tools WHERE id = :id';
$this->db->addResultSet(
$query,
[]
);
$this->db->addResultSet(
'SELECT MAX(id) as id FROM modules_informations',
[['id' => 1]]
);
$this->db->addResultSet(
'UPDATE modules_informations SET `mod_release` = :mod_release WHERE id = :id',
[]
);
$this->container->registerProvider(new ConfigurationDBProvider($this->db));
$upgrader = new Upgrader(new Container($this->container), $this->information, 'MyModule', $this->utils, 1);
$id = $upgrader->upgrade();
$this->assertEquals($id, 1);
}
public function mockExists($file)
{
return ! (preg_match('/install\.pre\.php/', $file));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/CentreonLegacy/Core/Configuration/ConfigurationTest.php | centreon/tests/php/CentreonLegacy/Core/Configuration/ConfigurationTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Configuration;
use CentreonLegacy\Core\Configuration;
use CentreonModule\Infrastructure\Source\ModuleSource;
use CentreonModule\Infrastructure\Source\WidgetSource;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Finder\Finder;
/**
* @group CentreonLegacy
* @group CentreonLegacy\Provider
*/
class ConfigurationTest extends TestCase
{
/** @var string[] */
public $configuration;
/** @var string */
public $centreonPath;
/** @var Configuration\Configuration */
public $service;
public function setUp(): void
{
$this->configuration = [
'opt1' => 'val1',
'opt2' => 'val2',
];
$this->centreonPath = 'path';
$this->service = new Configuration\Configuration($this->configuration, $this->centreonPath, new Finder());
}
public function testGet(): void
{
$key = 'opt1';
$value = $this->configuration[$key];
$result = $this->service->get($key);
$this->assertEquals($result, $value);
}
public function testGetWithCentreonPath(): void
{
$key = Configuration\Configuration::CENTREON_PATH;
$value = $this->centreonPath;
$result = $this->service->get($key);
$this->assertEquals($result, $value);
}
public function testGetModulePath(): void
{
$value = $this->centreonPath . ModuleSource::PATH;
$result = $this->service->getModulePath();
$this->assertEquals($result, $value);
}
public function testGetWidgetPath(): void
{
$value = $this->centreonPath . WidgetSource::PATH;
$result = $this->service->getWidgetPath();
$this->assertEquals($result, $value);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/CentreonLegacy/Core/Menu/MenuTest.php | centreon/tests/php/CentreonLegacy/Core/Menu/MenuTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Menu;
use Centreon\Test\Mock\CentreonDB;
class MenuTest extends \PHPUnit\Framework\TestCase
{
/** @var CentreonDB The database mock */
private $db;
public function setUp(): void
{
$this->db = new CentreonDB();
}
public function testGetGroups(): void
{
$this->db->addResultSet(
'SELECT topology_name, topology_parent, topology_group FROM topology WHERE topology_show = "1" AND topology_page IS NULL ORDER BY topology_group, topology_order',
[['topology_name' => 'By host', 'topology_parent' => 2, 'topology_group' => 201], ['topology_name' => 'By services', 'topology_parent' => 2, 'topology_group' => 202]]
);
$menu = new Menu($this->db);
$this->assertEquals(
$menu->getGroups(),
[2 => [201 => 'By host', 202 => 'By services']]
);
}
public function testGetColor(): void
{
$colorPageId3 = '#E4932C';
$menu = new Menu($this->db);
$this->assertEquals(
$menu->getColor(3),
$colorPageId3
);
}
public function testGetMenuLevelOne(): void
{
$result = ['p2' => ['label' => 'By host', 'menu_id' => 'By host', 'url' => 'centreon/20101', 'active' => false, 'color' => '#85B446', 'children' => [], 'options' => '&o=c', 'is_react' => 0]];
$this->db->addResultSet(
'SELECT topology_name, topology_parent, topology_group FROM topology WHERE topology_show = "1" AND topology_page IS NULL ORDER BY topology_group, topology_order',
[['topology_name' => 'By host', 'topology_parent' => '', 'topology_group' => 201]]
);
$this->db->addResultSet(
'SELECT topology_name, topology_page, topology_url, topology_url_opt, topology_group, topology_order, topology_parent, is_react FROM topology WHERE topology_show = "1" AND topology_page IS NOT NULL ORDER BY topology_parent, topology_group, topology_order, topology_page',
[['topology_name' => 'By host', 'topology_page' => 2, 'topology_url' => 'centreon/20101', 'topology_url_opt' => '&o=c', 'topology_parent' => '', 'topology_order' => 1, 'topology_group' => 201, 'is_react' => 0]]
);
$menu = new Menu($this->db);
$this->assertEquals(
$menu->getMenu(),
$result
);
}
public function testGetMenuLevelTwo(): void
{
$result = ['p2' => ['children' => ['_201' => ['label' => 'By host', 'url' => 'centreon/20101', 'active' => false, 'children' => [], 'options' => '&o=c', 'is_react' => 0]]]];
$this->db->addResultSet(
'SELECT topology_name, topology_parent, topology_group FROM topology WHERE topology_show = "1" AND topology_page IS NULL ORDER BY topology_group, topology_order',
[['topology_name' => 'By host', 'topology_parent' => 2, 'topology_group' => 201]]
);
$this->db->addResultSet(
'SELECT topology_name, topology_page, topology_url, topology_url_opt, topology_group, topology_order, topology_parent, is_react FROM topology WHERE topology_show = "1" AND topology_page IS NOT NULL ORDER BY topology_parent, topology_group, topology_order, topology_page',
[['topology_name' => 'By host', 'topology_page' => 201, 'topology_url' => 'centreon/20101', 'topology_url_opt' => '&o=c', 'topology_parent' => 2, 'topology_order' => 1, 'topology_group' => 201, 'is_react' => 0]]
);
$menu = new Menu($this->db);
$this->assertEquals(
$menu->getMenu(),
$result
);
}
public function testGetMenuLevelThree(): void
{
$result = ['p2' => ['children' => ['_201' => ['children' => ['Main Menu' => ['_20101' => ['label' => 'By host', 'url' => 'centreon/20101', 'active' => false, 'options' => '&o=c', 'is_react' => 0]]]]]]];
$this->db->addResultSet(
'SELECT topology_name, topology_parent, topology_group FROM topology WHERE topology_show = "1" AND topology_page IS NULL ORDER BY topology_group, topology_order',
[['topology_name' => 'By host', 'topology_parent' => 2, 'topology_group' => 201]]
);
$this->db->addResultSet(
'SELECT topology_name, topology_page, topology_url, topology_url_opt, topology_group, topology_order, topology_parent, is_react FROM topology WHERE topology_show = "1" AND topology_page IS NOT NULL ORDER BY topology_parent, topology_group, topology_order, topology_page',
[['topology_name' => 'By host', 'topology_page' => 20101, 'topology_url' => 'centreon/20101', 'topology_url_opt' => '&o=c', 'topology_parent' => 201, 'topology_order' => 1, 'topology_group' => 201, 'is_react' => 0]]
);
$menu = new Menu($this->db);
$this->assertEquals(
$menu->getMenu(),
$result
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/CentreonLegacy/Core/Widget/FactoryTest.php | centreon/tests/php/CentreonLegacy/Core/Widget/FactoryTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Widget;
use Centreon\Test\Mock\DependencyInjector\ServiceContainer;
use CentreonLegacy\ServiceProvider;
use Pimple\Container;
/**
* Class
*
* @class FactoryTest
* @package CentreonLegacy\Core\Widget
*/
class FactoryTest extends \PHPUnit\Framework\TestCase
{
/** @var ServiceContainer */
public $container;
public function setUp(): void
{
$this->container = new ServiceContainer();
$this->container[ServiceProvider::CENTREON_LEGACY_WIDGET_INFORMATION] = $this
->getMockBuilder(Information::class)
->disableOriginalConstructor()
->getMock();
$this->container[ServiceProvider::CENTREON_LEGACY_WIDGET_INSTALLER] = function (Container $container) {
return function ($widgetDirectory) {
return $this->getMockBuilder(Installer::class)
->disableOriginalConstructor()
->getMock();
};
};
$this->container[ServiceProvider::CENTREON_LEGACY_WIDGET_UPGRADER] = function (Container $container) {
return function ($widgetDirectory) {
return $this->getMockBuilder(Upgrader::class)
->disableOriginalConstructor()
->getMock();
};
};
$this->container[ServiceProvider::CENTREON_LEGACY_WIDGET_REMOVER] = function (Container $container) {
return function ($widgetDirectory) {
return $this->getMockBuilder(Remover::class)
->disableOriginalConstructor()
->getMock();
};
};
}
public function tearDown(): void
{
$this->container->terminate();
$this->container = null;
}
public function testNewInformation(): void
{
$factory = new Factory($this->container);
$this->assertInstanceOf(Information::class, $factory->newInformation());
}
public function testNewInstaller(): void
{
$factory = new Factory($this->container);
$this->assertInstanceOf(Installer::class, $factory->newInstaller('MyWidget'));
}
public function testNewUpgrader(): void
{
$factory = new Factory($this->container);
$this->assertInstanceOf(Upgrader::class, $factory->newUpgrader('MyWidget'));
}
public function testNewRemover(): void
{
$factory = new Factory($this->container);
$this->assertInstanceOf(Remover::class, $factory->newRemover('MyWidget'));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/CentreonLegacy/Core/Widget/InstallerTest.php | centreon/tests/php/CentreonLegacy/Core/Widget/InstallerTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Widget;
use Centreon\Test\Mock\CentreonDB;
use Centreon\Test\Mock\DependencyInjector\ConfigurationDBProvider;
use Centreon\Test\Mock\DependencyInjector\ServiceContainer;
use Pimple\Psr11\Container;
class InstallerTest extends \PHPUnit\Framework\TestCase
{
private $container;
private $db;
private $information;
private $utils;
public function setUp(): void
{
$this->container = new ServiceContainer();
$this->db = new CentreonDB();
$configuration = ['title' => 'My Widget', 'author' => 'Centreon', 'email' => 'contact@centreon.com', 'website' => 'http://www.centreon.com', 'description' => 'Widget for displaying host monitoring information', 'version' => '1.0.0', 'keywords' => 'centreon, widget, host, monitoring', 'screenshot' => '', 'thumbnail' => './widgets/host-monitoring/resources/centreon-logo.png', 'url' => './widgets/host-monitoring/index.php', 'directory' => 'my-widget', 'preferences' => ['preference' => [['@attributes' => ['label' => 'Host Name', 'name' => 'host_name_search', 'defaultValue' => '', 'type' => 'compare', 'header' => 'Filters']], ['@attributes' => ['label' => 'Results', 'name' => 'entries', 'defaultValue' => '10', 'type' => 'range', 'min' => '10', 'max' => '100', 'step' => '10']], ['@attributes' => ['label' => 'Order By', 'name' => 'order_by', 'defaultValue' => '', 'type' => 'sort'], 'option' => [['@attributes' => ['value' => 'h.name', 'label' => 'Host Name']], ['@attributes' => ['value' => 'criticality', 'label' => 'Severity']]]]]], 'autoRefresh' => 0];
$this->information = $this->getMockBuilder(Information::class)
->disableOriginalConstructor()
->onlyMethods(['getConfiguration', 'getTypes', 'isInstalled', 'getIdByName', 'getParameterIdByName'])
->getMock();
$this->information->expects($this->any())
->method('getConfiguration')
->willReturn($configuration);
$this->information->expects($this->any())
->method('getTypes')
->willReturn(
['compare' => ['id' => 1, 'name' => 'compare'], 'range' => ['id' => 2, 'name' => 'range'], 'sort' => ['id' => 3, 'name' => 'sort']]
);
$this->information->expects($this->any())
->method('isInstalled')
->willReturn(false);
$this->information->expects($this->any())
->method('getIdByName')
->willReturn(1);
$this->information->expects($this->any())
->method('getParameterIdByName')
->willReturn(1);
$this->utils = $this->getMockBuilder(\CentreonLegacy\Core\Utils\Utils::class)
->disableOriginalConstructor()
->getMock();
}
public function tearDown(): void
{
$this->container->terminate();
$this->container = null;
}
public function testInstall(): void
{
$query = 'INSERT INTO widget_models '
. '(title, description, url, version, is_internal, directory, author, '
. 'email, website, keywords, thumbnail, autoRefresh) '
. 'VALUES (:title, :description, :url, :version, :is_internal, :directory, :author, '
. ':email, :website, :keywords, :thumbnail, :autoRefresh) ';
$this->db->addResultSet(
$query,
[]
);
$query = 'INSERT INTO widget_parameters '
. '(widget_model_id, field_type_id, parameter_name, parameter_code_name, '
. 'default_value, parameter_order, require_permission, header_title) '
. 'VALUES '
. '(:widget_model_id, :field_type_id, :parameter_name, :parameter_code_name, '
. ':default_value, :parameter_order, :require_permission, :header_title) ';
$this->db->addResultSet(
$query,
[]
);
$query = 'INSERT INTO widget_parameters_multiple_options '
. '(parameter_id, option_name, option_value) VALUES '
. '(:parameter_id, :option_name, :option_value) ';
$this->db->addResultSet(
$query,
[]
);
$query = 'INSERT INTO widget_parameters_range (parameter_id, min_range, max_range, step) '
. 'VALUES (:parameter_id, :min_range, :max_range, :step) ';
$this->db->addResultSet(
$query,
[]
);
$this->container->registerProvider(new ConfigurationDBProvider($this->db));
$this->utils->expects($this->any())
->method('buildPath')
->willReturn('MyWidget');
$installer = new Installer(new Container($this->container), $this->information, 'MyWidget', $this->utils);
$id = $installer->install();
$this->assertEquals($id, 1);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/CentreonLegacy/Core/Widget/RemoverTest.php | centreon/tests/php/CentreonLegacy/Core/Widget/RemoverTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Widget;
use Centreon\Test\Mock\CentreonDB;
use Centreon\Test\Mock\DependencyInjector\ConfigurationDBProvider;
use Centreon\Test\Mock\DependencyInjector\ServiceContainer;
use Pimple\Psr11\Container;
class RemoverTest extends \PHPUnit\Framework\TestCase
{
private $container;
private $db;
private $information;
private $utils;
public function setUp(): void
{
$this->container = new ServiceContainer();
$this->db = new CentreonDB();
$configuration = ['title' => 'My Widget', 'author' => 'Centreon', 'email' => 'contact@centreon.com', 'website' => 'http://www.centreon.com', 'description' => 'Widget for displaying host monitoring information', 'version' => '1.0.0', 'keywords' => 'centreon, widget, host, monitoring', 'screenshot' => '', 'thumbnail' => './widgets/host-monitoring/resources/centreon-logo.png', 'url' => './widgets/host-monitoring/index.php', 'preferences' => ['preference' => [['@attributes' => ['label' => 'Host Name', 'name' => 'host_name_search', 'defaultValue' => '', 'type' => 'compare', 'header' => 'Filters']], ['@attributes' => ['label' => 'Results', 'name' => 'entries', 'defaultValue' => '10', 'type' => 'range', 'min' => '10', 'max' => '100', 'step' => '10']], ['@attributes' => ['label' => 'Order By', 'name' => 'order_by', 'defaultValue' => '', 'type' => 'sort'], 'option' => [['@attributes' => ['value' => 'h.name', 'label' => 'Host Name']], ['@attributes' => ['value' => 'criticality', 'label' => 'Severity']]]]]], 'autoRefresh' => 0];
$this->information = $this->getMockBuilder(Information::class)
->disableOriginalConstructor()
->onlyMethods(['getConfiguration', 'getTypes', 'isInstalled', 'getIdByName', 'getParameterIdByName'])
->getMock();
$this->information->expects($this->any())
->method('getConfiguration')
->willReturn($configuration);
$this->information->expects($this->any())
->method('getTypes')
->willReturn(
['compare' => ['id' => 1, 'name' => 'compare'], 'range' => ['id' => 2, 'name' => 'range'], 'sort' => ['id' => 3, 'name' => 'sort']]
);
$this->information->expects($this->any())
->method('isInstalled')
->willReturn(false);
$this->information->expects($this->any())
->method('getIdByName')
->willReturn(1);
$this->information->expects($this->any())
->method('getParameterIdByName')
->willReturn(1);
$this->utils = $this->getMockBuilder(\CentreonLegacy\Core\Utils\Utils::class)
->disableOriginalConstructor()
->getMock();
}
public function tearDown(): void
{
$this->container->terminate();
$this->container = null;
}
public function testRemove(): void
{
$query = 'DELETE FROM widget_models '
. 'WHERE directory = :directory '
. 'AND is_internal = FALSE ';
$this->db->addResultSet(
$query,
[]
);
$this->container->registerProvider(new ConfigurationDBProvider($this->db));
$remover = new Remover(new Container($this->container), $this->information, 'MyWidget', $this->utils);
$removed = $remover->remove();
$this->assertEquals($removed, true);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/CentreonLegacy/Core/Widget/InformationTest.php | centreon/tests/php/CentreonLegacy/Core/Widget/InformationTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Widget;
use Centreon\Test\Mock\CentreonDB;
use Centreon\Test\Mock\DependencyInjector\ConfigurationDBProvider;
use Centreon\Test\Mock\DependencyInjector\FilesystemProvider;
use Centreon\Test\Mock\DependencyInjector\FinderProvider;
use Centreon\Test\Mock\DependencyInjector\ServiceContainer;
use Pimple\Psr11\Container;
class InformationTest extends \PHPUnit\Framework\TestCase
{
private $container;
private $db;
private $utils;
private $configuration;
public function setUp(): void
{
$this->container = new ServiceContainer();
$this->db = new CentreonDB();
$this->utils = $this->getMockBuilder(\CentreonLegacy\Core\Utils\Utils::class)
->disableOriginalConstructor()
->getMock();
$this->configuration = ['title' => 'My Widget', 'author' => 'Centreon', 'email' => 'contact@centreon.com', 'website' => 'http://www.centreon.com', 'description' => 'Widget for displaying host monitoring information', 'version' => '1.0.0', 'keywords' => 'centreon, widget, host, monitoring', 'screenshot' => '', 'thumbnail' => './widgets/host-monitoring/resources/centreon-logo.png', 'url' => './widgets/host-monitoring/index.php', 'directory' => 'my-widget', 'preferences' => ['preference' => [['@attributes' => ['label' => 'Host Name', 'name' => 'host_name_search', 'defaultValue' => '', 'type' => 'compare', 'header' => 'Filters']]]]];
}
public function tearDown(): void
{
$this->container->terminate();
$this->container = null;
}
public function testGetConfiguration(): void
{
$expectedResult = $this->configuration;
$expectedResult['autoRefresh'] = 0;
$filesystem = $this->getMockBuilder(\Symfony\Component\Filesystem\Filesystem::class)
->disableOriginalConstructor()
->onlyMethods(['exists'])
->getMock();
$filesystem->expects($this->any())
->method('exists')
->willReturn(true);
$this->container->registerProvider(new FilesystemProvider($filesystem));
$this->utils->expects($this->any())
->method('buildPath')
->willReturn('MyWidget');
$this->utils->expects($this->any())
->method('xmlIntoArray')
->willReturn($this->configuration);
$information = new Information(new Container($this->container), $this->utils);
$configuration = $information->getConfiguration('my-widget');
$this->assertEquals($configuration, $expectedResult);
}
public function testGetTypes(): void
{
$expectedResult = ['type1' => ['id' => 1, 'name' => 'type1']];
$query = 'SELECT ft_typename, field_type_id '
. 'FROM widget_parameters_field_type ';
$this->db->addResultSet(
$query,
[['ft_typename' => 'type1', 'field_type_id' => 1]]
);
$this->container->registerProvider(new ConfigurationDBProvider($this->db));
$information = new Information(new Container($this->container), $this->utils);
$types = $information->getTypes();
$this->assertEquals($types, $expectedResult);
}
public function testGetParameterIdByName(): void
{
$query = 'SELECT parameter_id '
. 'FROM widget_parameters '
. 'WHERE parameter_code_name = :name ';
$this->db->addResultSet(
$query,
[['parameter_id' => 1]]
);
$this->container->registerProvider(new ConfigurationDBProvider($this->db));
$information = new Information(new Container($this->container), $this->utils);
$id = $information->getParameterIdByName('MyWidget');
$this->assertEquals($id, 1);
}
public function testGetParameters(): void
{
$expectedResult = ['parameter1' => ['parameter_id' => 1, 'parameter_name' => 'parameter 1', 'parameter_code_name' => 'parameter1', 'default_value' => '', 'parameter_order' => 1, 'header_title' => 'title', 'require_permission' => null, 'widget_model_id' => 1, 'field_type_id' => 1]];
$query = 'SELECT * '
. 'FROM widget_parameters '
. 'WHERE widget_model_id = :id ';
$this->db->addResultSet(
$query,
[['parameter_id' => 1, 'parameter_name' => 'parameter 1', 'parameter_code_name' => 'parameter1', 'default_value' => '', 'parameter_order' => 1, 'header_title' => 'title', 'require_permission' => null, 'widget_model_id' => 1, 'field_type_id' => 1]]
);
$this->container->registerProvider(new ConfigurationDBProvider($this->db));
$information = new Information(new Container($this->container), $this->utils);
$parameters = $information->getParameters(1);
$this->assertEquals($parameters, $expectedResult);
}
public function testGetIdByName(): void
{
$query = 'SELECT widget_model_id '
. 'FROM widget_models '
. 'WHERE directory = :directory';
$this->db->addResultSet(
$query,
[['widget_model_id' => 1]]
);
$this->container->registerProvider(new ConfigurationDBProvider($this->db));
$information = new Information(new Container($this->container), $this->utils);
$id = $information->getIdByName('MyWidget');
$this->assertEquals($id, 1);
}
public function testGetAvailableList(): void
{
$configuration = $this->configuration;
$configuration['autoRefresh'] = 0;
$expectedResult = ['my-widget' => $configuration];
$finder = $this->getMockBuilder(\Symfony\Component\Finder\Finder::class)
->disableOriginalConstructor()
->onlyMethods(['directories', 'depth', 'in', 'getIterator'])
->getMock();
$finder->expects($this->any())
->method('directories')
->willReturn($finder);
$finder->expects($this->any())
->method('depth')
->willReturn($finder);
$finder->expects($this->any())
->method('in')
->willReturn($finder);
$finder->expects($this->any())
->method('getIterator')
->willReturn(new \ArrayIterator([new \SplFileInfo('my-widget')]));
$this->container->registerProvider(new FinderProvider($finder));
$filesystem = $this->getMockBuilder(\Symfony\Component\Filesystem\Filesystem::class)
->disableOriginalConstructor()
->onlyMethods(['exists'])
->getMock();
$filesystem->expects($this->any())
->method('exists')
->willReturn(true);
$this->container->registerProvider(new FilesystemProvider($filesystem));
$this->utils->expects($this->any())
->method('buildPath')
->willReturn('MyWidget');
$this->utils->expects($this->any())
->method('xmlIntoArray')
->willReturn($this->configuration);
$information = new Information(new Container($this->container), $this->utils);
$list = $information->getAvailableList();
$this->assertEquals($list, $expectedResult);
}
public function testGetList(): void
{
$configuration = $this->configuration;
$configuration['autoRefresh'] = 0;
$configuration['source_available'] = true;
$configuration['is_installed'] = true;
$configuration['upgradeable'] = false;
$configuration['installed_version'] = '1.0.0';
$configuration['available_version'] = '1.0.0';
$configuration['id'] = 1;
unset($configuration['version']);
$expectedResult = ['my-widget' => $configuration];
$this->db->addResultSet(
'SELECT * FROM widget_models ',
[['widget_model_id' => 1, 'title' => 'my title', 'description' => 'my description', 'url' => '', 'version' => '1.0.0', 'is_internal' => 0, 'directory' => 'my-widget', 'author' => 'phpunit', 'email' => 'root@localhost', 'website' => 'centreon.com', 'keywords' => 'centreon', 'screenshot' => null, 'thumbnail' => '', 'autoRefresh' => 0]]
);
$this->container->registerProvider(new ConfigurationDBProvider($this->db));
$this->utils->expects($this->any())
->method('buildPath')
->willReturn('MyWidget');
$finder = $this->getMockBuilder(\Symfony\Component\Finder\Finder::class)
->disableOriginalConstructor()
->onlyMethods(['directories', 'depth', 'in', 'getIterator'])
->getMock();
$finder->expects($this->any())
->method('directories')
->willReturn($finder);
$finder->expects($this->any())
->method('depth')
->willReturn($finder);
$finder->expects($this->any())
->method('in')
->willReturn($finder);
$finder->expects($this->any())
->method('getIterator')
->willReturn(new \ArrayIterator([new \SplFileInfo('my-widget')]));
$this->container->registerProvider(new FinderProvider($finder));
$filesystem = $this->getMockBuilder(\Symfony\Component\Filesystem\Filesystem::class)
->disableOriginalConstructor()
->onlyMethods(['exists'])
->getMock();
$filesystem->expects($this->any())
->method('exists')
->willReturn(true);
$this->container->registerProvider(new FilesystemProvider($filesystem));
$this->utils->expects($this->any())
->method('xmlIntoArray')
->willReturn($this->configuration);
$information = new Information(new Container($this->container), $this->utils);
$list = $information->getList();
$this->assertEquals($list, $expectedResult);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/CentreonLegacy/Core/Widget/WidgetTest.php | centreon/tests/php/CentreonLegacy/Core/Widget/WidgetTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Widget;
use Centreon\Test\Mock\CentreonDB;
use Centreon\Test\Mock\DependencyInjector\ServiceContainer;
use Pimple\Psr11\Container;
class WidgetTest extends \PHPUnit\Framework\TestCase
{
private $container;
private $db;
private $information;
private $utils;
public function setUp(): void
{
$this->container = new ServiceContainer();
$this->db = new CentreonDB();
$configuration = ['title' => 'My Widget', 'author' => 'Centreon', 'email' => 'contact@centreon.com', 'website' => 'http://www.centreon.com', 'description' => 'Widget for displaying host monitoring information', 'version' => '1.0.0', 'keywords' => 'centreon, widget, host, monitoring', 'screenshot' => '', 'thumbnail' => './widgets/host-monitoring/resources/centreon-logo.png', 'url' => './widgets/host-monitoring/index.php', 'preferences' => ['preference' => [['@attributes' => ['label' => 'Host Name', 'name' => 'host_name_search', 'defaultValue' => '', 'type' => 'compare', 'header' => 'Filters']], ['@attributes' => ['label' => 'Results', 'name' => 'entries', 'defaultValue' => '10', 'type' => 'range', 'min' => '10', 'max' => '100', 'step' => '10']], ['@attributes' => ['label' => 'Order By', 'name' => 'order_by', 'defaultValue' => '', 'type' => 'sort'], 'option' => [['@attributes' => ['value' => 'h.name', 'label' => 'Host Name']], ['@attributes' => ['value' => 'criticality', 'label' => 'Severity']]]]]], 'autoRefresh' => 0];
$this->information = $this->getMockBuilder(Information::class)
->disableOriginalConstructor()
->onlyMethods(['getConfiguration'])
->getMock();
$this->information->expects($this->any())
->method('getConfiguration')
->willReturn($configuration);
$this->utils = $this->getMockBuilder(\CentreonLegacy\Core\Utils\Utils::class)
->disableOriginalConstructor()
->onlyMethods(['buildPath'])
->getMock();
$this->utils->expects($this->any())
->method('buildPath')
->willReturn('/');
}
public function tearDown(): void
{
$this->container->terminate();
$this->container = null;
}
public function testGetWidgetPath(): void
{
$widget = new Widget(new Container($this->container), $this->information, 'MyWidget', $this->utils);
$path = $widget->getWidgetPath('MyWidget');
$this->assertEquals($path, '/');
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/CentreonLegacy/Core/Widget/UpgraderTest.php | centreon/tests/php/CentreonLegacy/Core/Widget/UpgraderTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Widget;
use Centreon\Test\Mock\CentreonDB;
use Centreon\Test\Mock\DependencyInjector\ConfigurationDBProvider;
use Centreon\Test\Mock\DependencyInjector\ServiceContainer;
use Pimple\Psr11\Container;
class UpgraderTest extends \PHPUnit\Framework\TestCase
{
private $container;
private $db;
private $information;
private $utils;
public function setUp(): void
{
$this->container = new ServiceContainer();
$this->db = new CentreonDB();
$configuration = ['title' => 'My Widget', 'author' => 'Centreon', 'email' => 'contact@centreon.com', 'website' => 'http://www.centreon.com', 'description' => 'Widget for displaying host monitoring information', 'version' => '1.0.0', 'keywords' => 'centreon, widget, host, monitoring', 'screenshot' => '', 'thumbnail' => './widgets/host-monitoring/resources/centreon-logo.png', 'url' => './widgets/host-monitoring/index.php', 'directory' => 'my-widget', 'preferences' => ['preference' => [['@attributes' => ['label' => 'Host Name', 'name' => 'host_name_search', 'defaultValue' => '', 'type' => 'compare', 'header' => 'Filters']], ['@attributes' => ['label' => 'Results', 'name' => 'entries', 'defaultValue' => '10', 'type' => 'range', 'min' => '10', 'max' => '100', 'step' => '10']], ['@attributes' => ['label' => 'Order By', 'name' => 'order_by', 'defaultValue' => '', 'type' => 'sort'], 'option' => [['@attributes' => ['value' => 'h.name', 'label' => 'Host Name']], ['@attributes' => ['value' => 'criticality', 'label' => 'Severity']]]]]], 'autoRefresh' => 0];
$this->information = $this->getMockBuilder(Information::class)
->disableOriginalConstructor()
->onlyMethods(
['getConfiguration', 'getTypes', 'getParameters', 'isInstalled', 'getIdByName', 'getParameterIdByName']
)
->getMock();
$this->information->expects($this->any())
->method('getConfiguration')
->willReturn($configuration);
$this->information->expects($this->any())
->method('getTypes')
->willReturn(
['compare' => ['id' => 1, 'name' => 'compare'], 'range' => ['id' => 2, 'name' => 'range'], 'sort' => ['id' => 3, 'name' => 'sort']]
);
$this->information->expects($this->any())
->method('getParameters')
->willReturn(
['entries' => ['parameter_id' => 2, 'parameter_name' => 'entries', 'parameter_code_name' => 'entries', 'default_value' => '', 'parameter_order' => 1, 'header_title' => 'title', 'require_permission' => null, 'widget_model_id' => 1, 'field_type_id' => 2], 'order_by' => ['parameter_id' => 3, 'parameter_name' => 'Order By', 'parameter_code_name' => 'order_by', 'default_value' => '', 'parameter_order' => 1, 'header_title' => 'title', 'require_permission' => null, 'widget_model_id' => 1, 'field_type_id' => 3]]
);
$this->information->expects($this->any())
->method('isInstalled')
->willReturn(true);
$this->information->expects($this->any())
->method('getIdByName')
->willReturn(1);
$this->information->expects($this->any())
->method('getParameterIdByName')
->willReturn(1);
$this->utils = $this->getMockBuilder(\CentreonLegacy\Core\Utils\Utils::class)
->disableOriginalConstructor()
->getMock();
}
public function tearDown(): void
{
$this->container->terminate();
$this->container = null;
}
public function testUpgrade(): void
{
$query = 'UPDATE widget_models SET '
. 'title = :title, '
. 'description = :description, '
. 'url = :url, '
. 'version = :version, '
. 'author = :author, '
. 'email = :email, '
. 'website = :website, '
. 'keywords = :keywords, '
. 'thumbnail = :thumbnail, '
. 'autoRefresh = :autoRefresh '
. 'WHERE directory = :directory ';
$this->db->addResultSet(
$query,
[]
);
$query = 'DELETE FROM widget_parameters '
. 'WHERE parameter_id = :id ';
$this->db->addResultSet(
$query,
[]
);
$query = 'INSERT INTO widget_parameters '
. '(widget_model_id, field_type_id, parameter_name, parameter_code_name, '
. 'default_value, parameter_order, require_permission, header_title) '
. 'VALUES '
. '(:widget_model_id, :field_type_id, :parameter_name, :parameter_code_name, '
. ':default_value, :parameter_order, :require_permission, :header_title) ';
$this->db->addResultSet(
$query,
[]
);
$query = 'INSERT INTO widget_parameters_multiple_options '
. '(parameter_id, option_name, option_value) VALUES '
. '(:parameter_id, :option_name, :option_value) ';
$this->db->addResultSet(
$query,
[]
);
$query = 'INSERT INTO widget_parameters_range (parameter_id, min_range, max_range, step) '
. 'VALUES (:parameter_id, :min_range, :max_range, :step) ';
$this->db->addResultSet(
$query,
[]
);
$query = 'UPDATE widget_parameters SET '
. 'field_type_id = :field_type_id, '
. 'parameter_name = :parameter_name, '
. 'default_value = :default_value, '
. 'parameter_order = :parameter_order, '
. 'require_permission = :require_permission, '
. 'header_title = :header_title '
. 'WHERE widget_model_id = :widget_model_id '
. 'AND parameter_code_name = :parameter_code_name ';
$this->db->addResultSet(
$query,
[]
);
$query = 'DELETE FROM widget_parameters_multiple_options '
. 'WHERE parameter_id = :id ';
$this->db->addResultSet(
$query,
[]
);
$query = 'DELETE FROM widget_parameters_range '
. 'WHERE parameter_id = :id ';
$this->db->addResultSet(
$query,
[]
);
$this->container->registerProvider(new ConfigurationDBProvider($this->db));
$this->utils->expects($this->any())
->method('buildPath')
->willReturn('MyWidget');
$this->container->registerProvider(new ConfigurationDBProvider($this->db));
$installer = new Upgrader(new Container($this->container), $this->information, 'MyWidget', $this->utils);
$upgraded = $installer->upgrade();
$this->assertEquals($upgraded, true);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Utility/SqlConcatenatorTest.php | centreon/tests/php/Utility/SqlConcatenatorTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Utility;
use Utility\SqlConcatenator;
beforeEach(function (): void {
$this->concat = new SqlConcatenator();
$this->executePrivateTrimPrefix = static function (string $prefix, string|\Stringable ...$values): array {
$builder = new SqlConcatenator();
$reflectionClass = new \ReflectionClass($builder);
$method = $reflectionClass->getMethod('trimPrefix');
$method->setAccessible(true);
return $method->invoke($builder, $prefix, ...$values);
};
$this->stringable = static function (string $string): \Stringable {
return new class ($string) implements \Stringable {
public function __construct(public string $string)
{
}
public function __toString(): string
{
return $this->string;
}
};
};
});
// ---------- string concatenation ----------
it('should concat a string for select', function (): void {
expect($this->concat->appendSelect('abc', 'def')->concatAll())
->toBe('SELECT abc, def');
});
it('should concat a string for from', function (): void {
expect($this->concat->defineFrom('xyz')->concatAll())
->toBe('FROM xyz');
});
it('should concat a string for joins', function (): void {
expect($this->concat->appendJoins('abc', 'def')->concatAll())
->toBe('abc def');
});
it('should concat a string for where', function (): void {
expect($this->concat->appendWhere('abc', 'def')->concatAll())
->toBe('WHERE abc AND def');
});
it('should concat a string for group by', function (): void {
expect($this->concat->appendGroupBy('abc', 'def')->concatAll())
->toBe('GROUP BY abc, def');
});
it('should concat a string for having', function (): void {
expect($this->concat->appendHaving('abc', 'def')->concatAll())
->toBe('HAVING abc AND def');
});
it('should concat a string for order by', function (): void {
expect($this->concat->appendOrderBy('abc', 'def')->concatAll())
->toBe('ORDER BY abc, def');
});
it('should concat a string for limit', function (): void {
expect($this->concat->defineLimit('xyz')->concatAll())
->toBe('LIMIT xyz');
});
// ---------- stringable concatenation ----------
it('should concat a Stringable for select', function (): void {
expect($this->concat->appendSelect('abc', ($this->stringable)('def'))->concatAll())
->toBe('SELECT abc, def');
});
it('should concat a Stringable for from', function (): void {
expect($this->concat->defineFrom(($this->stringable)('xyz'))->concatAll())
->toBe('FROM xyz');
});
it('should concat a Stringable for joins', function (): void {
expect($this->concat->appendJoins('abc', ($this->stringable)('def'))->concatAll())
->toBe('abc def');
});
it('should concat a Stringable for where', function (): void {
expect($this->concat->appendWhere('abc', ($this->stringable)('def'))->concatAll())
->toBe('WHERE abc AND def');
});
it('should concat a Stringable for group by', function (): void {
expect($this->concat->appendGroupBy('abc', ($this->stringable)('def'))->concatAll())
->toBe('GROUP BY abc, def');
});
it('should concat a Stringable for having', function (): void {
expect($this->concat->appendHaving('abc', ($this->stringable)('def'))->concatAll())
->toBe('HAVING abc AND def');
});
it('should concat a Stringable for order by', function (): void {
expect($this->concat->appendOrderBy('abc', ($this->stringable)('def'))->concatAll())
->toBe('ORDER BY abc, def');
});
it('should concat a Stringable for limit', function (): void {
expect($this->concat->defineLimit(($this->stringable)('xyz'))->concatAll())
->toBe('LIMIT xyz');
});
// ---------- other concatenation ----------
it('should concat all together', function (): void {
expect(
$this->concat
->appendSelect('s1', ($this->stringable)('s2'))
->defineFrom('t1')
->appendJoins('j1', ($this->stringable)('j2'))
->appendWhere('w1', ($this->stringable)('w2'))
->appendGroupBy('g1', ($this->stringable)('g2'))
->appendHaving('h1', ($this->stringable)('h2'))
->appendOrderBy('o1', ($this->stringable)('o2'))
->defineLimit('l1')
->concatAll()
)->toBe(
'SELECT s1, s2 FROM t1 j1 j2 WHERE w1 AND w2 GROUP BY g1, g2 HAVING h1 AND h2 ORDER BY o1, o2 LIMIT l1'
);
});
// ---------- no Stringable cast before the final concatenation ----------
it('should not cast Stringable to string before the final concatenation for select', function (): void {
$stringable = ($this->stringable)('init_value_for_stringable');
$this->concat->appendSelect($stringable);
$stringable->string = 'updated';
expect($this->concat->concatAll())->toBe('SELECT updated');
});
it('should not cast Stringable to string before the final concatenation for from', function (): void {
$stringable = ($this->stringable)('init_value_for_stringable');
$this->concat->defineFrom($stringable);
$stringable->string = 'updated';
expect($this->concat->concatAll())->toBe('FROM updated');
});
it('should not cast Stringable to string before the final concatenation for joins', function (): void {
$stringable = ($this->stringable)('init_value_for_stringable');
$this->concat->appendJoins($stringable);
$stringable->string = 'updated';
expect($this->concat->concatAll())->toBe('updated');
});
it('should not cast Stringable to string before the final concatenation for where', function (): void {
$stringable = ($this->stringable)('init_value_for_stringable');
$this->concat->appendWhere($stringable);
$stringable->string = 'updated';
expect($this->concat->concatAll())->toBe('WHERE updated');
});
it('should not cast Stringable to string before the final concatenation for group by', function (): void {
$stringable = ($this->stringable)('init_value_for_stringable');
$this->concat->appendGroupBy($stringable);
$stringable->string = 'updated';
expect($this->concat->concatAll())->toBe('GROUP BY updated');
});
it('should not cast Stringable to string before the final concatenation for having', function (): void {
$stringable = ($this->stringable)('init_value_for_stringable');
$this->concat->appendHaving($stringable);
$stringable->string = 'updated';
expect($this->concat->concatAll())->toBe('HAVING updated');
});
it('should not cast Stringable to string before the final concatenation for order by', function (): void {
$stringable = ($this->stringable)('init_value_for_stringable');
$this->concat->appendOrderBy($stringable);
$stringable->string = 'updated';
expect($this->concat->concatAll())->toBe('ORDER BY updated');
});
it('should not cast Stringable to string before the final concatenation for limit', function (): void {
$stringable = ($this->stringable)('init_value_for_stringable');
$this->concat->defineLimit($stringable);
$stringable->string = 'updated';
expect($this->concat->concatAll())->toBe('LIMIT updated');
});
// ---------- trim prefix features ----------
it('should trim an already present prefix for select', function (): void {
expect($this->concat->appendSelect('SELECT abc', 'select def')->concatAll())
->toBe('SELECT abc, def');
});
it('should trim an already present prefix for from', function (): void {
expect($this->concat->defineFrom('FROM xyz')->concatAll())
->toBe('FROM xyz');
});
it('should trim an already present prefix for where', function (): void {
expect($this->concat->appendWhere('WHERE abc', 'where def')->concatAll())
->toBe('WHERE abc AND def');
});
it('should trim an already present prefix for group by', function (): void {
expect($this->concat->appendGroupBy('GROUP BY abc', 'group by def')->concatAll())
->toBe('GROUP BY abc, def');
});
it('should trim an already present prefix for having', function (): void {
expect($this->concat->appendHaving('HAVING abc', 'having def')->concatAll())
->toBe('HAVING abc AND def');
});
it('should trim an already present prefix for order by', function (): void {
expect($this->concat->appendOrderBy('ORDER BY abc', 'order by def')->concatAll())
->toBe('ORDER BY abc, def');
});
it('should trim an already present prefix for limit', function (): void {
expect($this->concat->defineLimit('LIMIT xyz')->concatAll())
->toBe('LIMIT xyz');
});
it('should trim a prefix case insensitive', function (): void {
expect(($this->executePrivateTrimPrefix)('PREFIX', 'pReFix abc'))
->toBe(['abc']);
});
it('should trim a prefix with surrounding spaces', function (): void {
expect(($this->executePrivateTrimPrefix)('PREFIX', ' PREFIX abc'))
->toBe(['abc']);
});
it('should remove empty strings while trimming arguments', function (): void {
expect(($this->executePrivateTrimPrefix)('PREFIX', 'abc', '', '0', 'def'))
->toBe(['abc', '0', 'def']);
});
it('should ignore Stringables while trimming arguments', function (): void {
expect(($this->executePrivateTrimPrefix)('PREFIX', $stringable = ($this->stringable)('a string')))
->toBe([$stringable]);
});
// ---------- select modifiers ----------
it('should add select modifiers when asked', function (): void {
expect(
$this->concat
->withNoCache(true)
->withCalcFoundRows(true)
->appendSelect('hello')
->concatAll()
)->toBe(
'SELECT SQL_NO_CACHE SQL_CALC_FOUND_ROWS hello'
);
});
// ---------- storing bind values feature ----------
it('should store simple bind values and clear them', function (): void {
$this->concat
->storeBindValue(':defg', '456', \PDO::PARAM_STR)
->storeBindValue(':abc', 123, \PDO::PARAM_INT);
expect($this->concat->retrieveBindValues())
->toBe(
[
':defg' => ['456', \PDO::PARAM_STR],
':abc' => [123, \PDO::PARAM_INT],
]
);
$this->concat->clearBindValues();
expect($this->concat->retrieveBindValues())->toBeArray()->toBeEmpty();
});
it('should store multiple bind values', function (): void {
$this->concat
->storeBindValue(':defg', '456', \PDO::PARAM_STR)
->storeBindValueMultiple('array', [7, 6, 5], \PDO::PARAM_INT);
expect($this->concat->retrieveBindValues())
->toBe(
[
':defg' => ['456', \PDO::PARAM_STR],
':array_1' => [7, \PDO::PARAM_INT],
':array_2' => [6, \PDO::PARAM_INT],
':array_3' => [5, \PDO::PARAM_INT],
]
);
});
it('should prefix a colon in bind value names when not set', function (): void {
$this->concat
->storeBindValue('simple_without_colon', 1, \PDO::PARAM_INT)
->storeBindValue(':simple_with_colon', 2, \PDO::PARAM_INT)
->storeBindValueMultiple('multiple_without_colon', [10, 20], \PDO::PARAM_INT)
->storeBindValueMultiple(':multiple_with_colon', [30, 40], \PDO::PARAM_INT);
expect($this->concat->retrieveBindValues())
->toBe(
[
':simple_without_colon' => [1, \PDO::PARAM_INT],
':simple_with_colon' => [2, \PDO::PARAM_INT],
':multiple_without_colon_1' => [10, \PDO::PARAM_INT],
':multiple_without_colon_2' => [20, \PDO::PARAM_INT],
':multiple_with_colon_1' => [30, \PDO::PARAM_INT],
':multiple_with_colon_2' => [40, \PDO::PARAM_INT],
]
);
});
it('should replace a multiple bind value name at any place in the final concat', function (): void {
$param = ':array';
$replaced = ':array_1, :array_2, :array_3';
$this->concat
->storeBindValueMultiple($param, [7, 6, 5], \PDO::PARAM_INT)
->appendSelect("This is totaly nonsense but why not ? {$param}")
->defineFrom("Remember this is a stupid string concatenator {$param}")
->appendJoins($param)
->appendWhere("field IN ({$param})")
->appendGroupBy($param)
->appendOrderBy($param)
->appendHaving($param)
->defineLimit($param);
expect($this->concat->concatAll())
->toBe(
"SELECT This is totaly nonsense but why not ? {$replaced}"
. " FROM Remember this is a stupid string concatenator {$replaced}"
. " {$replaced}"
. " WHERE field IN ({$replaced})"
. " GROUP BY {$replaced}"
. " HAVING {$replaced}"
. " ORDER BY {$replaced}"
. " LIMIT {$replaced}"
);
});
it('should replace a multiple bind value name taking into account only the word', function (): void {
$param = ':array';
$replaced = ':array_1, :array_2, :array_3';
$this->concat
->storeBindValueMultiple($param, [7, 6, 5], \PDO::PARAM_INT)
->appendWhere("field IN ({$param}) AND 42 = {$param}_not_replaced");
expect($this->concat->concatAll())
->toBe("WHERE field IN ({$replaced}) AND 42 = {$param}_not_replaced");
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Utility/EnvironmentFileManagerTest.php | centreon/tests/php/Utility/EnvironmentFileManagerTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Utility;
use Utility\EnvironmentFileManager;
it('should add variable and format then correctly', function ($send, $expected): void {
$env = new EnvironmentFileManager('');
$env->add($send['key'], $send['value']);
$var = $env->getAll();
expect($expected['key'])
->toBe(key($var))
->and($var[$expected['key']])
->toBe($expected['value']);
})->with([
// The first table contains all the data to be tested, the second contains the data to be expected.
// Test with TRUE values
[['key' => 'key', 'value' => true], ['key' => 'key', 'value' => true]],
[['key' => 'key', 'value' => 'true'], ['key' => 'key', 'value' => true]],
[['key' => 'IS_VALID', 'value' => 1], ['key' => 'IS_VALID', 'value' => true]],
[['key' => 'IS_VALID', 'value' => '1'], ['key' => 'IS_VALID', 'value' => true]],
// Test with FALSE values
[['key' => 'key', 'value' => false], ['key' => 'key', 'value' => false]],
[['key' => 'key', 'value' => 'false'], ['key' => 'key', 'value' => false]],
[['key' => 'IS_VALID', 'value' => 0], ['key' => 'IS_VALID', 'value' => false]],
[['key' => 'IS_VALID', 'value' => '0'], ['key' => 'IS_VALID', 'value' => false]],
// Test with numerical values
[['key' => 'key', 'value' => 0], ['key' => 'key', 'value' => 0]],
[['key' => 'key', 'value' => 1], ['key' => 'key', 'value' => 1]],
[['key' => 'key', 'value' => 1.1], ['key' => 'key', 'value' => 1.1]],
[['key' => 'key', 'value' => '1.3'], ['key' => 'key', 'value' => 1.3]],
[['key' => 'key', 'value' => '-1.4'], ['key' => 'key', 'value' => -1.4]],
[['key' => 'key', 'value' => ' 1.3 '], ['key' => 'key', 'value' => 1.3]],
[['key' => 'key', 'value' => ' -1.54 '], ['key' => 'key', 'value' => -1.54]],
// Test with literal values
[['key' => 'key', 'value' => 'test'], ['key' => 'key', 'value' => 'test']],
[['key' => 'IS_VALID', 'value' => 'test'], ['key' => 'IS_VALID', 'value' => 'test']],
[['key' => 'key', 'value' => ''], ['key' => 'key', 'value' => '']],
[['key' => 'IS_VALID', 'value' => ''], ['key' => 'IS_VALID', 'value' => '']],
// Test with no empty key and value
[['key' => ' key ', 'value' => ' test '], ['key' => 'key', 'value' => 'test']],
[['key' => ' IS_VALID ', 'value' => ' test '], ['key' => 'IS_VALID', 'value' => 'test']],
]);
it('should not add a variable whose key begins with the comment character (#)', function (): void {
$env = new EnvironmentFileManager('');
$env->add('#KEY', 'data');
$variables = $env->getAll();
expect($variables)->toHaveCount(0);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Utility/StringConverterTest.php | centreon/tests/php/Utility/StringConverterTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Tests\Utility;
use PHPUnit\Framework\TestCase;
use Utility\StringConverter;
class StringConverterTest extends TestCase
{
/**
* test convertCamelCaseToSnakeCase
*/
public function testConvertCamelCaseToSnakeCase(): void
{
$camelCaseName = 'myCurrentProperty1';
$snakeCaseName = StringConverter::convertCamelCaseToSnakeCase($camelCaseName);
$this->assertEquals('my_current_property1', $snakeCaseName);
}
/**
* test convertSnakeCaseToCamelCase
*/
public function testConvertSnakeCaseToCamelCase(): void
{
$snakeCaseName = 'my_current_property1';
$camelCaseName = StringConverter::convertSnakeCaseToCamelCase($snakeCaseName);
$this->assertEquals('myCurrentProperty1', $camelCaseName);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Utility/Difference/TupleDifferenceTest.php | centreon/tests/php/Utility/Difference/TupleDifferenceTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Utility;
use Utility\Difference\TupleDifference;
it(
'should compute getAdded()',
fn ($before, $after, $expected) => expect((new TupleDifference($before, $after))->getAdded())
->toBe($expected)
)
->with(
[
[[[1, 'a'], [1, 'b'], [3, 42]], [[2, 'a'], [3, 'b'], [4, 42]], [[2, 'a'], [3, 'b'], [4, 42]]],
[[[1, 'a'], [1, 'b'], [3, 42]], [[1, 'b'], [4, 42]], [1 => [4, 42]]],
[[[1, 'a'], [1, 'b'], [3, 42]], [[1, 'a'], [1, 'b'], [3, 42]], []],
[[[1, 'a'], [1, 'b'], [3, 42]], [], []],
[[[1, 'a']], [['a', 1]], [['a', 1]]],
[[[5], ['b']], [[6], ['b']], [[6]]],
]
);
it(
'should compute getRemoved()',
fn ($before, $after, $expected) => expect((new TupleDifference($before, $after))->getRemoved())
->toBe($expected)
)
->with(
[
[[[1, 'a'], [1, 'b'], [3, 42]], [[2, 'a'], [3, 'b'], [4, 42]], [[1, 'a'], [1, 'b'], [3, 42]]],
[[[1, 'a'], [1, 'b'], [3, 42]], [[1, 'b'], [4, 42]], [[1, 'a'], 2 => [3, 42]]],
[[[1, 'a'], [1, 'b'], [3, 42]], [[1, 'a'], [1, 'b'], [3, 42]], []],
[[[1, 'a'], [1, 'b'], [3, 42]], [], [[1, 'a'], [1, 'b'], [3, 42]]],
[[[1, 'a']], [['a', 1]], [[1, 'a']]],
[[[5], ['b']], [[6], ['b']], [[5]]],
]
);
it(
'should compute getCommon()',
fn ($before, $after, $expected) => expect((new TupleDifference($before, $after))->getCommon())
->toBe($expected)
)
->with(
[
[[[1, 'a'], [1, 'b'], [3, 42]], [[2, 'a'], [3, 'b'], [4, 42]], []],
[[[1, 'a'], [1, 'b'], [3, 42]], [[1, 'b'], [4, 42]], [1 => [1, 'b']]],
[[[1, 'a'], [1, 'b'], [3, 42]], [[1, 'a'], [1, 'b'], [3, 42]], [[1, 'a'], [1, 'b'], [3, 42]]],
[[[1, 'a'], [1, 'b'], [3, 42]], [], []],
[[[1, 'a']], [['a', 1]], []],
[[[5], ['b']], [[6], ['b']], [1 => ['b']]],
]
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Utility/Difference/BasicDifferenceTest.php | centreon/tests/php/Utility/Difference/BasicDifferenceTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Utility;
use Utility\Difference\BasicDifference;
it(
'should compute getAdded()',
fn ($before, $after, $expected) => expect((new BasicDifference($before, $after))->getAdded())
->toBe($expected)
)
->with(
[
// Integers
[[1, 2, 3], [4, 5, 6], [4, 5, 6]],
[[1, 2, 3], [3, 4], [1 => 4]],
[[1, 2, 3], [1, 2, 3], []],
[[1, 2, 3], [], []],
// Strings
[['a', 'b', 'c'], ['c', 'd'], [1 => 'd']],
// Mixed
[[1, 2, '3'], [3, '4'], [1 => '4']],
]
);
it(
'should compute getRemoved()',
fn ($before, $after, $expected) => expect((new BasicDifference($before, $after))->getRemoved())
->toBe($expected)
)
->with(
[
// Integers
[[1, 2, 3], [4, 5, 6], [1, 2, 3]],
[[1, 2, 3], [3, 4], [1, 2]],
[[1, 2, 3], [1, 2, 3], []],
[[1, 2, 3], [], [1, 2, 3]],
[[1, 2, 3], [1], [1 => 2, 3]],
// Strings
[['a', 'b', 'c'], ['c', 'd'], ['a', 'b']],
// Mixed
[[1, 2, '3'], [3, '4'], [1, 2]],
[[1, 2, 3], ['2'], [1, 2 => 3]],
]
);
it(
'should compute getCommon()',
fn ($before, $after, $expected) => expect((new BasicDifference($before, $after))->getCommon())
->toBe($expected)
)
->with(
[
// Integers
[[1, 2, 3], [4, 5, 6], []],
[[1, 2, 3], [3, 4], [2 => 3]],
[[1, 2, 3], [3, 2, 1], [1, 2, 3]],
[[1, 2, 3], [], []],
[[1, 2, 3], [2], [1 => 2]],
// Strings
[['a', 'b', 'c'], ['c', 'd'], [2 => 'c']],
// Mixed
[[1, 2, '3'], [3, '4'], [2 => '3']],
[[1, 2, 3], ['2'], [1 => 2]],
]
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/App/bootstrap.php | centreon/tests/php/App/bootstrap.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
require dirname(__DIR__, 3) . '/vendor/autoload.php';
require dirname(__DIR__, 3) . '/config/bootstrap.php';
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/App/ActivityLogging/Domain/Event/LogActivityEventHandlerTest.php | centreon/tests/php/App/ActivityLogging/Domain/Event/LogActivityEventHandlerTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\App\ActivityLogging\Domain\Event;
use App\ActivityLogging\Domain\Aggregate\ActionEnum;
use App\ActivityLogging\Domain\Aggregate\ActivityLog;
use App\ActivityLogging\Domain\Aggregate\TargetTypeEnum;
use App\ActivityLogging\Domain\Event\LogActivityEventHandler;
use App\MonitoringConfiguration\Domain\Aggregate\ServiceCategory\ServiceCategory;
use App\MonitoringConfiguration\Domain\Aggregate\ServiceCategory\ServiceCategoryId;
use App\MonitoringConfiguration\Domain\Aggregate\ServiceCategory\ServiceCategoryName;
use App\MonitoringConfiguration\Domain\Event\ServiceCategoryCreated;
use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
use Tests\App\ActivityLogging\Infrastructure\Double\FakeActivityLogFactory;
use Tests\App\ActivityLogging\Infrastructure\Double\FakeActivityLogRepository;
final class LogActivityEventHandlerTest extends TestCase
{
public function testCreateActivityLogOnCreation(): void
{
$repository = new FakeActivityLogRepository();
$handler = new LogActivityEventHandler($repository, $this->createContainer([
ServiceCategory::class => new FakeActivityLogFactory(),
]));
$aggregate = new ServiceCategory(
id: new ServiceCategoryId(1),
name: new ServiceCategoryName('NAME'),
alias: new ServiceCategoryName('ALIAS'),
activated: true,
);
$handler(new ServiceCategoryCreated(
aggregate: $aggregate,
creatorId: 2,
firedAt: $firedAt = new \DateTimeImmutable(),
));
$activityLog = reset($repository->activityLogs);
self::assertInstanceof(ActivityLog::class, $activityLog);
self::assertSame(ActionEnum::Add, $activityLog->action);
self::assertSame(2, $activityLog->actor->id->value);
self::assertSame(1, $activityLog->target->id->value);
self::assertSame('NAME', $activityLog->target->name->value);
self::assertSame(TargetTypeEnum::ServiceCategory, $activityLog->target->type);
self::assertEquals($firedAt, $activityLog->performedAt);
}
/**
* @param array<string, object> $factories
*/
private function createContainer(array $factories = []): ContainerInterface
{
return new class ($factories) implements ContainerInterface {
/**
* @param array<string, object> $factories
*/
public function __construct(
private array $factories,
) {
}
public function has(string $id): bool
{
return isset($this->factories[$id]);
}
public function get(string $id): object
{
return $this->factories[$id];
}
};
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/App/ActivityLogging/Infrastructure/Doctrine/DoctrineActivityLogRepositoryTest.php | centreon/tests/php/App/ActivityLogging/Infrastructure/Doctrine/DoctrineActivityLogRepositoryTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\App\ActivityLogging\Infrastructure\Doctrine;
use App\ActivityLogging\Domain\Aggregate\ActionEnum;
use App\ActivityLogging\Domain\Aggregate\ActivityLog;
use App\ActivityLogging\Domain\Aggregate\ActivityLogId;
use App\ActivityLogging\Domain\Aggregate\Actor;
use App\ActivityLogging\Domain\Aggregate\ActorId;
use App\ActivityLogging\Domain\Aggregate\Target;
use App\ActivityLogging\Domain\Aggregate\TargetId;
use App\ActivityLogging\Domain\Aggregate\TargetName;
use App\ActivityLogging\Domain\Aggregate\TargetTypeEnum;
use App\ActivityLogging\Infrastructure\Doctrine\DoctrineActivityLogRepository;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
final class DoctrineActivityLogRepositoryTest extends KernelTestCase
{
private DoctrineActivityLogRepository $repository;
protected function setUp(): void
{
/** @var DoctrineActivityLogRepository $repository */
$repository = self::getContainer()->get(DoctrineActivityLogRepository::class);
$this->repository = $repository;
}
public function testAdd(): void
{
self::assertSame(0, $this->repository->count());
$activityLog = new ActivityLog(
id: null,
action: ActionEnum::Add,
actor: new Actor(
id: new ActorId(1),
),
target: new Target(
id: new TargetId(1),
name: new TargetName('foo'),
type: TargetTypeEnum::ServiceCategory,
),
performedAt: (new \DateTimeImmutable())->setTime(0, 0),
details: [
'foo' => 'foo_value',
'bar' => 'bar_value',
],
);
$this->repository->add($activityLog);
self::assertEquals($activityLog, $this->repository->find($activityLog->id()));
}
public function testFind(): void
{
$activityLog = new ActivityLog(
id: null,
action: ActionEnum::Add,
actor: new Actor(
id: new ActorId(1),
),
target: new Target(
id: new TargetId(1),
name: new TargetName('foo'),
type: TargetTypeEnum::ServiceCategory,
),
performedAt: (new \DateTimeImmutable())->setTime(0, 0),
details: [],
);
$this->repository->add($activityLog);
self::assertNull($this->repository->find(new ActivityLogId(mt_rand())));
self::assertNotNull($this->repository->find($activityLog->id()));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/App/ActivityLogging/Infrastructure/Double/FakeActivityLogRepository.php | centreon/tests/php/App/ActivityLogging/Infrastructure/Double/FakeActivityLogRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\App\ActivityLogging\Infrastructure\Double;
use App\ActivityLogging\Domain\Aggregate\ActivityLog;
use App\ActivityLogging\Domain\Aggregate\ActivityLogId;
use App\ActivityLogging\Domain\Repository\ActivityLogRepository;
final class FakeActivityLogRepository implements ActivityLogRepository
{
/** @var array<int, ActivityLog> */
public array $activityLogs = [];
public function add(ActivityLog $activityLog): void
{
do {
$id = mt_rand();
} while (isset($this->activityLogs[$id]));
$reflection = new \ReflectionProperty($activityLog, 'id');
$reflection->setAccessible(true);
$reflection->setValue($activityLog, new ActivityLogId($id));
$this->activityLogs[$id] = $activityLog;
}
public function count(): int
{
return count($this->activityLogs);
}
public function find(ActivityLogId $id): ?ActivityLog
{
return $this->activityLogs[$id->value] ?? null;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/App/ActivityLogging/Infrastructure/Double/FakeActivityLogFactory.php | centreon/tests/php/App/ActivityLogging/Infrastructure/Double/FakeActivityLogFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\App\ActivityLogging\Infrastructure\Double;
use App\ActivityLogging\Domain\Aggregate\ActionEnum;
use App\ActivityLogging\Domain\Aggregate\ActivityLog;
use App\ActivityLogging\Domain\Aggregate\Actor;
use App\ActivityLogging\Domain\Aggregate\Target;
use App\ActivityLogging\Domain\Aggregate\TargetId;
use App\ActivityLogging\Domain\Aggregate\TargetName;
use App\ActivityLogging\Domain\Aggregate\TargetTypeEnum;
use App\ActivityLogging\Domain\Factory\ActivityLogFactoryInterface;
use App\Shared\Domain\Aggregate\AggregateRoot;
/**
* @implements ActivityLogFactoryInterface<AggregateRoot>
*/
final class FakeActivityLogFactory implements ActivityLogFactoryInterface
{
public function create(ActionEnum $action, AggregateRoot $aggregate, Actor $firedBy, \DateTimeImmutable $firedAt): ActivityLog
{
$target = new Target(
id: new TargetId(1),
name: new TargetName('NAME'),
type: TargetTypeEnum::ServiceCategory,
);
return new ActivityLog(
id: null,
action: $action,
actor: $firedBy,
target: $target,
performedAt: $firedAt,
details: [],
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/App/MonitoringConfiguration/Application/Command/CreateServiceCategoryCommandHandlerTest.php | centreon/tests/php/App/MonitoringConfiguration/Application/Command/CreateServiceCategoryCommandHandlerTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\App\MonitoringConfiguration\Application\Command;
use App\MonitoringConfiguration\Application\Command\CreateServiceCategoryCommand;
use App\MonitoringConfiguration\Application\Command\CreateServiceCategoryCommandHandler;
use App\MonitoringConfiguration\Domain\Aggregate\ServiceCategory\ServiceCategoryName;
use App\MonitoringConfiguration\Domain\Event\ServiceCategoryCreated;
use App\MonitoringConfiguration\Domain\Exception\ServiceCategoryAlreadyExistsException;
use PHPUnit\Framework\TestCase;
use Tests\App\MonitoringConfiguration\Infrastructure\Double\FakeServiceCategoryRepository;
use Tests\App\Shared\Double\EventBusSpy;
final class CreateServiceCategoryCommandHandlerTest extends TestCase
{
public function testCreateServiceCategory(): void
{
$repository = new FakeServiceCategoryRepository();
$eventBus = new EventBusSpy();
$handler = new CreateServiceCategoryCommandHandler($repository, $eventBus);
$handler(new CreateServiceCategoryCommand(
name: new ServiceCategoryName('NAME'),
alias: new ServiceCategoryName('ALIAS'),
activated: true,
creatorId: 1,
));
self::assertNotNull($repository->findOneByName(new ServiceCategoryName('NAME')));
}
public function testCannotCreateSameServiceCategory(): void
{
$repository = new FakeServiceCategoryRepository();
$eventBus = new EventBusSpy();
$handler = new CreateServiceCategoryCommandHandler($repository, $eventBus);
$handler(new CreateServiceCategoryCommand(
name: new ServiceCategoryName('NAME'),
alias: new ServiceCategoryName('ALIAS'),
activated: true,
creatorId: 1,
));
$this->expectException(ServiceCategoryAlreadyExistsException::class);
$handler(new CreateServiceCategoryCommand(
name: new ServiceCategoryName('NAME'),
alias: new ServiceCategoryName('ALIAS'),
activated: true,
creatorId: 1,
));
}
public function testDispatchCreatedEvent(): void
{
$repository = new FakeServiceCategoryRepository();
$eventBus = new EventBusSpy();
$handler = new CreateServiceCategoryCommandHandler($repository, $eventBus);
$handler(new CreateServiceCategoryCommand(
name: new ServiceCategoryName('NAME'),
alias: new ServiceCategoryName('ALIAS'),
activated: true,
creatorId: 1,
));
self::assertTrue($eventBus->shouldHaveDispatched(ServiceCategoryCreated::class));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/App/MonitoringConfiguration/Application/Command/CreateServiceCategoryCommandTest.php | centreon/tests/php/App/MonitoringConfiguration/Application/Command/CreateServiceCategoryCommandTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\App\MonitoringConfiguration\Application\Command;
use App\MonitoringConfiguration\Application\Command\CreateServiceCategoryCommand;
use App\MonitoringConfiguration\Application\Command\CreateServiceCategoryCommandHandler;
use App\MonitoringConfiguration\Domain\Aggregate\ServiceCategory\ServiceCategoryName;
use App\MonitoringConfiguration\Domain\Event\ServiceCategoryCreated;
use App\MonitoringConfiguration\Domain\Exception\ServiceCategoryAlreadyExistsException;
use PHPUnit\Framework\TestCase;
use Tests\App\MonitoringConfiguration\Infrastructure\Double\FakeServiceCategoryRepository;
use Tests\App\Shared\Double\EventBusSpy;
final class CreateServiceCategoryCommandHandlerTest extends TestCase
{
public function testCreateServiceCategory(): void
{
$repository = new FakeServiceCategoryRepository();
$eventBus = new EventBusSpy();
$handler = new CreateServiceCategoryCommandHandler($repository, $eventBus);
$handler(new CreateServiceCategoryCommand(
name: new ServiceCategoryName('NAME'),
alias: new ServiceCategoryName('ALIAS'),
activated: true,
creatorId: 1,
));
self::assertNotNull($repository->findOneByName(new ServiceCategoryName('NAME')));
}
public function testCannotCreateSameServiceCategory(): void
{
$repository = new FakeServiceCategoryRepository();
$eventBus = new EventBusSpy();
$handler = new CreateServiceCategoryCommandHandler($repository, $eventBus);
$handler(new CreateServiceCategoryCommand(
name: new ServiceCategoryName('NAME'),
alias: new ServiceCategoryName('ALIAS'),
activated: true,
creatorId: 1,
));
$this->expectException(ServiceCategoryAlreadyExistsException::class);
$handler(new CreateServiceCategoryCommand(
name: new ServiceCategoryName('NAME'),
alias: new ServiceCategoryName('ALIAS'),
activated: true,
creatorId: 1,
));
}
public function testDispatchCreatedEvent(): void
{
$repository = new FakeServiceCategoryRepository();
$eventBus = new EventBusSpy();
$handler = new CreateServiceCategoryCommandHandler($repository, $eventBus);
$handler(new CreateServiceCategoryCommand(
name: new ServiceCategoryName('NAME'),
alias: new ServiceCategoryName('ALIAS'),
activated: true,
creatorId: 1,
));
self::assertTrue($eventBus->shouldHaveDispatched(ServiceCategoryCreated::class));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/App/MonitoringConfiguration/Infrastructure/ApiPlatform/State/ListGlobalMacrosProviderTest.php | centreon/tests/php/App/MonitoringConfiguration/Infrastructure/ApiPlatform/State/ListGlobalMacrosProviderTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\App\MonitoringConfiguration\Infrastructure\ApiPlatform\State;
use App\MonitoringConfiguration\Infrastructure\ApiPlatform\Resource\GlobalMacroResource;
use Symfony\Component\HttpFoundation\Response;
use Tests\App\Shared\ApiTestCase;
final class ListGlobalMacrosProviderTest extends ApiTestCase
{
private const BASE_ENDPOINT = '/api/latest/configuration/global-macros';
public function testItFindAllGlobalMacrosWithoutParameter(): void
{
$this->login();
$this->request('GET', self::BASE_ENDPOINT);
self::assertResponseIsSuccessful();
self::assertMatchesResourceCollectionJsonSchema(GlobalMacroResource::class);
self::assertJsonContains(
[
'member' => [
['name' => '$USER1$'],
],
]
);
}
public function testItFindAllGlobalMacrosIsUnauthorizedForUserWithoutSufficientACL(): void
{
$this->login('user');
$this->request('GET', self::BASE_ENDPOINT);
$this->assertResponseStatusCodeSame(Response::HTTP_FORBIDDEN);
}
public function testItFindAllGlobalMacrosWithNameLikeOperator(): void
{
$this->login();
$response = $this->request('GET', self::BASE_ENDPOINT, ['query' => ['name' => ['lk' => 'USER1']]]);
self::assertResponseIsSuccessful();
$this->assertCount(1, (array) $response->toArray()['member']);
self::assertJsonContains(
[
'member' => [
['name' => '$USER1$'],
],
]
);
}
public function testItFindAllGlobalMacrosWithNameLikeOperatorNoMatch(): void
{
$this->login();
$response = $this->request('GET', self::BASE_ENDPOINT, ['query' => ['name' => ['lk' => 'USER3']]]);
self::assertResponseIsSuccessful();
$this->assertCount(0, (array) $response->toArray()['member']);
}
public function testItFindAllGlobalMacrosWithNameEqualOperator(): void
{
$this->login();
$response = $this->request('GET', self::BASE_ENDPOINT, ['query' => ['name' => ['eq' => '$USER1$']]]);
self::assertResponseIsSuccessful();
$this->assertCount(1, (array) $response->toArray()['member']);
self::assertJsonContains(
[
'member' => [
['name' => '$USER1$'],
],
]
);
}
public function testItFindAllGlobalMacrosWithNameEqualOperatorNoMatch(): void
{
$this->login();
$response = $this->request('GET', self::BASE_ENDPOINT, ['query' => ['name' => ['eq' => 'USER1']]]);
self::assertResponseIsSuccessful();
$this->assertCount(0, (array) $response->toArray()['member']);
}
public function testItFindAllGlobalMacrosWithPagination(): void
{
$this->login();
$response = $this->request('GET', self::BASE_ENDPOINT, ['query' => ['page' => '2', 'itemsPerPage' => '1']]);
self::assertResponseIsSuccessful();
self::assertMatchesResourceCollectionJsonSchema(GlobalMacroResource::class);
$this->assertCount(1, (array) $response->toArray()['member']);
$this->assertCount(1, (array) $response->toArray()['member']);
$this->assertEquals(2, $response->toArray()['totalItems']);
}
public function testIfFindAllGlobalMacrosWithPaginationAndAnOperator(): void
{
$this->login();
$response = $this->request(
'GET',
self::BASE_ENDPOINT,
['query' => ['page' => '1', 'itemsPerPage' => '2', 'name' => ['lk' => ['USER', 'PLUGIN']]]]
);
self::assertResponseIsSuccessful();
self::assertMatchesResourceCollectionJsonSchema(GlobalMacroResource::class);
$this->assertCount(2, (array) $response->toArray()['member']);
$this->assertEquals(2, $response->toArray()['totalItems']);
$response = $this->request(
'GET',
self::BASE_ENDPOINT,
['query' => ['page' => '1', 'itemsPerPage' => '2', 'name' => ['lk' => 'USER']]]
);
self::assertResponseIsSuccessful();
self::assertMatchesResourceCollectionJsonSchema(GlobalMacroResource::class);
$this->assertCount(1, (array) $response->toArray()['member']);
$this->assertEquals(1, $response->toArray()['totalItems']);
}
public function testItShouldIgnoreUnknownOperator(): void
{
$this->login();
$response = $this->request(
'GET',
self::BASE_ENDPOINT,
[
'query' => ['name' => ['eq' => ['$USER1$'], 'es' => ['$UNKNOWN$']]],
]
);
self::assertResponseIsSuccessful();
$this->assertCount(1, (array) $response->toArray()['member']);
}
protected static function apiUsers(): array
{
return ['user'];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/App/MonitoringConfiguration/Infrastructure/ApiPlatform/State/ListStandardMacrosProviderTest.php | centreon/tests/php/App/MonitoringConfiguration/Infrastructure/ApiPlatform/State/ListStandardMacrosProviderTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\App\MonitoringConfiguration\Infrastructure\ApiPlatform\State;
use App\MonitoringConfiguration\Infrastructure\ApiPlatform\Resource\StandardMacroResource;
use Tests\App\Shared\ApiTestCase;
final class ListStandardMacrosProviderTest extends ApiTestCase
{
private const BASE_ENDPOINT = '/api/latest/configuration/standard-macros';
public function testItFindStandardMacros(): void
{
$this->login();
$this->request('GET', self::BASE_ENDPOINT);
self::assertResponseIsSuccessful();
self::assertMatchesResourceCollectionJsonSchema(StandardMacroResource::class);
self::assertJsonContains(
[
'member' => [
['name' => '$HOSTNAME$'],
],
]
);
self::assertJsonContains(
[
'totalItems' => 110,
]
);
}
public function testItFindAllStandardMacrosWithNameLikeOperator(): void
{
$this->login();
$response = $this->request('GET', self::BASE_ENDPOINT, ['query' => ['name' => ['lk' => ['ALIAS', 'NAME']]]]);
self::assertResponseIsSuccessful();
$this->assertCount(10, (array) $response->toArray()['member']);
self::assertJsonContains(
[
'member' => [
['name' => '$HOSTNAME$'],
],
]
);
}
public function testItFindAllStandardMacrosWithNameLikeOperatorNoMatch(): void
{
$this->login();
$response = $this->request('GET', self::BASE_ENDPOINT, ['query' => ['name' => ['lk' => 'foo']]]);
self::assertResponseIsSuccessful();
$this->assertCount(0, (array) $response->toArray()['member']);
}
public function testItFindAllGlobalMacrosWithNameEqualOperator(): void
{
$this->login();
$response = $this->request('GET', self::BASE_ENDPOINT, ['query' => ['name' => ['eq' => '$HOSTNAME$']]]);
self::assertResponseIsSuccessful();
$this->assertCount(1, (array) $response->toArray()['member']);
self::assertJsonContains(
[
'member' => [
['name' => '$HOSTNAME$'],
],
]
);
}
public function testItFindAllGlobalMacrosWithPagination(): void
{
$this->login();
$response = $this->request('GET', self::BASE_ENDPOINT, ['query' => ['page' => '2', 'itemsPerPage' => '10']]);
self::assertResponseIsSuccessful();
self::assertMatchesResourceCollectionJsonSchema(StandardMacroResource::class);
$this->assertCount(10, (array) $response->toArray()['member']);
$this->assertEquals(110, $response->toArray()['totalItems']);
}
public function testIfFindAllGlobalMacrosWithPaginationAndAnOperator(): void
{
$this->login();
$response = $this->request(
'GET',
self::BASE_ENDPOINT,
['query' => ['page' => '1', 'itemsPerPage' => '2', 'name' => ['lk' => ['NAME', 'ALIAS']]]]
);
self::assertResponseIsSuccessful();
self::assertMatchesResourceCollectionJsonSchema(StandardMacroResource::class);
$this->assertCount(2, (array) $response->toArray()['member']);
$this->assertEquals(10, $response->toArray()['totalItems']);
}
public function testItShouldIgnoreUnknownOperator(): void
{
$this->login();
$response = $this->request(
'GET',
self::BASE_ENDPOINT,
[
'query' => ['name' => ['lk' => ['ALIAS'], 'es' => ['$UNKNOWN$']]],
]
);
self::assertResponseIsSuccessful();
$this->assertCount(5, (array) $response->toArray()['member']);
}
protected static function apiUsers(): array
{
return ['user'];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/App/MonitoringConfiguration/Infrastructure/ApiPlatform/State/CreateServiceCategoryProcessorTest.php | centreon/tests/php/App/MonitoringConfiguration/Infrastructure/ApiPlatform/State/CreateServiceCategoryProcessorTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\App\MonitoringConfiguration\Infrastructure\ApiPlatform\State;
use App\ActivityLogging\Domain\Repository\ActivityLogRepository;
use App\MonitoringConfiguration\Domain\Aggregate\ServiceCategory\ServiceCategoryName;
use App\MonitoringConfiguration\Domain\Repository\ServiceCategoryRepository;
use App\MonitoringConfiguration\Infrastructure\ApiPlatform\Resource\ServiceCategoryResource;
use Tests\App\Shared\ApiTestCase;
final class CreateServiceCategoryProcessorTest extends ApiTestCase
{
public function testCreateServiceCategory(): void
{
/** @var ServiceCategoryRepository $repository */
$repository = self::getContainer()->get(ServiceCategoryRepository::class);
$serviceCategory = $repository->findOneByName(new ServiceCategoryName('NAME'));
self::assertNull($serviceCategory);
$this->login();
$response = $this->request('POST', '/api/latest/configuration/services/categories', [
'headers' => [
'Content-Type' => 'application/json',
],
'json' => [
'name' => 'NAME',
'alias' => 'ALIAS',
'is_activated' => false,
],
]);
self::assertResponseIsSuccessful();
self::assertMatchesResourceItemJsonSchema(ServiceCategoryResource::class);
self::assertJsonContains([
'name' => 'NAME',
'alias' => 'ALIAS',
'is_activated' => false,
]);
self::assertArrayHasKey('id', $response->toArray());
$serviceCategory = $repository->findOneByName(new ServiceCategoryName('NAME'));
self::assertNotNull($serviceCategory);
}
public function testCannotCreateSameServiceCategory(): void
{
$this->login();
$this->request('POST', '/api/latest/configuration/services/categories', [
'json' => [
'name' => 'NAME',
'alias' => 'ALIAS',
'is_activated' => false,
],
]);
self::assertResponseIsSuccessful();
$this->request('POST', '/api/latest/configuration/services/categories', [
'json' => [
'name' => 'NAME',
'alias' => 'ALIAS',
'is_activated' => false,
],
]);
self::assertResponseStatusCodeSame(409);
}
public function testCannotCreateServiceCategoryWithInvalidValues(): void
{
$this->login();
$this->request('POST', '/api/latest/configuration/services/categories', [
'json' => [
'name' => '',
],
]);
self::assertResponseStatusCodeSame(400);
self::assertJsonContains([
'code' => 400,
'message' => "[name] This value is too short. It should have 1 character or more.\n"
. "[alias] This value should not be null.\n",
]);
}
public function testCannotCreateServiceCategoryWithInvalidValueTypes(): void
{
$this->login();
$this->request('POST', '/api/latest/configuration/services/categories', [
'json' => [
'name' => true,
'alias' => 0,
'is_activated' => [1.23],
],
]);
self::assertResponseStatusCodeSame(400);
self::assertJsonContains([
'code' => 400,
'message' => "[name] This value should be of type string.\n"
. "[alias] This value should be of type string.\n"
. "[is_activated] This value should be of type bool.\n",
]);
}
public function testCannotCreateServiceCategoryIfNotLogged(): void
{
$this->request('POST', '/api/latest/configuration/services/categories', [
'json' => [
'name' => 'NAME',
'alias' => 'ALIAS',
'is_activated' => false,
],
]);
self::assertResponseStatusCodeSame(401);
}
public function testCannotCreateServiceCategoryIfNotEnoughPermission(): void
{
$this->login('user');
$this->request('POST', '/api/latest/configuration/services/categories', [
'json' => [
'name' => 'NAME',
'alias' => 'ALIAS',
'is_activated' => false,
],
]);
self::assertResponseStatusCodeSame(403);
self::assertJsonContains([
'code' => 403,
'message' => 'You are not allowed to create service categories',
]);
}
public function testCreateServiceCategoryAddActivityLog(): void
{
/** @var ActivityLogRepository $repository */
$repository = self::getContainer()->get(ActivityLogRepository::class);
self::assertSame(0, $repository->count());
$this->login();
$this->request('POST', '/api/latest/configuration/services/categories', [
'headers' => [
'Content-Type' => 'application/json',
],
'json' => [
'name' => 'NAME',
'alias' => 'ALIAS',
'is_activated' => false,
],
]);
self::assertResponseIsSuccessful();
self::assertSame(1, $repository->count());
}
protected static function apiUsers(): array
{
return ['user'];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/App/MonitoringConfiguration/Infrastructure/ApiPlatform/State/ListPluginsProviderTest.php | centreon/tests/php/App/MonitoringConfiguration/Infrastructure/ApiPlatform/State/ListPluginsProviderTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\App\MonitoringConfiguration\Infrastructure\ApiPlatform\State;
use App\MonitoringConfiguration\Infrastructure\ApiPlatform\Resource\PluginResource;
use Tests\App\Shared\ApiTestCase;
final class ListPluginsProviderTest extends ApiTestCase
{
public function testItFindPlugins(): void
{
$this->login();
$this->request('GET', '/api/latest/configuration/plugins');
self::assertResponseIsSuccessful();
self::assertMatchesResourceCollectionJsonSchema(PluginResource::class);
self::assertJsonContains(
[
'member' => [
['name' => 'urlize'],
],
]
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/App/MonitoringConfiguration/Infrastructure/Double/FakeServiceCategoryRepository.php | centreon/tests/php/App/MonitoringConfiguration/Infrastructure/Double/FakeServiceCategoryRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\App\MonitoringConfiguration\Infrastructure\Double;
use App\MonitoringConfiguration\Domain\Aggregate\ServiceCategory\ServiceCategory;
use App\MonitoringConfiguration\Domain\Aggregate\ServiceCategory\ServiceCategoryId;
use App\MonitoringConfiguration\Domain\Aggregate\ServiceCategory\ServiceCategoryName;
use App\MonitoringConfiguration\Domain\Repository\ServiceCategoryRepository;
use App\Shared\Domain\Aggregate\AggregateRoot;
final class FakeServiceCategoryRepository implements ServiceCategoryRepository
{
/** @var array<int, ServiceCategory> */
public array $serviceCategories = [];
public function add(ServiceCategory $serviceCategory): void
{
do {
$id = mt_rand();
} while (isset($this->serviceCategories[$id]));
$reflection = new \ReflectionProperty(AggregateRoot::class, 'id');
$reflection->setAccessible(true);
$reflection->setValue($serviceCategory, new ServiceCategoryId($id));
$this->serviceCategories[$id] = $serviceCategory;
}
public function findOneByName(ServiceCategoryName $name): ?ServiceCategory
{
foreach ($this->serviceCategories as $serviceCategory) {
if ($serviceCategory->name->value === $name->value) {
return $serviceCategory;
}
}
return null;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/App/MonitoringConfiguration/Infrastructure/Dbal/DbalStandardMacroRepositoryTest.php | centreon/tests/php/App/MonitoringConfiguration/Infrastructure/Dbal/DbalStandardMacroRepositoryTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\App\MonitoringConfiguration\Infrastructure\Dbal;
use App\MonitoringConfiguration\Domain\Aggregate\StandardMacro\StandardMacro;
use App\MonitoringConfiguration\Domain\Repository\Criteria\StandardMacroCriteria;
use App\MonitoringConfiguration\Infrastructure\Dbal\DbalStandardMacroRepository;
use App\Shared\Infrastructure\InMemory\InMemoryPaginator;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
final class DbalStandardMacroRepositoryTest extends KernelTestCase
{
private DbalStandardMacroRepository $repository;
protected function setUp(): void
{
/** @var DbalStandardMacroRepository $repository */
$repository = self::getContainer()->get(DbalStandardMacroRepository::class);
$this->repository = $repository;
}
public function testFindAll(): void
{
$globalMacros = $this->repository->findAll();
self::containsOnlyInstancesOf(StandardMacro::class);
self::assertCount(110, $globalMacros);
}
public function testFindAllWithNameCriteria(): void
{
$criteria = new StandardMacroCriteria();
$criteria = $criteria->withName('HOSTALIAS', StandardMacroCriteria::OPERATOR_LIKE);
$globalMacros = $this->repository->findAll($criteria);
self::containsOnlyInstancesOf(StandardMacro::class);
self::assertCount(1, $globalMacros);
$criteria = new StandardMacroCriteria();
$criteria = $criteria->withName('$HOSTALIAS$', StandardMacroCriteria::OPERATOR_EQUAL);
$globalMacros = $this->repository->findAll($criteria);
self::containsOnlyInstancesOf(StandardMacro::class);
self::assertCount(1, $globalMacros);
}
public function testFindAllWithPagination(): void
{
$criteria = new StandardMacroCriteria();
$criteria = $criteria->withPagination(page: 1, itemsPerPage: 1);
$paginator = $this->repository->findAll($criteria);
self::assertInstanceOf(InMemoryPaginator::class, $paginator);
self::assertCount(1, $paginator);
self::assertSame(1, $paginator->getCurrentPage());
self::assertSame(1, $paginator->getItemsPerPage());
self::assertSame(110, $paginator->getTotalItems());
self::assertSame(110, $paginator->getLastPage());
}
public function testFindAllWithNameCriteriaAndPagination(): void
{
$criteria = new StandardMacroCriteria();
$criteria = $criteria->withName('NAME', StandardMacroCriteria::OPERATOR_LIKE);
$criteria = $criteria->withName('ALIAS', StandardMacroCriteria::OPERATOR_LIKE);
$criteria = $criteria->withPagination(page: 1, itemsPerPage: 2);
$paginator = $this->repository->findAll($criteria);
self::assertInstanceOf(InMemoryPaginator::class, $paginator);
self::assertCount(2, $paginator);
self::assertSame(1, $paginator->getCurrentPage());
self::assertSame(2, $paginator->getItemsPerPage());
self::assertSame(10, $paginator->getTotalItems());
self::assertSame(5, $paginator->getLastPage());
$criteria = new StandardMacroCriteria();
$criteria = $criteria->withName('$HOSTALIAS$', StandardMacroCriteria::OPERATOR_EQUAL);
$criteria = $criteria->withName('$HOSTNAME$', StandardMacroCriteria::OPERATOR_EQUAL);
$criteria = $criteria->withPagination(page: 1, itemsPerPage: 2);
$paginator = $this->repository->findAll($criteria);
self::assertInstanceOf(InMemoryPaginator::class, $paginator);
self::assertCount(2, $paginator);
self::assertSame(1, $paginator->getCurrentPage());
self::assertSame(2, $paginator->getItemsPerPage());
self::assertSame(2, $paginator->getTotalItems());
self::assertSame(1, $paginator->getLastPage());
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/App/MonitoringConfiguration/Infrastructure/Dbal/DbalOptionRepositoryTest.php | centreon/tests/php/App/MonitoringConfiguration/Infrastructure/Dbal/DbalOptionRepositoryTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\App\MonitoringConfiguration\Infrastructure\Dbal;
use App\MonitoringConfiguration\Domain\Aggregate\Option\Option;
use App\MonitoringConfiguration\Domain\Aggregate\Option\OptionName;
use App\MonitoringConfiguration\Domain\Exception\OptionDoesNotExistException;
use App\MonitoringConfiguration\Domain\Repository\OptionRepository;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
final class DbalOptionRepositoryTest extends KernelTestCase
{
private OptionRepository $repository;
protected function setUp(): void
{
/** @var OptionRepository $repository */
$repository = self::getContainer()->get(OptionRepository::class);
$this->repository = $repository;
}
public function testItFindByName(): void
{
$option = $this->repository->getByName(new OptionName(Option::PLUGIN_PATH_OPTION_NAME));
self::assertSame(Option::PLUGIN_PATH_OPTION_NAME, $option->name->value);
self::assertSame('/usr/lib64/nagios/plugins/', $option->value->value);
}
public function testItThrowExceptionWhenOptionDoesNotExist(): void
{
$this->expectException(OptionDoesNotExistException::class);
$this->repository->getByName(new OptionName('foo'));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/App/MonitoringConfiguration/Infrastructure/Dbal/DbalPollerRepositoryTest.php | centreon/tests/php/App/MonitoringConfiguration/Infrastructure/Dbal/DbalPollerRepositoryTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\App\MonitoringConfiguration\Infrastructure\Dbal;
use App\MonitoringConfiguration\Domain\Aggregate\GlobalMacro\GlobalMacro;
use App\MonitoringConfiguration\Domain\Aggregate\GlobalMacro\GlobalMacroComment;
use App\MonitoringConfiguration\Domain\Aggregate\GlobalMacro\GlobalMacroExpression;
use App\MonitoringConfiguration\Domain\Aggregate\GlobalMacro\GlobalMacroId;
use App\MonitoringConfiguration\Domain\Aggregate\GlobalMacro\GlobalMacroName;
use App\MonitoringConfiguration\Domain\Aggregate\Poller\Poller;
use App\MonitoringConfiguration\Infrastructure\Dbal\DbalPollerRepository;
use App\Shared\Domain\Collection;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
final class DbalOptionRepositoryTest extends KernelTestCase
{
private DbalPollerRepository $repository;
protected function setUp(): void
{
/** @var DbalPollerRepository $repository */
$repository = self::getContainer()->get(DbalPollerRepository::class);
$this->repository = $repository;
}
public function testItFindAllByGlobalMacro(): void
{
$pollers = $this->repository->findAllByGlobalMacro(
new GlobalMacro(
new GlobalMacroId(1),
new GlobalMacroName('$USER1$'),
new GlobalMacroExpression('/usr/lib64/nagios/plugins/'),
new GlobalMacroComment('path to plugins'),
false,
false,
new Collection([], Poller::class)
)
);
self::assertCount(1, $pollers);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/App/MonitoringConfiguration/Infrastructure/Dbal/DbalServiceCategoryRepositoryTest.php | centreon/tests/php/App/MonitoringConfiguration/Infrastructure/Dbal/DbalServiceCategoryRepositoryTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\App\MonitoringConfiguration\Infrastructure\Dbal;
use App\MonitoringConfiguration\Domain\Aggregate\ServiceCategory\ServiceCategory;
use App\MonitoringConfiguration\Domain\Aggregate\ServiceCategory\ServiceCategoryName;
use App\MonitoringConfiguration\Infrastructure\Dbal\DbalServiceCategoryRepository;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
final class DbalServiceCategoryRepositoryTest extends KernelTestCase
{
private DbalServiceCategoryRepository $repository;
protected function setUp(): void
{
/** @var DbalServiceCategoryRepository $repository */
$repository = self::getContainer()->get(DbalServiceCategoryRepository::class);
$this->repository = $repository;
}
public function testAdd(): void
{
self::assertNull($this->repository->findOneByName(new ServiceCategoryName('NAME')));
$serviceCategory = new ServiceCategory(
id: null,
name: new ServiceCategoryName('NAME'),
alias: new ServiceCategoryName('ALIAS'),
activated: true,
);
$this->repository->add($serviceCategory);
self::assertEquals($serviceCategory, $this->repository->findOneByName(new ServiceCategoryName('NAME')));
}
public function testFindOneByName(): void
{
$serviceCategory = new ServiceCategory(
id: null,
name: new ServiceCategoryName('NAME'),
alias: new ServiceCategoryName('ALIAS'),
activated: true,
);
$this->repository->add($serviceCategory);
self::assertNotNull($this->repository->findOneByName(new ServiceCategoryName('NAME')));
self::assertNull($this->repository->findOneByName(new ServiceCategoryName('OTHER_NAME')));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/App/MonitoringConfiguration/Infrastructure/Dbal/DbalGlobalMacroRepositoryTest.php | centreon/tests/php/App/MonitoringConfiguration/Infrastructure/Dbal/DbalGlobalMacroRepositoryTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\App\MonitoringConfiguration\Infrastructure\Dbal;
use App\MonitoringConfiguration\Domain\Aggregate\GlobalMacro\GlobalMacro;
use App\MonitoringConfiguration\Domain\Repository\Criteria\GlobalMacroCriteria;
use App\MonitoringConfiguration\Infrastructure\Dbal\DbalGlobalMacroRepository;
use App\Shared\Domain\Collection;
use App\Shared\Infrastructure\InMemory\InMemoryPaginator;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
final class DbalGlobalMacroRepositoryTest extends KernelTestCase
{
private DbalGlobalMacroRepository $repository;
protected function setUp(): void
{
/** @var DbalGlobalMacroRepository $repository */
$repository = self::getContainer()->get(DbalGlobalMacroRepository::class);
$this->repository = $repository;
}
public function testFindAll(): void
{
$globalMacros = $this->repository->findAll();
self::containsOnlyInstancesOf(GlobalMacro::class);
self::assertCount(2, $globalMacros);
}
public function testFindAllWithNameCriteria(): void
{
$criteria = new GlobalMacroCriteria();
$criteria = $criteria->withName('USER1', GlobalMacroCriteria::OPERATOR_LIKE);
$globalMacros = $this->repository->findAll($criteria);
self::containsOnlyInstancesOf(GlobalMacro::class);
self::assertCount(1, $globalMacros);
$criteria = new GlobalMacroCriteria();
$criteria = $criteria->withName('$USER1$', GlobalMacroCriteria::OPERATOR_EQUAL);
$globalMacros = $this->repository->findAll($criteria);
self::containsOnlyInstancesOf(GlobalMacro::class);
self::assertCount(1, $globalMacros);
}
public function testFindAllWithPagination(): void
{
$criteria = new GlobalMacroCriteria();
$criteria = $criteria->withPagination(page: 1, itemsPerPage: 1);
$paginator = $this->repository->findAll($criteria);
self::assertInstanceOf(InMemoryPaginator::class, $paginator);
self::assertCount(1, $paginator);
self::assertSame(1, $paginator->getCurrentPage());
self::assertSame(1, $paginator->getItemsPerPage());
self::assertSame(2, $paginator->getTotalItems());
self::assertSame(2, $paginator->getLastPage());
}
public function testFindAllWithNameCriteriaAndPagination(): void
{
$criteria = new GlobalMacroCriteria();
$criteria = $criteria->withName('USER', GlobalMacroCriteria::OPERATOR_LIKE);
$criteria = $criteria->withName('PLUGINS', GlobalMacroCriteria::OPERATOR_LIKE);
$criteria = $criteria->withPagination(page: 1, itemsPerPage: 2);
$paginator = $this->repository->findAll($criteria);
self::assertInstanceOf(InMemoryPaginator::class, $paginator);
self::assertCount(2, $paginator);
self::assertSame(1, $paginator->getCurrentPage());
self::assertSame(2, $paginator->getItemsPerPage());
self::assertSame(2, $paginator->getTotalItems());
self::assertSame(1, $paginator->getLastPage());
$criteria = new GlobalMacroCriteria();
$criteria = $criteria->withName('$USER1$', GlobalMacroCriteria::OPERATOR_EQUAL);
$criteria = $criteria->withName('$CENTREONPLUGINS$', GlobalMacroCriteria::OPERATOR_EQUAL);
$criteria = $criteria->withPagination(page: 1, itemsPerPage: 2);
$paginator = $this->repository->findAll($criteria);
self::assertInstanceOf(InMemoryPaginator::class, $paginator);
self::assertCount(2, $paginator);
self::assertSame(1, $paginator->getCurrentPage());
self::assertSame(2, $paginator->getItemsPerPage());
self::assertSame(2, $paginator->getTotalItems());
self::assertSame(1, $paginator->getLastPage());
}
public function testRetrievePollersRelationEagerly(): void
{
$criteria = new GlobalMacroCriteria();
$criteria = $criteria->withName('$USER1$', GlobalMacroCriteria::OPERATOR_EQUAL);
$globalMacros = $this->repository->findAll($criteria);
self::assertCount(1, $globalMacros);
$globalMacro = iterator_to_array($globalMacros)[0] ?? null;
self::assertInstanceOf(GlobalMacro::class, $globalMacro);
// as we are eager by defaults, elements are an array
$reflection = new \ReflectionClass(Collection::class);
$elements = $reflection->getProperty('elements')->getValue($globalMacro->pollers);
self::assertIsArray($elements);
$pollers = $globalMacro->pollers;
self::assertCount(1, $pollers);
$poller = $pollers->toArray()[0];
$pollerGlobalMacros = $poller->globalMacros;
self::assertCount(2, $pollerGlobalMacros);
// references are kept
foreach ($pollerGlobalMacros as $pollerGlobalMacro) {
self::assertSame($poller, $pollerGlobalMacro->pollers->toArray()[0]);
}
}
public function testRetrievePollersRelationLazily(): void
{
$criteria = new GlobalMacroCriteria();
$criteria = $criteria
->withName('$USER1$', GlobalMacroCriteria::OPERATOR_EQUAL)
->withLazyRelations();
$globalMacros = $this->repository->findAll($criteria);
self::assertCount(1, $globalMacros);
$globalMacro = iterator_to_array($globalMacros)[0];
// as we are eager by defaults, elements are null
$reflection = new \ReflectionClass(Collection::class);
$elements = $reflection->getProperty('elements')->getValue($globalMacro->pollers);
self::assertNull($elements);
$pollers = $globalMacro->pollers;
self::assertCount(1, $pollers);
$poller = $pollers->toArray()[0];
$pollerGlobalMacros = $poller->globalMacros;
self::assertCount(2, $pollerGlobalMacros);
// references are kept
foreach ($pollerGlobalMacros as $pollerGlobalMacro) {
self::assertSame($poller, $pollerGlobalMacro->pollers->toArray()[0]);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/App/Shared/ApiTestCase.php | centreon/tests/php/App/Shared/ApiTestCase.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\App\Shared;
use ApiPlatform\Symfony\Bundle\Test\ApiTestCase as SymfonyApiTestCase;
use ApiPlatform\Symfony\Bundle\Test\Client;
use Doctrine\DBAL\Connection;
use Symfony\Contracts\HttpClient\ResponseInterface;
abstract class ApiTestCase extends SymfonyApiTestCase
{
private const TEST_PASSWORD = 'Centreon!2021';
protected static ?bool $alwaysBootKernel = true;
private Client $client;
private ?string $token = null;
public static function setUpBeforeClass(): void
{
/** @var Connection $connection */
$connection = static::getContainer()->get('doctrine.dbal.test_setup_default_connection');
$connection->beginTransaction();
try {
foreach (static::apiUsers() as $apiUser) {
if (\is_string($apiUser)) {
$apiUser = ['identifier' => $apiUser, 'admin' => false];
}
self::createApiUser($connection, $apiUser['identifier'], $apiUser['admin'] ?? false);
}
$connection->commit();
} catch (\Throwable $e) {
$connection->rollBack();
throw $e;
}
}
public static function tearDownAfterClass(): void
{
/** @var Connection $connection */
$connection = static::getContainer()->get('doctrine.dbal.test_setup_default_connection');
$connection->beginTransaction();
try {
foreach (static::apiUsers() as $apiUser) {
if (\is_string($apiUser)) {
$apiUser = ['identifier' => $apiUser];
}
self::deleteApiUser($connection, $apiUser['identifier']);
}
$connection->commit();
} catch (\Throwable $e) {
$connection->rollBack();
throw $e;
}
parent::tearDownAfterClass();
}
protected function setUp(): void
{
$this->client = static::createClient();
$this->token = null;
}
/**
* @param array{headers?: array<string, mixed>, ...<string, mixed>} $options
*/
final public function request(string $method, string $url, array $options = []): ResponseInterface
{
if ($this->token) {
$options['headers']['X-AUTH-TOKEN'] = $this->token;
}
$_SERVER['REMOTE_ADDR'] = '8.8.8.8';
return $this->client->request($method, $url, $options);
}
/**
* Define API users to create for the current test class.
*
* @return list<array{identifier: string, admin?: bool}|string>
*/
protected static function apiUsers(): array
{
return [];
}
final protected function login(string $login = 'admin'): void
{
$this->request('POST', '/api/latest/login', [
'json' => [
'security' => [
'credentials' => [
'login' => $login,
'password' => self::TEST_PASSWORD,
],
],
],
]);
$response = $this->client->getResponse();
/** @var array{security: array{token: string}}|null $content */
$content = $response?->toArray();
$this->token = $content['security']['token'] ?? null;
if (! $this->token) {
throw new \RuntimeException('Cannot find authentication token');
}
}
final protected function logout(): void
{
$this->token = null;
}
private static function createApiUser(Connection $connection, string $identifier, bool $admin = false): void
{
$connection->insert('contact', [
'contact_name' => $identifier,
'contact_alias' => $identifier,
'contact_admin' => $admin ? '1' : '0',
'contact_register' => '1',
'contact_activate' => '1',
'contact_email' => $identifier . '@email.com',
]);
$connection->insert('contact_password', [
'contact_id' => (int) $connection->lastInsertId(),
'password' => password_hash('Centreon!2021', \PASSWORD_BCRYPT),
'creation_date' => (new \DateTimeImmutable())->getTimestamp(),
]);
}
private static function deleteApiUser(Connection $connection, string $identifier): void
{
$connection->executeStatement('DELETE FROM contact_password WHERE contact_id IN (SELECT contact_id FROM contact WHERE contact_alias = :identifier)', [
'identifier' => $identifier,
]);
$connection->executeStatement('DELETE FROM contact WHERE contact_alias = :identifier', [
'identifier' => $identifier,
]);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/App/Shared/Infrastructure/InMemory/InMemoryPaginatorTest.php | centreon/tests/php/App/Shared/Infrastructure/InMemory/InMemoryPaginatorTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\App\Shared\Infrastructure\InMemory;
use App\Shared\Domain\Collection;
use App\Shared\Infrastructure\InMemory\InMemoryPaginator;
use PHPUnit\Framework\TestCase;
final class InMemoryPaginatorTest extends TestCase
{
public function testGetItemsPerPage(): void
{
$paginator = new InMemoryPaginator(new Collection([], \stdClass::class), 0, 1, 10);
$this->assertSame(10, $paginator->getItemsPerPage());
}
public function testGetCurrentPage(): void
{
$paginator = new InMemoryPaginator(new Collection([], \stdClass::class), 0, 2, 10);
$this->assertSame(2, $paginator->getCurrentPage());
}
public function testGetLastPage(): void
{
$paginator = new InMemoryPaginator(new Collection([], \stdClass::class), 25, 1, 10);
$this->assertSame(3, $paginator->getLastPage());
}
public function testGetTotalItems(): void
{
$paginator = new InMemoryPaginator(new Collection([], \stdClass::class), 42, 1, 10);
$this->assertSame(42, $paginator->getTotalItems());
}
public function testCountReturnsNumberOfItems(): void
{
$items = new Collection([(object) ['id' => 1], (object) ['id' => 2]], \stdClass::class);
$paginator = new InMemoryPaginator($items, 2, 1, 10);
$this->assertSame(2, $paginator->count());
}
public function testGetIteratorReturnsTraversable(): void
{
$items = new Collection([(object) ['id' => 1], (object) ['id' => 2]], \stdClass::class);
$paginator = new InMemoryPaginator($items, 2, 1, 10);
$iterator = $paginator->getIterator();
$this->assertSame(iterator_to_array($items), iterator_to_array($iterator));
}
public function testLastPageIsAtLeastOne(): void
{
$paginator = new InMemoryPaginator(new Collection([], \stdClass::class), 0, 1, 10);
$this->assertSame(1, $paginator->getLastPage());
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/App/Shared/Infrastructure/ApiPlatform/CollectionNormalizationTest.php | centreon/tests/php/App/Shared/Infrastructure/ApiPlatform/CollectionNormalizationTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\App\Shared\Infrastructure\ApiPlatform;
use App\Shared\Domain\Collection;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
/**
* Ensures that collections normalized properly by API Platform.
*/
final class CollectionNormalizationTest extends KernelTestCase
{
public function testNormalizeCollection(): void
{
/** @var NormalizerInterface $normalizer */
$normalizer = self::getContainer()->get(NormalizerInterface::class);
$items = [(object) ['foo' => 'bar'], (object) ['bar' => 'baz']];
$collection = new Collection($items, \stdClass::class);
$lazyCollection = new Collection(fn (): array => $items, \stdClass::class);
$normalizedItems = $normalizer->normalize($items, 'jsonld');
$normalizedCollection = $normalizer->normalize($collection, 'jsonld');
$lazyNormalizedCollection = $normalizer->normalize($lazyCollection, 'jsonld');
self::assertSame($normalizedItems, $normalizedCollection);
self::assertSame($normalizedItems, $lazyNormalizedCollection);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/App/Shared/Double/EventBusSpy.php | centreon/tests/php/App/Shared/Double/EventBusSpy.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\App\Shared\Double;
use App\Shared\Domain\Event\EventBus;
use App\Shared\Domain\Event\EventInterface;
final class EventBusSpy implements EventBus
{
/** @var list<EventInterface> */
private array $events = [];
public function fire(EventInterface $event): void
{
$this->events[] = $event;
}
/**
* @param class-string<EventInterface> $eventClass
*/
public function shouldHaveDispatched(string $eventClass, int|null $times = null): bool
{
$filteredEvents = array_filter($this->events, static fn ($event): bool => $event::class === $eventClass);
if ($times === null) {
return $filteredEvents !== [];
}
return \count($filteredEvents) === $times;
}
/**
* @param class-string<EventInterface> $eventClass
*/
public function shouldNotHaveDispatched(string $eventClass): bool
{
return ! $this->shouldHaveDispatched($eventClass);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/HostTemplate/Application/PartialUpdateHostTemplate/PartialUpdateHostTemplateTest.php | centreon/tests/php/Core/HostTemplate/Application/PartialUpdateHostTemplate/PartialUpdateHostTemplateTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\HostTemplate\Application\UseCase\PartialUpdateHostTemplate;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Option\Option;
use Centreon\Domain\Option\OptionService;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Core\Application\Common\UseCase\ConflictResponse;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\CommandMacro\Application\Repository\ReadCommandMacroRepositoryInterface;
use Core\CommandMacro\Domain\Model\CommandMacro;
use Core\CommandMacro\Domain\Model\CommandMacroType;
use Core\Common\Application\Converter\YesNoDefaultConverter;
use Core\Common\Application\Repository\ReadVaultRepositoryInterface;
use Core\Common\Application\Repository\WriteVaultRepositoryInterface;
use Core\Host\Application\Converter\HostEventConverter;
use Core\Host\Domain\Model\HostEvent;
use Core\Host\Domain\Model\SnmpVersion;
use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface;
use Core\HostCategory\Application\Repository\WriteHostCategoryRepositoryInterface;
use Core\HostCategory\Domain\Model\HostCategory;
use Core\HostTemplate\Application\Exception\HostTemplateException;
use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface;
use Core\HostTemplate\Application\Repository\WriteHostTemplateRepositoryInterface;
use Core\HostTemplate\Application\UseCase\PartialUpdateHostTemplate\PartialUpdateHostTemplate;
use Core\HostTemplate\Application\UseCase\PartialUpdateHostTemplate\PartialUpdateHostTemplateRequest;
use Core\HostTemplate\Application\UseCase\PartialUpdateHostTemplate\PartialUpdateHostTemplateValidation;
use Core\HostTemplate\Domain\Model\HostTemplate;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Macro\Application\Repository\ReadHostMacroRepositoryInterface;
use Core\Macro\Application\Repository\WriteHostMacroRepositoryInterface;
use Core\Macro\Domain\Model\Macro;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(function (): void {
$this->readHostTemplateRepository = $this->createMock(ReadHostTemplateRepositoryInterface::class);
$this->readHostMacroRepository = $this->createMock(ReadHostMacroRepositoryInterface::class);
$this->readCommandMacroRepository = $this->createMock(ReadCommandMacroRepositoryInterface::class);
$this->writeHostMacroRepository = $this->createMock(WriteHostMacroRepositoryInterface::class);
$this->dataStorageEngine = $this->createMock(DataStorageEngineInterface::class);
$this->user = $this->createMock(ContactInterface::class);
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->presenter = new DefaultPresenter($this->presenterFormatter);
$this->useCase = new PartialUpdateHostTemplate(
$this->readHostTemplateRepository = $this->createMock(ReadHostTemplateRepositoryInterface::class),
$this->readHostMacroRepository = $this->createMock(ReadHostMacroRepositoryInterface::class),
$this->readCommandMacroRepository = $this->createMock(ReadCommandMacroRepositoryInterface::class),
$this->writeHostMacroRepository = $this->createMock(WriteHostMacroRepositoryInterface::class),
$this->readHostCategoryRepository = $this->createMock(ReadHostCategoryRepositoryInterface::class),
$this->writeHostCategoryRepository = $this->createMock(WriteHostCategoryRepositoryInterface::class),
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->writeHostTemplateRepository = $this->createMock(WriteHostTemplateRepositoryInterface::class),
$this->validation = $this->createMock(PartialUpdateHostTemplateValidation::class),
$this->optionService = $this->createMock(OptionService::class),
$this->dataStorageEngine = $this->createMock(DataStorageEngineInterface::class),
$this->user = $this->createMock(ContactInterface::class),
$this->writeVaultRepository = $this->createMock(WriteVaultRepositoryInterface::class),
$this->readVaultRepository = $this->createMock(ReadVaultRepositoryInterface::class),
);
$this->inheritanceModeOption = new Option();
$this->inheritanceModeOption->setName('inheritanceMode')->setValue('1');
// Settup host template
$this->hostTemplateId = 1;
$this->checkCommandId = 1;
$this->originalHostTemplate = new HostTemplate(
id: $this->hostTemplateId,
name: 'host_template_name',
alias: 'host_template_alias',
snmpVersion: SnmpVersion::Three,
snmpCommunity: 'someCommunity',
noteUrl: 'some note url',
note: 'a note',
actionUrl: 'some action url',
comment: 'a comment'
);
$this->request = new PartialUpdateHostTemplateRequest();
$this->request->name = $this->originalHostTemplate->getName() . ' edit ';
$this->request->alias = $this->originalHostTemplate->getAlias() . ' edit ';
$this->request->snmpVersion = SnmpVersion::Two->value;
$this->request->snmpCommunity = 'snmpCommunity-value edit';
$this->request->timezoneId = 1;
$this->request->severityId = 1;
$this->request->checkCommandId = $this->checkCommandId;
$this->request->checkCommandArgs = ['arg1', 'arg2'];
$this->request->checkTimeperiodId = 1;
$this->request->maxCheckAttempts = 5;
$this->request->normalCheckInterval = 5;
$this->request->retryCheckInterval = 5;
$this->request->activeCheckEnabled = 1;
$this->request->passiveCheckEnabled = 1;
$this->request->notificationEnabled = 1;
$this->request->notificationOptions = HostEventConverter::toBitFlag([HostEvent::Down, HostEvent::Unreachable]);
$this->request->notificationInterval = 5;
$this->request->notificationTimeperiodId = 2;
$this->request->addInheritedContactGroup = true;
$this->request->addInheritedContact = true;
$this->request->firstNotificationDelay = 5;
$this->request->recoveryNotificationDelay = 5;
$this->request->acknowledgementTimeout = 5;
$this->request->freshnessChecked = 1;
$this->request->freshnessThreshold = 5;
$this->request->flapDetectionEnabled = 1;
$this->request->lowFlapThreshold = 5;
$this->request->highFlapThreshold = 5;
$this->request->eventHandlerEnabled = 1;
$this->request->eventHandlerCommandId = 2;
$this->request->eventHandlerCommandArgs = ['arg3', ' arg4'];
$this->request->noteUrl = 'noteUrl-value edit';
$this->request->note = 'note-value edit';
$this->request->actionUrl = 'actionUrl-value edit';
$this->request->iconId = 1;
$this->request->iconAlternative = 'iconAlternative-value';
$this->request->comment = 'comment-value edit';
$this->editedHostTemplate = new HostTemplate(
id: $this->hostTemplateId,
name: $this->request->name,
alias: $this->request->alias,
snmpVersion: SnmpVersion::from($this->request->snmpVersion),
snmpCommunity: $this->request->snmpCommunity,
timezoneId: $this->request->timezoneId,
severityId: $this->request->severityId,
checkCommandId: $this->request->checkCommandId,
checkCommandArgs: ['arg1', 'test2'],
checkTimeperiodId: $this->request->checkTimeperiodId,
maxCheckAttempts: $this->request->maxCheckAttempts,
normalCheckInterval: $this->request->normalCheckInterval,
retryCheckInterval: $this->request->retryCheckInterval,
activeCheckEnabled: YesNoDefaultConverter::fromScalar($this->request->activeCheckEnabled),
passiveCheckEnabled: YesNoDefaultConverter::fromScalar($this->request->passiveCheckEnabled),
notificationEnabled: YesNoDefaultConverter::fromScalar($this->request->notificationEnabled),
notificationOptions: HostEventConverter::fromBitFlag($this->request->notificationOptions),
notificationInterval: $this->request->notificationInterval,
notificationTimeperiodId: $this->request->notificationTimeperiodId,
addInheritedContactGroup: $this->request->addInheritedContactGroup,
addInheritedContact: $this->request->addInheritedContact,
firstNotificationDelay: $this->request->firstNotificationDelay,
recoveryNotificationDelay: $this->request->recoveryNotificationDelay,
acknowledgementTimeout: $this->request->acknowledgementTimeout,
freshnessChecked: YesNoDefaultConverter::fromScalar($this->request->freshnessChecked),
freshnessThreshold: $this->request->freshnessThreshold,
flapDetectionEnabled: YesNoDefaultConverter::fromScalar($this->request->flapDetectionEnabled),
lowFlapThreshold: $this->request->lowFlapThreshold,
highFlapThreshold: $this->request->highFlapThreshold,
eventHandlerEnabled: YesNoDefaultConverter::fromScalar($this->request->eventHandlerEnabled),
eventHandlerCommandId: $this->request->eventHandlerCommandId,
eventHandlerCommandArgs: $this->request->eventHandlerCommandArgs,
noteUrl: $this->request->noteUrl,
note: $this->request->note,
actionUrl: $this->request->actionUrl,
iconId: $this->request->iconId,
iconAlternative: $this->request->iconAlternative,
comment: $this->request->comment,
isLocked: false,
);
// Settup parent templates
$this->parentTemplates = [2, 3];
$this->request->templates = $this->parentTemplates;
// Settup macros
$this->macroA = new Macro(null, $this->hostTemplateId, 'macroNameA', 'macroValueA');
$this->macroA->setOrder(0);
$this->macroB = new Macro(null, $this->hostTemplateId, 'macroNameB', 'macroValueB');
$this->macroB->setOrder(1);
$this->commandMacro = new CommandMacro(1, CommandMacroType::Host, 'commandMacroName');
$this->commandMacros = [
$this->commandMacro->getName() => $this->commandMacro,
];
$this->hostMacros = [
$this->macroA->getName() => $this->macroA,
$this->macroB->getName() => $this->macroB,
];
$this->inheritanceLineIds = [
['child_id' => 1, 'parent_id' => $this->parentTemplates[0], 'order' => 0],
['child_id' => $this->parentTemplates[0], 'parent_id' => $this->parentTemplates[1], 'order' => 1],
];
$this->request->macros = [
[
'name' => $this->macroA->getName(),
'value' => $this->macroA->getValue() . '_edit',
'is_password' => $this->macroA->isPassword(),
'description' => $this->macroA->getDescription(),
],
[
'name' => 'macroNameC',
'value' => 'macroValueC',
'is_password' => false,
'description' => null,
],
];
// Settup categories
$this->categoryA = new HostCategory(1, 'cat-name-A', 'cat-alias-A');
$this->categoryB = new HostCategory(2, 'cat-name-B', 'cat-alias-B');
$this->request->categories = [$this->categoryB->getId()];
});
// Generic usecase tests
it('should present a ForbiddenResponse when a user has insufficient rights', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(false);
($this->useCase)($this->request, $this->presenter, $this->hostTemplateId);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(HostTemplateException::writeActionsNotAllowed()->getMessage());
});
it('should present an ErrorResponse when an exception is thrown', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostTemplateRepository
->expects($this->once())
->method('findById')
->willThrowException(new \Exception());
($this->useCase)($this->request, $this->presenter, $this->hostTemplateId);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(HostTemplateException::partialUpdateHostTemplate()->getMessage());
});
it('should present a NotFoundResponse when the host template does not exist', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->readHostTemplateRepository
->expects($this->once())
->method('findByIdAndAccessGroups')
->willReturn(null);
($this->useCase)($this->request, $this->presenter, $this->hostTemplateId);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(NotFoundResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe('Host template not found');
});
it('should present a InvalidArgumentResponse when the host template is locked', function (): void {
$hostTemplate = new HostTemplate(id: 1, name: 'tpl-name', alias: 'tpl-alias', isLocked: true);
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostTemplateRepository
->expects($this->once())
->method('findById')
->willReturn($hostTemplate);
($this->useCase)($this->request, $this->presenter, $this->hostTemplateId);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(InvalidArgumentResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(HostTemplateException::hostIsLocked($hostTemplate->getId())->getMessage());
});
// Tests for host template
it('should present a ConflictResponse when name is already used', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostTemplateRepository
->expects($this->once())
->method('findById')
->willReturn($this->originalHostTemplate);
$this->validation
->expects($this->once())
->method('assertIsValidName')
->willThrowException(
HostTemplateException::nameAlreadyExists(
HostTemplate::formatName($this->request->name),
$this->request->name
)
);
($this->useCase)($this->request, $this->presenter, $this->hostTemplateId);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(
HostTemplateException::nameAlreadyExists(
HostTemplate::formatName($this->request->name),
$this->request->name
)->getMessage()
);
});
it('should present a ConflictResponse when host severity ID is not valid', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->readHostTemplateRepository
->expects($this->once())
->method('findByIdAndAccessGroups')
->willReturn($this->originalHostTemplate);
$this->validation
->expects($this->once())
->method('assertIsValidSeverity')
->willThrowException(
HostTemplateException::idDoesNotExist('severityId', $this->request->severityId)
);
($this->useCase)($this->request, $this->presenter, $this->hostTemplateId);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(HostTemplateException::idDoesNotExist('severityId', $this->request->severityId)->getMessage());
});
it('should present a ConflictResponse when a host timezone ID is not valid', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostTemplateRepository
->expects($this->once())
->method('findById')
->willReturn($this->originalHostTemplate);
$this->validation
->expects($this->once())
->method('assertIsValidTimezone')
->willThrowException(
HostTemplateException::idDoesNotExist('timezoneId', $this->request->timezoneId)
);
($this->useCase)($this->request, $this->presenter, $this->hostTemplateId);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(HostTemplateException::idDoesNotExist('timezoneId', $this->request->timezoneId)->getMessage());
});
it('should present a ConflictResponse when a timeperiod ID is not valid', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->readHostTemplateRepository
->expects($this->once())
->method('findByIdAndAccessGroups')
->willReturn($this->originalHostTemplate);
$this->validation
->expects($this->once())
->method('assertIsValidTimePeriod')
->willThrowException(
HostTemplateException::idDoesNotExist(
'checkTimeperiodId',
$this->request->checkTimeperiodId
)
);
($this->useCase)($this->request, $this->presenter, $this->hostTemplateId);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(
HostTemplateException::idDoesNotExist(
'checkTimeperiodId',
$this->request->checkTimeperiodId
)->getMessage()
);
});
it('should present a ConflictResponse when a command ID is not valid', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostTemplateRepository
->expects($this->once())
->method('findById')
->willReturn($this->originalHostTemplate);
$this->validation
->expects($this->once())
->method('assertIsValidCommand')
->willThrowException(
HostTemplateException::idDoesNotExist(
'checkCommandId',
$this->request->checkCommandId
)
);
($this->useCase)($this->request, $this->presenter, $this->hostTemplateId);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(
HostTemplateException::idDoesNotExist(
'checkCommandId',
$this->request->checkCommandId
)->getMessage()
);
});
it('should present a ConflictResponse when the host icon ID is not valid', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->readHostTemplateRepository
->expects($this->once())
->method('findByIdAndAccessGroups')
->willReturn($this->originalHostTemplate);
$this->validation
->expects($this->once())
->method('assertIsValidIcon')
->willThrowException(
HostTemplateException::idDoesNotExist(
'iconId',
$this->request->iconId
)
);
($this->useCase)($this->request, $this->presenter, $this->hostTemplateId);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(
HostTemplateException::idDoesNotExist(
'iconId',
$this->request->iconId
)->getMessage()
);
});
// Tests for parents templates
it('should present a ConflictResponse when a parent template ID is not valid', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostTemplateRepository
->expects($this->once())
->method('findById')
->willReturn($this->originalHostTemplate);
// Host template
$this->optionService
->expects($this->once())
->method('findSelectedOptions')
->willReturn(['inheritance_mode' => $this->inheritanceModeOption]);
$this->writeHostTemplateRepository
->expects($this->once())
->method('update');
// Parent templates
$this->validation
->expects($this->once())
->method('assertAreValidTemplates')
->willThrowException(HostTemplateException::idsDoNotExist('templates', $this->request->templates));
($this->useCase)($this->request, $this->presenter, $this->hostTemplateId);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(
HostTemplateException::idsDoNotExist(
'templates',
$this->request->templates
)->getMessage()
);
});
it('should present a ConflictResponse when a parent template create a circular inheritance', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostTemplateRepository
->expects($this->once())
->method('findById')
->willReturn($this->originalHostTemplate);
// Host template
$this->optionService
->expects($this->once())
->method('findSelectedOptions')
->willReturn(['inheritance_mode' => $this->inheritanceModeOption]);
$this->writeHostTemplateRepository
->expects($this->once())
->method('update');
// Parent templates
$this->validation
->expects($this->once())
->method('assertAreValidTemplates')
->willThrowException(HostTemplateException::circularTemplateInheritance());
($this->useCase)($this->request, $this->presenter, $this->hostTemplateId);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(
HostTemplateException::circularTemplateInheritance()->getMessage()
);
});
// Tests for categories
it('should present a ConflictResponse when a host category does not exist', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostTemplateRepository
->expects($this->once())
->method('findById')
->willReturn($this->originalHostTemplate);
// Host template
$this->optionService
->expects($this->once())
->method('findSelectedOptions')
->willReturn(['inheritance_mode' => $this->inheritanceModeOption]);
$this->writeHostTemplateRepository
->expects($this->once())
->method('update');
// Parent templates
$this->writeHostTemplateRepository
->expects($this->once())
->method('deleteParents');
$this->writeHostTemplateRepository
->expects($this->exactly(2))
->method('addParent');
// Macros
$this->readHostTemplateRepository
->expects($this->once())
->method('findParents')
->willReturn($this->inheritanceLineIds);
$this->readHostMacroRepository
->expects($this->once())
->method('findByHostIds')
->willReturn($this->hostMacros);
$this->readCommandMacroRepository
->expects($this->once())
->method('findByCommandIdAndType')
->willReturn($this->commandMacros);
$this->writeHostMacroRepository
->expects($this->once())
->method('delete');
$this->writeHostMacroRepository
->expects($this->once())
->method('add');
$this->writeHostMacroRepository
->expects($this->once())
->method('update');
// Categories
$this->validation
->expects($this->once())
->method('assertAreValidCategories')
->willThrowException(HostTemplateException::idsDoNotExist('categories', $this->request->categories));
($this->useCase)($this->request, $this->presenter, $this->hostTemplateId);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(HostTemplateException::idsDoNotExist('categories', $this->request->categories)->getMessage());
});
// Test for successful request
it('should present a NoContentResponse on success', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->exactly(2))
->method('isAdmin')
->willReturn(true);
$this->readHostTemplateRepository
->expects($this->once())
->method('findById')
->willReturn($this->originalHostTemplate);
// Host template
$this->optionService
->expects($this->once())
->method('findSelectedOptions')
->willReturn(['inheritance_mode' => $this->inheritanceModeOption]);
$this->validation->expects($this->once())->method('assertIsValidSeverity');
$this->validation->expects($this->once())->method('assertIsValidTimezone');
$this->validation->expects($this->exactly(2))->method('assertIsValidTimePeriod');
$this->validation->expects($this->exactly(2))->method('assertIsValidCommand');
$this->validation->expects($this->once())->method('assertIsValidIcon');
$this->writeHostTemplateRepository
->expects($this->once())
->method('update');
// Parent templates
$this->validation
->expects($this->once())
->method('assertAreValidTemplates');
$this->writeHostTemplateRepository
->expects($this->once())
->method('deleteParents');
$this->writeHostTemplateRepository
->expects($this->exactly(2))
->method('addParent');
// Macros
$this->readHostTemplateRepository
->expects($this->once())
->method('findParents')
->willReturn($this->inheritanceLineIds);
$this->readHostMacroRepository
->expects($this->once())
->method('findByHostIds')
->willReturn($this->hostMacros);
$this->readCommandMacroRepository
->expects($this->once())
->method('findByCommandIdAndType')
->willReturn($this->commandMacros);
$this->writeHostMacroRepository
->expects($this->once())
->method('delete');
$this->writeHostMacroRepository
->expects($this->once())
->method('add');
$this->writeHostMacroRepository
->expects($this->once())
->method('update');
// Categories
$this->validation
->expects($this->once())
->method('assertAreValidCategories');
$this->readHostCategoryRepository
->expects($this->once())
->method('findByHost')
->willReturn([$this->categoryA]);
$this->writeHostCategoryRepository
->expects($this->once())
->method('linkToHost');
$this->writeHostCategoryRepository
->expects($this->once())
->method('unlinkFromHost');
($this->useCase)($this->request, $this->presenter, $this->hostTemplateId);
expect($this->presenter->getResponseStatus())->toBeInstanceOf(NoContentResponse::class);
});
| 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.