Skip to content

Commit

Permalink
Merge pull request #47 from acquia/ACMS-3658
Browse files Browse the repository at this point in the history
ACMS-3658: Code optimized & more PHPUnit tests added.
  • Loading branch information
vishalkhode1 committed Mar 22, 2024
2 parents 2db4b83 + 0b6f2be commit 2b0d670
Show file tree
Hide file tree
Showing 17 changed files with 431 additions and 74 deletions.
2 changes: 1 addition & 1 deletion settings/site/default.local.settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
* @see https://www.drupal.org/node/3105918
*/
if (phpversion() >= 8.3 ) {
ini_set('zend.assertions', 1);
@ini_set('zend.assertions', 1);
}
else {
assert_options(ASSERT_ACTIVE, TRUE);
Expand Down
4 changes: 2 additions & 2 deletions src/Drush/Traits/SiteUriTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ private function getSitesSubdirFromUri(string $root, string $uri): mixed {
}
// Strip off the protocol from the provided uri -- however,
// now we will require that the sites subdir already exist.
$dir = preg_replace('#[^/]*/*#', '', $dir);
if ($dir && file_exists(Path::join($root, $dir))) {
$dir = preg_replace('#[^/]*//#', '', $dir);
if ($dir && file_exists(Path::join($root . "/sites", $dir))) {
return $dir;
}

Expand Down
9 changes: 1 addition & 8 deletions src/Helpers/EnvironmentDetector.php
Original file line number Diff line number Diff line change
Expand Up @@ -205,14 +205,7 @@ public static function getSiteName(string $site_path): ?string {
* The repo root as an absolute path.
*/
public static function getRepoRoot(): string {
if (self::getDrupalRoot()) {
// This is a web or Drush request.
return dirname(self::getDrupalRoot());
}
// phpcs:ignore
global $repo_root;
// phpcs:enable
return $repo_root;
return self::getDrupalRoot() ? dirname(self::getDrupalRoot()) : "";
}

/**
Expand Down
38 changes: 11 additions & 27 deletions src/Helpers/Filesystem.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public function ensureDirectoryExists(string $directory): void {
if (!is_dir($directory)) {
if (file_exists($directory)) {
throw new \RuntimeException(
sprintf("The directory '%s' exists and is not a directory.", $directory)
sprintf("The file at path '%s' already exists.", $directory)
);
}
if (!@mkdir($directory, 0777, TRUE)) {
Expand Down Expand Up @@ -86,10 +86,7 @@ public function copyFiles(string $sourceDir, string $destDir, bool $overwrite =
foreach ($sourceFiles as $sourceFile) {
$sourceFileName = basename($sourceFile);
$destFile = $destDir . DIRECTORY_SEPARATOR . $sourceFileName;
$status = $this->copyFile($sourceFile, $destFile, $overwrite);
if (!$status) {
return FALSE;
}
$this->copyFile($sourceFile, $destFile, $overwrite);
}

return TRUE;
Expand All @@ -114,7 +111,7 @@ public function copyFile(string $source, string $destination, bool $overwrite =

// Copy the file from source to destination.
if (is_file($source)) {
if (!copy($source, $destination)) {
if (!@copy($source, $destination)) {
throw new \RuntimeException("Failed to copy file: $destination.");
}
}
Expand All @@ -138,20 +135,11 @@ public function appendToFile(string $filePath, string $content): bool {
throw new \RuntimeException("Unable to open the file for writing: " . $filePath);
}

// Check if the file is writable.
if (!is_writable($filePath)) {
fclose($fileHandle);
throw new \RuntimeException("The file is not writable: " . $filePath);
}

// Append the content to the file.
if (fwrite($fileHandle, $content) === FALSE) {
fclose($fileHandle);
throw new \RuntimeException("Failed to write content to the file: " . $filePath);
}
$status = fwrite($fileHandle, $content);

fclose($fileHandle);
return TRUE;
return $status;
}

/**
Expand All @@ -164,17 +152,15 @@ public function appendToFile(string $filePath, string $content): bool {
*/
public function dumpFile(string $filePath, string $content): bool {
$dir = dirname($filePath);
$this->ensureDirectoryExists($dir);
if (!is_dir($dir)) {
$this->ensureDirectoryExists($dir);
}
$fileHandle = @fopen($filePath, 'w');
if (!$fileHandle) {
throw new \RuntimeException("Unable to open the file for writing: " . $filePath);
}

if (fwrite($fileHandle, $content) === FALSE) {
fclose($fileHandle);
throw new \RuntimeException("Failed to write content to the file: " . $filePath);
}
return TRUE;
return fwrite($fileHandle, $content);
}

/**
Expand All @@ -199,12 +185,10 @@ private function toIterable(string|iterable $files): iterable {
* Given file mode.
* @param int $umask
* Given umask for file.
* @param bool $recursive
* Determines if recursive needed.
*/
public function chmod(string|iterable $files, int $mode, int $umask = 0000, bool $recursive = FALSE): bool {
public function chmod(string|iterable $files, int $mode, int $umask = 0000): bool {
foreach ($this->toIterable($files) as $file) {
if (file_exists($file) && !chmod($file, $mode & ~$umask)) {
if (file_exists($file) && !@chmod($file, $mode & ~$umask)) {
$file_or_directory = is_dir($file) ? "directory" : "file";
throw new \RuntimeException(
sprintf("Failed to change permissions for %s: '%s'.", $file_or_directory, $file)
Expand Down
16 changes: 5 additions & 11 deletions src/Plugin.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

namespace Acquia\Drupal\RecommendedSettings;

use Acquia\Drupal\RecommendedSettings\Exceptions\SettingsException;
use Composer\Composer;
use Composer\DependencyResolver\Operation\InstallOperation;
use Composer\DependencyResolver\Operation\OperationInterface;
Expand Down Expand Up @@ -99,16 +98,11 @@ public function onPostCmdEvent(): void {
// Only install the template files, if the drupal-recommended-settings
// plugin is installed, with drupal project.
if ($this->settingsPackage && $this->getDrupalRoot()) {
try {
$vendor_dir = $this->composer->getConfig()->get('vendor-dir');
$this->executeCommand(
$vendor_dir . "/bin/drush drs:init:settings", [],
TRUE
);
}
catch (SettingsException $e) {
$this->io->write("<fg=white;bg=red;options=bold>[error]</> " . $e->getMessage());
}
$vendor_dir = $this->composer->getConfig()->get('vendor-dir');
$this->executeCommand(
$vendor_dir . "/bin/drush drs:init:settings", [],
TRUE
);
}
}

Expand Down
2 changes: 2 additions & 0 deletions tests/fixtures/project/drs/config.yml
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
drupal:
db:
database: mydatabase
multisites:
- acms
9 changes: 9 additions & 0 deletions tests/src/Functional/Config/ConfigInitializerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,9 @@ public function testLoadAllConfig(): void {
"port" => 3306,
],
],
"multisites" => [
"acms",
],
]);

$config = new Config();
Expand Down Expand Up @@ -213,6 +216,9 @@ public function testLoadAllConfig(): void {
"port" => 3306,
],
],
"multisites" => [
"acms",
],
]);

$config_initializer->addConfig([
Expand Down Expand Up @@ -242,6 +248,9 @@ public function testLoadAllConfig(): void {
"port" => 3306,
],
],
"multisites" => [
"acms",
],
]);

}
Expand Down
7 changes: 7 additions & 0 deletions tests/src/Functional/Config/SettingsConfigTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,13 @@ public function testGetMethod(): void {
$settings_config->set("a.b.c", "true");
$settings_config->set("d", 'This should be boolean ${a.b.c} value.');
$this->assertEquals($settings_config->get("d"), 'This should be boolean 1 value.');

$settings_config->set("a.b.c", "false");
$settings_config->set("d", 'This should be boolean ${a.b.c} value.');
$this->assertEquals($settings_config->get("d"), 'This should be boolean value.');

$settings_config->set("e", 'This is ${f} test.');
$this->assertEquals($settings_config->get("e"), 'This is ${f} test.');
}

/**
Expand Down
12 changes: 12 additions & 0 deletions tests/src/Functional/Drush/Traits/SiteUriTraitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ class SiteUriTraitTest extends FunctionalTestBase {
protected function setUp(): void {
parent::setUp();
$this->fileSystem = new Filesystem();

$this->setupSite();
}

Expand Down Expand Up @@ -59,6 +60,14 @@ public function testGetSitesSubdirFromUri(): void {

$uri = $this->getSitesSubdirFromUri($drupal_root, "http://acquia.org:8080/developer/acquia_cms");
$this->assertEquals($uri, "developer.acquia_cms");

mkdir($drupal_root . "/sites/site3");
$uri = $this->getSitesSubdirFromUri($drupal_root, "https://site3");
$this->assertEquals($uri, "site3");

rename($drupal_root . "/sites/default", $drupal_root . "/sites/default.back");
$uri = $this->getSitesSubdirFromUri($drupal_root, "https://site4");
$this->assertFalse($uri);
}

/**
Expand Down Expand Up @@ -120,7 +129,10 @@ protected function setupSite(): void {
*/
protected function tearDown(): void {
parent::tearDown();
@rmdir($this->getDrupalRoot() . "/sites/site3");
@unlink($this->getDrupalRoot() . "/sites/sites.php");
@unlink($this->getDrupalRoot() . "/sites/site3");
@rename($this->getDrupalRoot() . "/sites/default.back", $this->getDrupalRoot() . "/sites/default");
}

}
91 changes: 88 additions & 3 deletions tests/src/Functional/Helpers/EnvironmentDetectorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
* Functional test for the EnvironmentDetectorTest class.
*
* @covers \Acquia\Drupal\RecommendedSettings\Helpers\EnvironmentDetector
* @phpcs:disable SlevomatCodingStandard.Variables.DisallowSuperGlobalVariable.DisallowedSuperGlobalVariable
*/
class EnvironmentDetectorTest extends FunctionalTestBase {

Expand Down Expand Up @@ -118,6 +119,11 @@ public function testMultipleEnv(): void {

putenv("AH_SITE_ENVIRONMENT=prod");
$this->assertTrue(EnvironmentDetector::isProdEnv());

putenv("AH_SITE_ENVIRONMENT=");
putenv('PANTHEON_ENVIRONMENT=live');
$this->assertTrue(EnvironmentDetector::isProdEnv());
putenv("PANTHEON_ENVIRONMENT=");
}

/**
Expand All @@ -131,13 +137,82 @@ public function testIsAcsfInited(): void {
$this->assertTrue(EnvironmentDetector::isAcsfInited());
}

/**
* Test EnvironmentDetector OS related methods.
*/
public function testOS(): void {
$os_name = EnvironmentDetector::getOsName();

$this->assertIsString($os_name);
$this->assertNotEmpty($os_name);

$os_version = EnvironmentDetector::getOsVersion();
$this->assertIsString($os_version);
$this->assertNotEmpty($os_version);

$this->assertIsBool(EnvironmentDetector::isDarwin());
}

/**
* Test EnvironmentDetector::getSiteName().
* @throws \ReflectionException
*/
public function testGetSiteName(): void {
$sitePath = "sites/site1";
$this->assertSame('site1', EnvironmentDetector::getSiteName($sitePath));

putenv('AH_SITE_GROUP=test');
putenv('AH_SITE_ENVIRONMENT=prod');
// Test definitely will be skipped in MacOS due to this, ensure to create
// directory/file manually running commands:
// sudo mkdir -p /var/www/site-php/test.prod/
// sudo touch /var/www/site-php/test.prod/multisite-config.json,
// This is important, or else we won't be able to test this functionality
if (!is_dir("/var/www/site-php/test.prod/")) {
if (!@mkdir("/var/www/site-php/test.prod/", "0777", TRUE)
|| !@touch("/var/www/site-php/test.prod/multisite-config.json")) {
putenv('AH_SITE_GROUP=');
putenv('AH_SITE_ENVIRONMENT=');
$this->markTestSkipped("Not able to create directory. Please create manually.");
}
}
$GLOBALS['gardens_site_settings']['conf']['acsf_db_name'] = "site1";
$this->assertEquals("site1", EnvironmentDetector::getSiteName($sitePath));
unset($GLOBALS['gardens_site_settings']);
putenv('AH_SITE_GROUP=');
putenv('AH_SITE_ENVIRONMENT=');
}

/**
* Test EnvironmentDetector::getSiteName().
*/
public function testGetSiteNameForLocalAcsf(): void {
if (getenv("ORCA_FIXTURE_DIR")) {
// Due to some reasons, we've to manually copy fixture directories to
// project directory.
// @todo: Revisit on why it's not working & fix it.
$this->copyFixtureFiles($this->getFixtureDirectory(), $this->getProjectRoot());
}
$drsFileSystem = new DrsFilesystem();
$drsFileSystem->ensureDirectoryExists($this->drupalRoot . '/sites/g');
$drsFileSystem->dumpFile($this->drupalRoot . '/sites/g/random.php', "<?php echo 'hello';");
$this->assertFileExists($this->drupalRoot . '/sites/g/random.php');
$ci_updated = $host_updated = FALSE;
if (getenv("CI")) {
putenv("CI=");
$ci_updated = TRUE;
}
if (!getenv('HTTP_HOST')) {
putenv("HTTP_HOST=localhost.acms");
$host_updated = TRUE;
}
$this->assertEquals("acms", EnvironmentDetector::getSiteName("sites/site1"));
if ($ci_updated) {
putenv("CI=true");
}
if ($host_updated) {
putenv("HTTP_HOST=");
}
}

/**
Expand All @@ -152,24 +227,34 @@ public function testGetRepoRoot(): void {
* @throws \ReflectionException
*/
public function testGetEnvironments(): void {
$ci_updated = FALSE;
if (getenv("CI")) {
putenv("CI=");
$ci_updated = TRUE;
}
$this->assertSame([
'local' => FALSE,
'local' => TRUE,
'dev' => FALSE,
'stage' => FALSE,
'prod' => TRUE,
'prod' => FALSE,
'ci' => FALSE,
'ode' => FALSE,
'ah_other' => FALSE
], EnvironmentDetector::getEnvironments());
if ($ci_updated) {
putenv("CI=true");
}
}

/**
* {@inheritdoc}
*/
protected function tearDown(): void {
parent::tearDown();
@unlink($this->drupalRoot . '/sites/g/random.php');
@rmdir($this->drupalRoot . '/sites/g');
@unlink('/var/www/site-php/test.prod/multisite-config.json');
@rmdir('/var/www');
parent::tearDown();
}

}
Loading

0 comments on commit 2b0d670

Please sign in to comment.