Skip to content

Commit

Permalink
refactor: added new class for environment configuration during setup …
Browse files Browse the repository at this point in the history
…and update
  • Loading branch information
thorsten committed Nov 16, 2024
1 parent ee4ed19 commit e5d580f
Show file tree
Hide file tree
Showing 14 changed files with 198 additions and 68 deletions.
2 changes: 1 addition & 1 deletion phpmyfaq/admin/instances.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
use phpMyFAQ\Configuration;
use phpMyFAQ\Entity\InstanceEntity;
use phpMyFAQ\Enums\PermissionType;
use phpMyFAQ\Filesystem;
use phpMyFAQ\Filesystem\Filesystem;
use phpMyFAQ\Filter;
use phpMyFAQ\Instance;
use phpMyFAQ\Instance\Client;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
use phpMyFAQ\Database;
use phpMyFAQ\Entity\InstanceEntity;
use phpMyFAQ\Enums\PermissionType;
use phpMyFAQ\Filesystem;
use phpMyFAQ\Filesystem\Filesystem;
use phpMyFAQ\Filter;
use phpMyFAQ\Instance\Client;
use phpMyFAQ\Instance\Setup;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -183,9 +183,6 @@ public function downloadPackage(Request $request): JsonResponse
return $this->json(['success' => Translation::get('downloadSuccessful')], Response::HTTP_OK);
}

/**
* @throws Exception
*/
#[Route('admin/api/extract-package')]
public function extractPackage(): StreamedResponse
{
Expand All @@ -208,9 +205,6 @@ public function extractPackage(): StreamedResponse
});
}

/**
* @throws Exception
*/
#[Route('admin/api/create-temporary-backup')]
public function createTemporaryBackup(): StreamedResponse
{
Expand All @@ -233,9 +227,6 @@ public function createTemporaryBackup(): StreamedResponse
});
}

/**
* @throws Exception
*/
#[Route('admin/api/install-package')]
public function installPackage(): StreamedResponse
{
Expand All @@ -256,9 +247,6 @@ public function installPackage(): StreamedResponse
});
}

/**
* @throws Exception
*/
#[Route('admin/api/update-database')]
public function updateDatabase(): StreamedResponse
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
* @since 2012-04-02
*/

namespace phpMyFAQ;
namespace phpMyFAQ\Filesystem;

use phpMyFAQ\Core\Exception;

Expand Down Expand Up @@ -117,7 +117,7 @@ public function moveDirectory(string $sourcePath, string $destinationPath): bool
}

/**
* Deletes given directory.
* Deletes the given directory.
*/
public function deleteDirectory(string $pathname): bool
{
Expand Down
4 changes: 2 additions & 2 deletions phpmyfaq/src/phpMyFAQ/Instance/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@
namespace phpMyFAQ\Instance;

use phpMyFAQ\Configuration;
use phpMyFAQ\Database;
use phpMyFAQ\Core\Exception;
use phpMyFAQ\Filesystem;
use phpMyFAQ\Database;
use phpMyFAQ\Filesystem\Filesystem;
use phpMyFAQ\Instance;
use phpMyFAQ\Instance\Database as InstanceDatabase;

Expand Down
90 changes: 90 additions & 0 deletions phpmyfaq/src/phpMyFAQ/Setup/EnvironmentConfigurator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
<?php

namespace phpMyFAQ\Setup;

use phpMyFAQ\Core\Exception;
use SplFileObject;
use Symfony\Component\HttpFoundation\Request;
use Tivie\HtaccessParser\Exception\SyntaxException;
use Tivie\HtaccessParser\Parser;

use const Tivie\HtaccessParser\Token\TOKEN_DIRECTIVE;

class EnvironmentConfigurator
{
private string $rootFilePath;

private string $htaccessPath;

private string $serverPath;

public function __construct(string $rootPath = '', private readonly ?Request $request = null)
{
$this->rootFilePath = $rootPath;
$this->htaccessPath = $this->rootFilePath . '/.htaccess';
}

public function getRootFilePath(): string
{
return $this->rootFilePath;
}

public function getHtaccessPath(): string
{
return $this->htaccessPath;
}

public function getServerPath(): string
{
return $this->serverPath = $this->request->getPathInfo();
}

/**
* @throws Exception
*/
public function getRewriteBase(): string
{
$file = new SplFileObject($this->htaccessPath);
$parser = new Parser();
try {
$htaccess = $parser->parse($file);
} catch (SyntaxException $e) {
throw new Exception('Syntax error in .htaccess file: ' . $e->getMessage());
} catch (\Tivie\HtaccessParser\Exception\Exception $e) {
throw new Exception('Error parsing .htaccess file: ' . $e->getMessage());
}
$rewriteBase = $htaccess->search('RewriteBase', TOKEN_DIRECTIVE);

return $rewriteBase->getArguments()[0];
}

/**
* Adjusts the RewriteBase in the .htaccess file for the user's environment to avoid errors with controllers.
* Returns true, if the file was successfully changed.
*
* @throws Exception
*/
public function adjustRewriteBaseHtaccess(): bool
{
if (!file_exists($this->htaccessPath)) {
throw new Exception(sprintf('The %s file does not exist!', $this->htaccessPath));
}

$file = new SplFileObject($this->htaccessPath);
$parser = new Parser();
try {
$htaccess = $parser->parse($file);
} catch (SyntaxException $e) {
throw new Exception('Syntax error in .htaccess file: ' . $e->getMessage());
} catch (\Tivie\HtaccessParser\Exception\Exception $e) {
throw new Exception('Error parsing .htaccess file: ' . $e->getMessage());
}
$rewriteBase = $htaccess->search('RewriteBase', TOKEN_DIRECTIVE);

$rewriteBase->removeArgument($this->getRewriteBase());
$rewriteBase->setArguments((array)$this->getServerPath());

$output = (string) $htaccess;
return file_put_contents($this->htaccessPath, $output);
}
}
35 changes: 3 additions & 32 deletions phpmyfaq/src/phpMyFAQ/Setup/Installer.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
use phpMyFAQ\Link;
use phpMyFAQ\System;
use phpMyFAQ\User;
use Symfony\Component\HttpFoundation\Request;

/**
* Class Installer
Expand Down Expand Up @@ -1142,7 +1143,8 @@ public function startInstall(array|null $setup = null): void
}

// adjust RewriteBase in .htaccess
$this->adjustRewriteBaseHtaccess($rootDir);
$envConfiguration = new EnvironmentConfigurator($rootDir, Request::createFromGlobals());
$envConfiguration->adjustRewriteBaseHtaccess();
}

/**
Expand All @@ -1154,37 +1156,6 @@ public function checkMinimumPhpVersion(): bool
return version_compare(PHP_VERSION, System::VERSION_MINIMUM_PHP) >= 0;
}

/**
* Adjusts the RewriteBase in the .htaccess file for the user's environment to avoid errors with controllers.
* Returns true, if the file was successfully changed.
*
* @throws Exception
*/
public function adjustRewriteBaseHtaccess(string $path): bool
{
$htaccessPath = $path . '/.htaccess';

if (!file_exists($htaccessPath)) {
throw new Exception(sprintf('The %s file does not exist!', $htaccessPath));
}

$lines = file($htaccessPath);
$newLines = [];

foreach ($lines as $line) {
if (str_starts_with($line, 'RewriteBase')) {
$requestUri = filter_input(INPUT_SERVER, 'PHP_SELF');
$rewriteBase = substr((string) $requestUri, 0, strpos((string) $requestUri, 'setup/index.php'));
$rewriteBase = ($rewriteBase === '') ? '/' : $rewriteBase;
$newLines[] = 'RewriteBase ' . $rewriteBase . PHP_EOL;
} else {
$newLines[] = $line;
}
}

return file_put_contents($htaccessPath, implode('', $newLines)) !== false;
}

public function hasLdapSupport(): bool
{
return extension_loaded('ldap');
Expand Down
2 changes: 1 addition & 1 deletion phpmyfaq/src/phpMyFAQ/Setup/Update.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
use phpMyFAQ\Database;
use phpMyFAQ\Database\DatabaseDriver;
use phpMyFAQ\Enums\ReleaseType;
use phpMyFAQ\Filesystem;
use phpMyFAQ\Filesystem\Filesystem;
use phpMyFAQ\Forms;
use phpMyFAQ\Setup;
use phpMyFAQ\System;
Expand Down
2 changes: 1 addition & 1 deletion tests/.htaccess
Original file line number Diff line number Diff line change
@@ -1 +1 @@
RewriteBase /
RewriteBase /phpmyfaq-test/
6 changes: 3 additions & 3 deletions tests/bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@
const IS_VALID_PHPMYFAQ = true;
const DEBUG = true;

$_SERVER['HTTP_HOST'] = 'https://localhost/';
$_SERVER['SERVER_NAME'] = 'https://localhost/';
$_SERVER['HTTP_HOST'] = 'https://localhost/phpmyfaq-test/';
$_SERVER['SERVER_NAME'] = 'https://localhost/phpmyfaq-test/';

require PMF_ROOT_DIR . '/content/core/config/constants.php';

Expand All @@ -63,7 +63,7 @@
$loader->register();

//
// Delete possible SQLite file first
// Delete a possible SQLite file first
//
@unlink(PMF_TEST_DIR . '/test.db');

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php

namespace phpMyFAQ;
namespace phpMyFAQ\Filesystem;

use PHPUnit\Framework\TestCase;

Expand Down
6 changes: 1 addition & 5 deletions tests/phpMyFAQ/Instance/ClientTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,9 @@
namespace phpMyFAQ\Instance;

use phpMyFAQ\Configuration;
use phpMyFAQ\Core\Exception;
use phpMyFAQ\Database\DatabaseDriver;
use phpMyFAQ\Database\Sqlite3;
use phpMyFAQ\Filesystem;
use phpMyFAQ\Strings;
use phpMyFAQ\Filesystem\Filesystem;
use PHPUnit\Framework\TestCase;
use RecursiveIteratorIterator;

/**
* Class ClientTest
Expand Down
92 changes: 92 additions & 0 deletions tests/phpMyFAQ/Setup/EnvironmentConfiguratorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
<?php

namespace phpMyFAQ\Setup;

use phpMyFAQ\Core\Exception;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;

class EnvironmentConfiguratorTest extends TestCase
{
private EnvironmentConfigurator $configurator;

public function setUp(): void
{
$this->configurator = new EnvironmentConfigurator(dirname(__DIR__, 2));
}

protected function tearDown(): void
{
Request::setTrustedProxies([], -1);
Request::setTrustedHosts([]);

file_put_contents(dirname(__DIR__, 2) . '/.htaccess', 'RewriteBase /phpmyfaq-test/');
}

public function testGetRootFilePath(): void
{
$this->assertEquals(dirname(__DIR__, 2), $this->configurator->getRootFilePath());
}

public function testGetHtaccessPath(): void
{
$this->assertEquals(dirname(__DIR__, 2) . '/.htaccess', $this->configurator->getHtaccessPath());
}

public function testGetServerPath(): void
{
$request = new Request();
$server = [];
$server['REQUEST_URI'] = '/';
$request->initialize([], [], [], [], [], $server);
$configurator = new EnvironmentConfigurator('/path/to', $request);
$this->assertEquals('/', $configurator->getServerPath());
}

/**
* @throws Exception
*/
public function testGetRewriteBase(): void
{
$request = new Request();
$server = [];
$server['REQUEST_URI'] = '/phpmyfaq-test/';
$server['HTTP_HOST'] = 'https://localhost/phpmyfaq-test/';
$server['SERVER_NAME'] = 'https://localhost/phpmyfaq-test/';
$request->initialize([], [], [], [], [], $server);
$configurator = new EnvironmentConfigurator(dirname(__DIR__, 2), $request);
$this->assertEquals('/phpmyfaq-test/', $configurator->getRewriteBase());
}

public function testGetServerPathWithSubdirectoryPath(): void
{
$request = new Request();
$server = [];
$server['REQUEST_URI'] = '/path/info';
$request->initialize([], [], [], [], [], $server);
$configurator = new EnvironmentConfigurator('/path/to', $request);
$this->assertEquals('/path/info', $configurator->getServerPath());
}

public function testAdjustRewriteBaseHtaccessThrowsExceptionForMissingFile(): void
{
$configurator = new EnvironmentConfigurator('/path/to');
$this->expectException(Exception::class);
$this->expectExceptionMessage('The /path/to/.htaccess file does not exist!');
$configurator->adjustRewriteBaseHtaccess();
}

/**
* @throws Exception
*/
public function testAdjustRewriteBaseHtaccess(): void
{
$request = new Request();
$server = [];
$server['REQUEST_URI'] = '/path/info';
$request->initialize([], [], [], [], [], $server);
$configurator = new EnvironmentConfigurator(dirname(__DIR__, 2), $request);
$this->assertTrue($configurator->adjustRewriteBaseHtaccess());
$this->assertEquals('/path/info', $configurator->getRewriteBase());
}
}
7 changes: 0 additions & 7 deletions tests/phpMyFAQ/Setup/InstallerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,6 @@ public function testCheckBasicStuffThrowsExceptionForAlreadyInstalled(): void
$this->installer->checkBasicStuff();
}

public function testAdjustRewriteBaseHtaccessThrowsExceptionForMissingFile(): void
{
$this->expectException(Exception::class);
$this->expectExceptionMessage('The /path/to/.htaccess file does not exist!');
$this->installer->adjustRewriteBaseHtaccess('/path/to');
}

public function testHasLdapSupport(): void
{
if (extension_loaded('ldap')) {
Expand Down

0 comments on commit e5d580f

Please sign in to comment.