Enhance type safety, authentication checks, and testing framework (#3701)

* Improve type safety, auth checks and PHPStan fixes (#3250)

* Improve type safety, auth checks and PHPStan fixes

* Remove @phpstan-ignore annotations

* Improve type safety, auth checks and PHPStan fixes

* Remove @phpstan-ignore annotations

* Remove redundant @phpstan-ignore comment

* Improve code robustness and reliability (#3248)

* Harden code against null/undefined values

* Update dependency lockfiles

* Sanitize ticket input and use IDs in email list

* Restructure tests and add test utilities

* Move E2E tests to `Library\E2E` namespace

* Update `php-build` action ref in workflows

* Switch tests to Pest and add test scaffolding

* Refactor E2E tests to Pest-style tests

m

Skip E2E tests when env not configured

* Refactor Unit tests and update test config

Add test datasets and refine test helpers

* Add DEBUG guard, fix API JSON decode, update tests

* Refactor tests: add types and Mockery expectations

* Adjust tests, phpstan config, and composer script

* Instantiate test APIs locally, remove beforeEach

* Refactor runtime checks, types & logging

* Apply PHP Code Styling Changes

m

* Add PHPStan ignores, test renames & small fixes

* Enable Pest tests in CI workflow

* Remove legacy tests; add new unit tests/config

* Avoid undefined index in fingerprint comparison

* Ignore properties absent in both fingerprints

* Remove public_ticket_create API method

* Add Fingerprint unit tests

* Remove em dash from fingerprint test name

* Switch to Pest; assorted bug fixes & refactors

* Prefer getDi() and guard DEBUG define

* Refactor tests: DBAL, Antispam rename, helpers

* Refactor email tests to use Doctrine entities

* Update tests, use DBAL mocks & improve Formbuilder admin

* Validate plan_id and update unit tests

* Replace error_log with DI logger and update tests

* Expect db->store in Invoice Service test

* Use DI logger instead of error_log; fix tests

* Fix typo in Hook Service test

* Fix Staff test spelling fixture

* Complete Pest test migration

* Fix Product test spelling fixtures

* Fix Product test spelling fixtures

* Run live tests with Pest and load helpers

* Migrate tests to ApiClient; remove legacy APIHelper

* Fix Email test spelling

* Remove unused PHPUnit bridge

* Organize Cypress end-to-end tests

* Document Pest test directory root

* Remove noisy Pest comments
This commit is contained in:
Adam Daley authored and GitHub committed 2026-06-02 07:43:01 +01:00
1 parent f36ee692d2
commit dd3dcbfd52
477 files changed
+45173 -56802

No files matched your search

+43 -43
View File
@@ -29,7 +29,7 @@ class Admin extends \Api_Abstract
*/
public function get_params($data)
{
$this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'manage_settings');
$this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'manage_settings');
return $this->getService()->getParams($data);
}
@@ -39,7 +39,7 @@ class Admin extends \Api_Abstract
*/
public function localization_settings(): array
{
$this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'manage_settings');
$this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'manage_settings');
return [
'locale' => (string) Config::getProperty('i18n.locale', 'en_US'),
@@ -56,7 +56,7 @@ class Admin extends \Api_Abstract
*/
public function update_params($data)
{
$this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'update_params');
$this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'update_params');
return $this->getService()->updateParams($data);
}
@@ -68,7 +68,7 @@ class Admin extends \Api_Abstract
*/
public function update_localization_settings($data): bool
{
$this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'update_params');
$this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'update_params');
if (isset($data['locale']) && $data['locale'] !== '') {
Config::setProperty('i18n.locale', $data['locale']);
@@ -87,7 +87,7 @@ class Admin extends \Api_Abstract
public function messages($data)
{
try {
$this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'manage_settings');
$this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'manage_settings');
} catch (\Throwable) {
return [];
}
@@ -105,7 +105,7 @@ class Admin extends \Api_Abstract
public function cas_messages()
{
try {
$this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'manage_settings');
$this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'manage_settings');
} catch (\Throwable) {
return [];
}
@@ -120,7 +120,7 @@ class Admin extends \Api_Abstract
*/
public function template_exists($data)
{
$this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'manage_settings');
$this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'manage_settings');
if (!isset($data['file'])) {
return false;
@@ -136,7 +136,7 @@ class Admin extends \Api_Abstract
*/
public function env($data)
{
$this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'manage_settings');
$this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'manage_settings');
$fetchExternalIp = Tools::normalizeBoolean($data['ip'] ?? false);
@@ -156,7 +156,7 @@ class Admin extends \Api_Abstract
public function is_allowed($data)
{
$f = $data['f'] ?? null;
$service = $this->di['mod_service']('Staff');
$service = $this->getDi()['mod_service']('Staff');
return $service->hasPermission($this->getIdentity(), $data['mod'], $f);
}
@@ -168,7 +168,7 @@ class Admin extends \Api_Abstract
*/
public function clear_cache()
{
$this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'invalidate_cache');
$this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'invalidate_cache');
return $this->getService()->clearCache();
}
@@ -178,9 +178,9 @@ class Admin extends \Api_Abstract
*/
public function update_available(): bool
{
$this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'view');
$this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'view');
$updater = $this->di['updater'];
$updater = $this->getDi()['updater'];
return $updater->isUpdateAvailable();
}
@@ -190,9 +190,9 @@ class Admin extends \Api_Abstract
*/
public function update_info(): array
{
$this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'view');
$this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'view');
$updater = $this->di['updater'];
$updater = $this->getDi()['updater'];
$info = $updater->getLatestVersionInfo();
$requiredPhpVersion = $info['minimum_php_version'] ?? 'unknown';
@@ -203,7 +203,7 @@ class Admin extends \Api_Abstract
$info['minimum_php_version'] = $requiredPhpVersion;
$info['current_php_version'] = PHP_VERSION;
$info['php_version_supported'] = $requiredPhpVersion === 'unknown' || version_compare(PHP_VERSION, $requiredPhpVersion, '>=');
$info['readiness'] = $this->di['update_readiness']->check();
$info['readiness'] = $this->getDi()['update_readiness']->check();
return $info;
}
@@ -213,9 +213,9 @@ class Admin extends \Api_Abstract
*/
public function recheck_update(): bool
{
$this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'recheck_update');
$this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'recheck_update');
$updater = $this->di['updater'];
$updater = $this->getDi()['updater'];
$updater->getLatestVersionInfo(null, true);
return true;
@@ -228,54 +228,54 @@ class Admin extends \Api_Abstract
*/
public function update_core($data): bool
{
$updater = $this->di['updater'];
$updater = $this->getDi()['updater'];
if ($updater->getUpdateBranch() !== 'preview' && !$updater->isUpdateAvailable()) {
throw new \FOSSBilling\InformationException('You have the latest version of FOSSBilling. You do not need to update.');
}
$this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'system_update');
$this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'system_update');
if (function_exists('set_time_limit')) {
set_time_limit(300);
}
$new_version = $updater->getLatestVersion();
$this->di['events_manager']->fire(['event' => 'onBeforeAdminUpdateCore']);
$this->getDi()['events_manager']->fire(['event' => 'onBeforeAdminUpdateCore']);
$updater->performUpdate();
$this->di['logger']->info('Installed FOSSBilling update files from %s to %s. Update finalization is pending.', \FOSSBilling\Version::VERSION, $new_version);
$this->getDi()['logger']->info('Installed FOSSBilling update files from %s to %s. Update finalization is pending.', \FOSSBilling\Version::VERSION, $new_version);
return true;
}
public function update_finalization_status(): array
{
$this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'system_update');
$this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'system_update');
return $this->di['update_finalization']->getStatus();
return $this->getDi()['update_finalization']->getStatus();
}
public function finalize_update(): bool
{
$this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'system_update');
$this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'system_update');
if (function_exists('set_time_limit')) {
set_time_limit(180);
}
$this->di['update_finalization']->finalizeUpdate();
$this->di['events_manager']->fire(['event' => 'onAfterAdminUpdateCore']);
$this->di['logger']->info('Finalized FOSSBilling update to %s.', \FOSSBilling\Version::VERSION);
$this->getDi()['update_finalization']->finalizeUpdate();
$this->getDi()['events_manager']->fire(['event' => 'onAfterAdminUpdateCore']);
$this->getDi()['logger']->info('Finalized FOSSBilling update to %s.', \FOSSBilling\Version::VERSION);
return true;
}
public function complete_update_finalization(): bool
{
$this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'system_update');
$this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'system_update');
$this->di['update_finalization']->completeFinalization();
$this->di['logger']->info('Completed FOSSBilling update finalization for %s.', \FOSSBilling\Version::VERSION);
$this->getDi()['update_finalization']->completeFinalization();
$this->getDi()['logger']->info('Completed FOSSBilling update finalization for %s.', \FOSSBilling\Version::VERSION);
return true;
}
@@ -287,17 +287,17 @@ class Admin extends \Api_Abstract
*/
public function manual_update(): bool
{
$this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'system_update');
$this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'system_update');
if (function_exists('set_time_limit')) {
set_time_limit(180);
}
$updater = $this->di['updater'];
$this->di['events_manager']->fire(['event' => 'onBeforeAdminManualUpdate']);
$updater = $this->getDi()['updater'];
$this->getDi()['events_manager']->fire(['event' => 'onBeforeAdminManualUpdate']);
$updater->performManualUpdate();
$this->di['events_manager']->fire(['event' => 'onAfterAdminManualUpdate']);
$this->di['logger']->info('Updated FOSSBilling - applied patches and updated configuration file.');
$this->getDi()['events_manager']->fire(['event' => 'onAfterAdminManualUpdate']);
$this->getDi()['logger']->info('Updated FOSSBilling - applied patches and updated configuration file.');
return true;
}
@@ -307,9 +307,9 @@ class Admin extends \Api_Abstract
*/
public function is_behind_on_patches(): bool
{
$this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'view');
$this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'view');
$updater = $this->di['updater'];
$updater = $this->getDi()['updater'];
return $updater->isBehindOnDBPatches();
}
@@ -319,7 +319,7 @@ class Admin extends \Api_Abstract
*/
public function instance_id(): string
{
$this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'view');
$this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'view');
return INSTANCE_ID;
}
@@ -329,7 +329,7 @@ class Admin extends \Api_Abstract
*/
public function error_reporting_enabled(): bool
{
$this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'view');
$this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'view');
return (bool) Config::getProperty('debug_and_monitoring.report_errors', false);
}
@@ -339,7 +339,7 @@ class Admin extends \Api_Abstract
*/
public function toggle_error_reporting(): bool
{
$this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'toggle_error_reporting');
$this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'toggle_error_reporting');
$current = Config::getProperty('debug_and_monitoring.report_errors', false);
Config::setProperty('debug_and_monitoring.report_errors', !$current);
@@ -352,21 +352,21 @@ class Admin extends \Api_Abstract
*/
public function last_error_reporting_change(): string
{
$this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'view');
$this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'view');
return \FOSSBilling\SentryHelper::last_change;
}
public function get_interface_ips(): array
{
$this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'manage_network_interface');
$this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'manage_network_interface');
return Tools::listHttpInterfaces();
}
public function set_interface_ip($data): bool
{
$this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'manage_network_interface');
$this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'manage_network_interface');
$config = Config::getConfig();
if (isset($data['interface'])) {
+4 -4
View File
@@ -31,7 +31,7 @@ class Guest extends \Api_Abstract
public function company()
{
$companyInfo = $this->getService()->getCompany();
$auth = $this->di['auth'];
$auth = $this->getDi()['auth'];
$hideExtraCompanyInfoFromGuest = $this->getService()->getParamValue('hide_company_public');
if (!$auth->isAdminLoggedIn() && !$auth->isClientLoggedIn() && $hideExtraCompanyInfoFromGuest) {
@@ -56,7 +56,7 @@ class Guest extends \Api_Abstract
*/
public function default_country(): ?string
{
$mod = $this->di['mod']('system');
$mod = $this->getDi()['mod']('system');
$cfg = $mod->getConfig();
return $cfg['default_country'] ?? null;
@@ -69,7 +69,7 @@ class Guest extends \Api_Abstract
*/
public function countries(): array
{
$mod = $this->di['mod']('system');
$mod = $this->getDi()['mod']('system');
$cfg = $mod->getConfig();
$configuredCountries = trim((string) ($cfg['countries'] ?? ''));
@@ -171,7 +171,7 @@ class Guest extends \Api_Abstract
*/
public function current_url()
{
return $this->di['request']->getRequestUri();
return $this->getDi()['request']->getRequestUri();
}
/**
+2 -4
View File
@@ -31,11 +31,9 @@ class Service
private const int MYSQL_DUPLICATE_ENTRY_ERROR = 23000;
protected ?Container $di = null;
private readonly Filesystem $filesystem;
public function __construct()
public function __construct(private readonly ?Filesystem $filesystem = new Filesystem())
{
$this->filesystem = new Filesystem();
}
public function setDi(Container $di): void
@@ -602,7 +600,7 @@ class Service
}
$code = (string) $code;
if ($code === null || $code === '' || $code === 0 || $code === '0') {
if ($code === '' || $code === '0') {
return '-';
}
@@ -0,0 +1,117 @@
<?php
/**
* Copyright 2022-2026 FOSSBilling
* SPDX-License-Identifier: Apache-2.0.
*
* @copyright FOSSBilling (https://www.fossbilling.org)
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
*/
declare(strict_types=1);
// Skip E2E tests if environment is not configured
if (!getenv('APP_URL') || !getenv('TEST_API_KEY')) {
return;
}
function systemIpLookupWorking(): bool
{
$services = ['https://api64.ipify.org', 'https://ifconfig.io/ip', 'https://ip.hestiacp.com/'];
foreach ($services as $service) {
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 2,
CURLOPT_FAILONERROR => true,
CURLOPT_URL => $service,
]);
$ip = curl_exec($ch);
curl_close($ch);
if (filter_var($ip, FILTER_VALIDATE_IP)) {
return true;
}
}
return false;
}
test('clear cache', function (): void {
$result = Tests\Helpers\ApiClient::request('admin/system/clear_cache');
expect($result->wasSuccessful())->toBeTrue($result);
expect($result->getResult())->toBeBool();
});
test('error reporting toggle', function (): void {
$before = Tests\Helpers\ApiClient::request('admin/system/error_reporting_enabled')->getResult();
expect($before)->toBeBool();
$result = Tests\Helpers\ApiClient::request('admin/system/toggle_error_reporting');
expect($result->wasSuccessful())->toBeTrue($result);
expect($result->getResult())->toBeTrue();
$after = Tests\Helpers\ApiClient::request('admin/system/error_reporting_enabled')->getResult();
expect($after)->toBeBool();
$this->assertNotEquals($after, $before);
if ($after) {
$result = Tests\Helpers\ApiClient::request('admin/system/toggle_error_reporting');
expect($result->wasSuccessful())->toBeTrue($result);
expect($result->getResult())->toBeTrue();
}
});
test('get and set network interfaces', function (): void {
$result = Tests\Helpers\ApiClient::request('admin/system/get_interface_ips');
expect($result->wasSuccessful())->toBeTrue($result);
expect($result->getResult())->toBeArray();
foreach ($result->getResult() as $ip) {
expect((bool) filter_var($ip, FILTER_VALIDATE_IP))->toBeTrue();
}
if (systemIpLookupWorking()) {
foreach ($result->getResult() as $ip) {
$testResult = Tests\Helpers\ApiClient::request('admin/system/set_interface_ip', ['interface' => $ip]);
expect($testResult->wasSuccessful())->toBeTrue($result);
sleep(2);
$result = Tests\Helpers\ApiClient::request('admin/system/env', ['ip' => true]);
expect($result->wasSuccessful())->toBeTrue($result);
expect((bool) filter_var($result->getResult(), FILTER_VALIDATE_IP))->toBeTrue();
}
}
Tests\Helpers\ApiClient::request('admin/system/set_interface_ip', ['interface' => '0']);
});
test('interface is ignored when not valid', function (): void {
$result = Tests\Helpers\ApiClient::request('admin/system/set_interface_ip', ['interface' => '12345']);
expect($result->wasSuccessful())->toBeTrue($result);
expect($result->getResult())->toBeTrue();
if (systemIpLookupWorking()) {
sleep(2);
$result = Tests\Helpers\ApiClient::request('admin/system/env', ['ip' => true]);
expect($result->wasSuccessful())->toBeTrue($result);
expect((bool) filter_var($result->getResult(), FILTER_VALIDATE_IP))->toBeTrue();
}
});
test('custom interface', function (): void {
$result = Tests\Helpers\ApiClient::request('admin/system/set_interface_ip', ['custom_interface' => '12345']);
expect($result->wasSuccessful())->toBeTrue($result);
expect($result->getResult())->toBeTrue();
if (systemIpLookupWorking()) {
sleep(2);
$result = Tests\Helpers\ApiClient::request('admin/system/env', ['ip' => true]);
expect($result->wasSuccessful())->toBeTrue($result);
expect($result->getResult())->toBeEmpty();
}
$result = Tests\Helpers\ApiClient::request('admin/system/set_interface_ip', ['custom_interface' => '', 'interface' => '0']);
expect($result->wasSuccessful())->toBeTrue($result);
expect($result->getResult())->toBeTrue();
});
@@ -0,0 +1,58 @@
<?php
/**
* Copyright 2022-2026 FOSSBilling
* SPDX-License-Identifier: Apache-2.0.
*
* @copyright FOSSBilling (https://www.fossbilling.org)
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
*/
declare(strict_types=1);
// Skip E2E tests if environment is not configured
if (!getenv('APP_URL') || !getenv('TEST_API_KEY')) {
return;
}
test('template exists', function (): void {
$result = Tests\Helpers\ApiClient::request('guest/system/template_exists', ['file' => 'layout_default.html.twig']);
expect($result->wasSuccessful())->toBeTrue($result);
expect($result->getResult())->toBeTrue();
});
test('template does not exist', function (): void {
$result = Tests\Helpers\ApiClient::request('guest/system/template_exists', ['file' => 'thisfiledoesnotexist.txt']);
expect($result->wasSuccessful())->toBeTrue($result);
expect($result->getResult())->toBeFalse();
});
test('periods', function (): void {
$result = Tests\Helpers\ApiClient::request('guest/system/periods');
expect($result->wasSuccessful())->toBeTrue($result);
expect($result->getResult())->toBeArray();
});
test('countries', function (): void {
$result = Tests\Helpers\ApiClient::request('guest/system/countries');
expect($result->wasSuccessful())->toBeTrue($result);
expect($result->getResult())->toBeArray();
});
test('countries eunion', function (): void {
$result = Tests\Helpers\ApiClient::request('guest/system/countries_eunion');
expect($result->wasSuccessful())->toBeTrue($result);
expect($result->getResult())->toBeArray();
});
test('states', function (): void {
$result = Tests\Helpers\ApiClient::request('guest/system/states');
expect($result->wasSuccessful())->toBeTrue($result);
expect($result->getResult())->toBeArray();
});
test('phone codes', function (): void {
$result = Tests\Helpers\ApiClient::request('guest/system/phone_codes');
expect($result->wasSuccessful())->toBeTrue($result);
expect($result->getResult())->toBeArray();
});
@@ -0,0 +1,142 @@
<?php
/**
* Copyright 2022-2026 FOSSBilling
* SPDX-License-Identifier: Apache-2.0.
*
* @copyright FOSSBilling (https://www.fossbilling.org)
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
*/
declare(strict_types=1);
use function Tests\Helpers\container;
test('dependency injection', function (): void {
$api = new Box\Mod\System\Api\Admin();
$di = container();
$api->setDi($di);
$getDi = $api->getDi();
expect($getDi)->toEqual($di);
});
test('get params', function (): void {
$api = new Box\Mod\System\Api\Admin();
$data = [];
$serviceMock = Mockery::mock(Box\Mod\System\Service::class);
$serviceMock
->shouldReceive('getParams')
->atLeast()->once()
->andReturn([]);
$api->setService($serviceMock);
$result = $api->get_params($data);
expect($result)->toBeArray();
});
test('update params', function (): void {
$api = new Box\Mod\System\Api\Admin();
$data = [];
$serviceMock = Mockery::mock(Box\Mod\System\Service::class);
$serviceMock
->shouldReceive('updateParams')
->atLeast()->once()
->andReturn(true);
$api->setService($serviceMock);
$result = $api->update_params($data);
expect($result)->toBeBool();
expect($result)->toBeTrue();
});
test('messages', function (): void {
$api = new Box\Mod\System\Api\Admin();
$data = [];
$di = container();
$api->setDi($di);
$serviceMock = Mockery::mock(Box\Mod\System\Service::class);
$serviceMock
->shouldReceive('getMessages')
->atLeast()->once()
->andReturn([]);
$api->setService($serviceMock);
$result = $api->messages($data);
expect($result)->toBeArray();
});
test('template exists', function (): void {
$api = new Box\Mod\System\Api\Admin();
$data = [
'file' => 'testing.txt',
];
$serviceMock = Mockery::mock(Box\Mod\System\Service::class);
$serviceMock
->shouldReceive('templateExists')
->atLeast()->once()
->andReturn(true);
$api->setService($serviceMock);
$result = $api->template_exists($data);
expect($result)->toBeBool();
expect($result)->toBeTrue();
});
test('env', function (): void {
$api = new Box\Mod\System\Api\Admin();
$data = [];
$serviceMock = Mockery::mock(Box\Mod\System\Service::class);
$serviceMock
->shouldReceive('getEnv')
->atLeast()->once()
->andReturn([]);
$di = container();
$api->setDi($di);
$api->setService($serviceMock);
$result = $api->env($data);
expect($result)->toBeArray();
});
test('is allowed', function (): void {
$api = new Box\Mod\System\Api\Admin();
$data = [
'mod' => 'extension',
];
$staffServiceMock = Mockery::mock(Box\Mod\Staff\Service::class);
$staffServiceMock
->shouldReceive('hasPermission')
->atLeast()->once()
->andReturn(true);
$validatorStub = $this->createStub(FOSSBilling\Validate::class);
$di = container();
$di['mod_service'] = $di->protect(function ($serviceName) use ($staffServiceMock) {
if ($serviceName == 'Staff') {
return $staffServiceMock;
}
return false;
});
$di['validator'] = $validatorStub;
$api->setDi($di);
$result = $api->is_allowed($data);
expect($result)->toBeBool();
expect($result)->toBeTrue();
});
@@ -0,0 +1,148 @@
<?php
/**
* Copyright 2022-2026 FOSSBilling
* SPDX-License-Identifier: Apache-2.0.
*
* @copyright FOSSBilling (https://www.fossbilling.org)
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
*/
declare(strict_types=1);
use function Tests\Helpers\container;
test('getDi returns set dependency injection container', function (): void {
$api = new Box\Mod\System\Api\Guest();
$di = container();
$api->setDi($di);
$getDi = $api->getDi();
expect($getDi)->toEqual($di);
});
test('company returns company data when public display is enabled', function (): void {
$api = new Box\Mod\System\Api\Guest();
$companyData = ['companyName' => 'TestCo'];
$authMock = Mockery::mock('\Box_Authorization');
$authMock->shouldReceive('isAdminLoggedIn')
->atLeast()->once()
->andReturn(false);
$authMock->shouldReceive('isClientLoggedIn')
->atLeast()->once()
->andReturn(false);
$serviceMock = Mockery::mock(Box\Mod\System\Service::class);
$serviceMock
->shouldReceive('getCompany')
->atLeast()->once()
->andReturn($companyData);
$serviceMock
->shouldReceive('getParamValue')
->atLeast()->once()
->with('hide_company_public')
->andReturn(0);
$di = container();
$di['auth'] = $authMock;
$api->setDi($di);
$api->setService($serviceMock);
$result = $api->company();
expect($result)->toBeArray()->not->toBeEmpty();
});
test('company filters sensitive data when public display is disabled', function (): void {
$api = new Box\Mod\System\Api\Guest();
$companyData = [
'companyName' => 'TestCo',
'vat_number' => 'Test VAT',
'email' => 'test@email.com',
'tel' => '123456789',
'account_number' => '987654321',
'number' => '123456',
'address_1' => 'Test Address 1',
'address_2' => 'Test Address 2',
'address_3' => 'Test Address 3',
];
$authMock = Mockery::mock('\Box_Authorization');
$authMock->shouldReceive('isAdminLoggedIn')
->atLeast()->once()
->andReturn(false);
$authMock->shouldReceive('isClientLoggedIn')
->atLeast()->once()
->andReturn(false);
$serviceMock = Mockery::mock(Box\Mod\System\Service::class);
$serviceMock
->shouldReceive('getCompany')
->atLeast()->once()
->andReturn($companyData);
$serviceMock
->shouldReceive('getParamValue')
->atLeast()->once()
->with('hide_company_public')
->andReturn(1);
$di = container();
$di['auth'] = $authMock;
$api->setDi($di);
$api->setService($serviceMock);
$result = $api->company();
expect($result)->toBeArray();
expect($result)->not->toHaveKey('vat_number');
expect($result)->not->toHaveKey('email');
expect($result)->not->toHaveKey('tel');
expect($result)->not->toHaveKey('account_number');
expect($result)->not->toHaveKey('number');
expect($result)->not->toHaveKey('address_1');
expect($result)->not->toHaveKey('address_2');
expect($result)->not->toHaveKey('address_3');
});
test('period_title returns period title string', function (): void {
$api = new Box\Mod\System\Api\Guest();
$data = ['code' => 'periodCode'];
$servuceMock = Mockery::mock(Box\Mod\System\Service::class);
$servuceMock
->shouldReceive('getPeriod')
->atLeast()->once()
->andReturn('periodTtitleValue');
$di = container();
$api->setDi($di);
$api->setService($servuceMock);
$result = $api->period_title($data);
expect($result)->toBeString();
});
test('period_title returns dash when code is missing', function (): void {
$api = new Box\Mod\System\Api\Guest();
$data = [];
$expected = '-';
$di = container();
$api->setDi($di);
$result = $api->period_title($data);
expect($result)->toBeString()->toEqual($expected);
});
test('get_pending_messages returns and clears pending messages', function (): void {
$api = new Box\Mod\System\Api\Guest();
$serviceMock = Mockery::mock(Box\Mod\System\Service::class);
$messageArr = ['Important message to user'];
$serviceMock
->shouldReceive('getPendingMessages')
->atLeast()->once()
->andReturn($messageArr);
$serviceMock->shouldReceive('clearPendingMessages')->atLeast()->once();
$api->setService($serviceMock);
$result = $api->get_pending_messages();
expect($result)->toBeArray()->toEqual($messageArr);
});
@@ -0,0 +1,305 @@
<?php
/**
* Copyright 2022-2026 FOSSBilling
* SPDX-License-Identifier: Apache-2.0.
*
* @copyright FOSSBilling (https://www.fossbilling.org)
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
*/
declare(strict_types=1);
use Box\Mod\System\Service;
use function Tests\Helpers\container;
test('getParamValue throws exception when key parameter is missing', function (): void {
$service = new Service();
$param = '';
$this->expectException(FOSSBilling\Exception::class);
$this->expectExceptionMessage('Parameter key is missing');
$service->getParamValue($param);
});
test('getCompany returns company information', function (): void {
$service = new Service();
$expected = [
'www' => SYSTEM_URL,
'name' => 'Inc. Test',
'email' => 'work@example.eu',
'tel' => null,
'signature' => null,
'logo_url' => null,
'logo_url_dark' => null,
'favicon_url' => null,
'address_1' => null,
'address_2' => null,
'address_3' => null,
'account_number' => null,
'bank_name' => null,
'bic' => null,
'display_bank_info' => null,
'bank_info_pagebottom' => null,
'number' => null,
'note' => null,
'privacy_policy' => null,
'tos' => null,
'vat_number' => null,
];
$multParamsResults = [
[
'param' => 'company_name',
'value' => 'Inc. Test',
],
[
'param' => 'company_email',
'value' => 'work@example.eu',
],
];
$resultMock = Mockery::mock(Doctrine\DBAL\Result::class);
$resultMock->shouldReceive('fetchAllAssociative')
->once()
->andReturn($multParamsResults);
$queryBuilderMock = Mockery::mock(Doctrine\DBAL\Query\QueryBuilder::class);
$queryBuilderMock->shouldReceive('select')->once()->with('param', 'value')->andReturnSelf();
$queryBuilderMock->shouldReceive('from')->once()->with('setting')->andReturnSelf();
$queryBuilderMock->shouldReceive('where')->once()->with('param IN (:params)')->andReturnSelf();
$queryBuilderMock->shouldReceive('setParameter')->once()->andReturnSelf();
$queryBuilderMock->shouldReceive('executeQuery')->once()->andReturn($resultMock);
$dbalMock = Mockery::mock(Doctrine\DBAL\Connection::class);
$dbalMock->shouldReceive('createQueryBuilder')->once()->andReturn($queryBuilderMock);
$di = container();
$di['dbal'] = $dbalMock;
$service->setDi($di);
$result = $service->getCompany();
expect($result)->toBeArray();
expect($result)->toBe($expected);
});
test('getParams returns system parameters', function (): void {
$service = new Service();
$expected = [
'company_name' => 'Inc. Test',
'company_email' => 'work@example.eu',
];
$multParamsResults = [
[
'param' => 'company_name',
'value' => 'Inc. Test',
],
[
'param' => 'company_email',
'value' => 'work@example.eu',
],
];
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('getAll')->atLeast()->once()
->andReturn($multParamsResults);
$di = container();
$di['db'] = $dbMock;
$service->setDi($di);
$result = $service->getParams([]);
expect($result)->toBeArray();
expect($result)->toBe($expected);
});
test('updateParams updates system parameters', function (): void {
$service = new Service();
$data = [
'company_name' => 'newValue',
];
$eventMock = Mockery::mock('\Box_EventManager');
$eventMock->shouldReceive('fire')->atLeast()->once();
$logStub = $this->createStub('\Box_Log');
$systemServiceMock = Mockery::mock(Service::class)->makePartial();
$systemServiceMock->shouldReceive('setParamValue')->atLeast()->once()
->andReturn(true);
$di = container();
$di['events_manager'] = $eventMock;
$di['logger'] = $logStub;
$systemServiceMock->setDi($di);
$result = $systemServiceMock->updateParams($data);
expect($result)->toBeBool();
expect($result)->toBeTrue();
});
test('getMessages returns system messages', function (): void {
$service = new Service();
$latestVersion = '1.0.0';
$type = 'info';
$filesystemMock = Mockery::mock(Symfony\Component\Filesystem\Filesystem::class);
$filesystemMock->allows()->exists(Mockery::any())->andReturn(false);
$systemServiceMock = Mockery::mock(new Service($filesystemMock))->makePartial();
$systemServiceMock->allows()->getParamValue(Mockery::any())->andReturn(false);
$updaterMock = Mockery::mock(FOSSBilling\Update::class);
$updaterMock->allows()->isUpdateAvailable()->andReturn(true);
$updaterMock->allows()->getLatestVersion()->andReturn($latestVersion);
$updaterMock->allows()->isBehindOnDBPatches()->andReturn(false);
$urlMock = Mockery::mock(Box\Url::class);
$urlMock->allows()->adminLink(Mockery::any())->andReturn('http://example.com');
$dbalMock = Mockery::mock(Doctrine\DBAL\Connection::class);
$queryBuilderMock = Mockery::mock(Doctrine\DBAL\Query\QueryBuilder::class);
$resultMock = Mockery::mock(Doctrine\DBAL\Result::class);
$dbalMock->allows()->createQueryBuilder()->andReturn($queryBuilderMock);
$queryBuilderMock->allows()->select(Mockery::any())->andReturnSelf();
$queryBuilderMock->allows()->from(Mockery::any())->andReturnSelf();
$queryBuilderMock->allows()->where(Mockery::any())->andReturnSelf();
$queryBuilderMock->allows()->setParameter(Mockery::any(), Mockery::any())->andReturnSelf();
$queryBuilderMock->allows()->executeQuery()->andReturn($resultMock);
$resultMock->allows()->fetchOne()->andReturn(false);
$di = container();
$di['updater'] = $updaterMock;
$di['url'] = $urlMock;
$di['dbal'] = $dbalMock;
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $systemServiceMock);
$systemServiceMock->setDi($di);
$result = $systemServiceMock->getMessages($type);
expect($result)->toBeArray();
});
test('templateExists returns false when paths are empty', function (): void {
$service = new Service();
$getThemeResults = ['paths' => []];
$themeServiceMock = Mockery::mock(Box\Mod\Theme\Service::class)->makePartial();
$themeServiceMock->shouldReceive('getThemeConfig')->atLeast()->once()
->andReturn($getThemeResults);
$di = container();
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $themeServiceMock);
$service->setDi($di);
$result = $service->templateExists('defaultFile.cp');
expect($result)->toBeBool();
expect($result)->toBeFalse();
});
test('clearCache clears cache directory', function (): void {
$service = new Service();
// Use a temporary directory for testing instead of PATH_CACHE
$cacheDir = sys_get_temp_dir() . '/fossbilling_test_cache_' . uniqid();
// Create cache directory with .gitkeep
if (!is_dir($cacheDir)) {
mkdir($cacheDir, 0o755, true);
}
$gitkeepFile = $cacheDir . '/.gitkeep';
file_put_contents($gitkeepFile, '');
// Call clearCache with the temp directory
$result = $service->clearCache($cacheDir);
// Restore .gitkeep file after clearCache removes it
file_put_contents($gitkeepFile, '');
expect($result)->toBeBool();
expect($result)->toBeTrue();
// Cleanup temp directory
if (is_dir($cacheDir)) {
// Remove .gitkeep file first, then the directory
if (file_exists($gitkeepFile)) {
unlink($gitkeepFile);
}
rmdir($cacheDir);
}
});
test('getPeriod returns period description', function (): void {
$service = new Service();
$code = '1W';
$expected = 'Every Week';
$result = $service->getPeriod($code);
expect($result)->toBeString();
expect($result)->toBe($expected);
});
test('getPendingMessages returns pending messages from session', function (): void {
$service = new Service();
$di = container();
$sessionMock = Mockery::mock(FOSSBilling\Session::class);
$sessionMock->shouldReceive('get')->atLeast()->once()
->with('pending_messages')
->andReturn([]);
$di['session'] = $sessionMock;
$service->setDi($di);
$result = $service->getPendingMessages();
expect($result)->toBeArray();
});
test('getPendingMessages returns empty array when session returns non-array', function (): void {
$service = new Service();
$di = container();
$sessionMock = Mockery::mock(FOSSBilling\Session::class);
$sessionMock->shouldReceive('get')->atLeast()->once()
->with('pending_messages')
->andReturn(null);
$di['session'] = $sessionMock;
$service->setDi($di);
$result = $service->getPendingMessages();
expect($result)->toBeArray();
});
test('setPendingMessage adds message to pending messages', function (): void {
$service = new Service();
$serviceMock = Mockery::mock(Service::class)->makePartial();
$serviceMock->shouldReceive('getPendingMessages')->atLeast()->once()
->andReturn([]);
$di = container();
$sessionMock = Mockery::mock(FOSSBilling\Session::class);
$sessionMock->shouldReceive('set')->atLeast()->once()
->with('pending_messages', Mockery::any());
$di['session'] = $sessionMock;
$serviceMock->setDi($di);
$message = 'Important Message';
$result = $serviceMock->setPendingMessage($message);
expect($result)->toBeTrue();
});
test('clearPendingMessages clears pending messages', function (): void {
$service = new Service();
$di = container();
$sessionMock = Mockery::mock(FOSSBilling\Session::class);
$sessionMock->shouldReceive('delete')->atLeast()->once()
->with('pending_messages');
$di['session'] = $sessionMock;
$service->setDi($di);
$result = $service->clearPendingMessages();
expect($result)->toBeTrue();
});