Skip to content

Commit

Permalink
Merge pull request #424 from jolicode/code-grooming
Browse files Browse the repository at this point in the history
Code grooming
  • Loading branch information
joelwurtz authored Apr 23, 2024
2 parents e118903 + 388445d commit 636a246
Show file tree
Hide file tree
Showing 9 changed files with 95 additions and 126 deletions.
8 changes: 3 additions & 5 deletions src/Console/Command/ComposerCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,14 @@ protected function configure(): void

protected function execute(InputInterface $input, OutputInterface $output): int
{
$extra = array_filter($this->getRawTokens($input), fn ($item) => 'composer' !== $item);

$vendorDirectory = $this->rootDir . Composer::VENDOR_DIR;

if (!file_exists($file = $this->rootDir . '/castor.composer.json') && !file_exists($file = $this->rootDir . '/.castor/castor.composer.json')) {
// Default to the root directory (so someone can do a composer init by example)
$file = $this->rootDir . '/castor.composer.json';
}

$this->composer->run($file, $vendorDirectory, $extra, $output, true);
$vendorDirectory = $this->rootDir . '/' . Composer::VENDOR_DIR;

$this->composer->run($file, $vendorDirectory, $this->getRawTokens($input), $output, $input->isInteractive());

return Command::SUCCESS;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Console/Input/GetRawTokenTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ private function getRawTokens(InputInterface $input): array
$parameters = [];
$keep = false;
foreach ($tokens as $value) {
if ($value === $input->getFirstArgument()) {
if (!$keep && $value === $input->getFirstArgument()) {
$keep = true;

continue;
Expand Down
6 changes: 3 additions & 3 deletions src/Import/Importer.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

use Castor\Import\Exception\ImportError;
use Castor\Import\Exception\RemoteNotAllowed;
use Castor\Import\Remote\PackageImporter;
use Castor\Import\Remote\Composer;
use JoliCode\PhpOsHelper\OsHelper;
use Psr\Log\LoggerInterface;
use Symfony\Component\Finder\Finder;
Expand All @@ -21,7 +21,7 @@ class Importer
private array $imports = [];

public function __construct(
private readonly PackageImporter $packageImporter,
private readonly Composer $composer,
private readonly LoggerInterface $logger,
) {
}
Expand All @@ -39,7 +39,7 @@ public function import(string $path, ?string $file = null): void
$package = mb_substr($path, mb_strlen($scheme) + 3);

try {
$this->packageImporter->importFromPackage(
$this->composer->importFromPackage(
$scheme,
$package,
$file,
Expand Down
92 changes: 79 additions & 13 deletions src/Import/Remote/Composer.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,46 +4,68 @@

use Castor\Helper\PathHelper;
use Castor\Import\Exception\ComposerError;
use Castor\Import\Exception\ImportError;
use Castor\Import\Exception\InvalidImportFormat;
use Castor\Import\Exception\RemoteNotAllowed;
use Castor\Import\Mount;
use Castor\Kernel;
use Composer\Console\Application as ComposerApplication;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Symfony\Component\Console\Helper\ProgressIndicator;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\Output;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Filesystem\Filesystem;

/** @internal */
class Composer
{
public const VENDOR_DIR = '/.castor/vendor/';
public const VENDOR_DIR = '.castor/vendor';

public function __construct(
private readonly Filesystem $filesystem,
private readonly Kernel $kernel,
private readonly InputInterface $input,
private readonly OutputInterface $output,
private readonly Filesystem $filesystem,
private readonly LoggerInterface $logger = new NullLogger(),
) {
}

public function install(string $entrypointDirectory, bool $update = false, bool $displayProgress = true): void
public function isRemoteAllowed(): bool
{
if ($_SERVER['CASTOR_NO_REMOTE'] ?? false) {
return false;
}

// Need to look for the raw options as the input is not yet parsed
if (true !== $this->input->getParameterOption('--no-remote', true)) {
return false;
}

return true;
}

public function install(string $entrypointDirectory): void
{
$vendorDirectory = $entrypointDirectory . self::VENDOR_DIR;
$update = true !== $this->input->getParameterOption('--update-remotes', true);
$displayProgress = 'list' !== $this->input->getFirstArgument();

if (!file_exists($file = $entrypointDirectory . '/castor.composer.json') && !file_exists($file = $entrypointDirectory . '/.castor/castor.composer.json')) {
$this->logger->debug(sprintf('The castor.composer.json file does not exists in %s or %s/.castor, skipping composer install.', $entrypointDirectory, $entrypointDirectory));

return;
}

$vendorDirectory = $entrypointDirectory . '/' . self::VENDOR_DIR;

if (!$update && $this->isInstalled($vendorDirectory, $file)) {
return;
}

if (!file_exists($vendorDirectory)) {
$this->filesystem->mkdir($vendorDirectory);
}

file_put_contents($vendorDirectory . '.gitignore', "*\n");
$this->filesystem->mkdir($vendorDirectory);
$this->filesystem->dumpFile($vendorDirectory . '/.gitignore', "*\n");

$progressIndicator = null;

Expand All @@ -67,22 +89,66 @@ public function install(string $entrypointDirectory, bool $update = false, bool
$this->writeInstalled($vendorDirectory, $file);
}

public function remove(): void
public function requireAutoload(): void
{
$autoloadPath = PathHelper::getRoot() . '/' . self::VENDOR_DIR . '/autoload.php';

if (!file_exists($autoloadPath)) {
return;
}

require $autoloadPath;
}

public function importFromPackage(string $scheme, string $package, ?string $file = null): void
{
if (!$this->isRemoteAllowed()) {
throw new RemoteNotAllowed('Remote imports are disabled.');
}

if (!preg_match('#^(?<organization>[^/]+)/(?<repository>[^/]+)$#', $package)) {
throw new InvalidImportFormat(sprintf('The import path must be formatted like this: "%s://<organization>/<repository>".', $scheme));
}

if ('composer' === $scheme || 'package' === $scheme) {
if ('package' === $scheme) {
@trigger_deprecation('castor/castor', '0.16.0', 'The "package" scheme is deprecated, use "composer" instead.');
}

$packageDirectory = PathHelper::getRoot() . '/' . self::VENDOR_DIR . '/' . $package;

if (!file_exists($packageDirectory)) {
throw new ImportError(sprintf('The package "%s" is not installed, make sure you required it in your castor.composer.json file.', $package));
}

$this->kernel->addMount(new Mount(
PathHelper::getRoot() . '/' . self::VENDOR_DIR . '/' . $package . '/' . ($file ?? ''),
allowEmptyEntrypoint: true,
allowRemotePackage: false,
));

return;
}

throw new InvalidImportFormat(sprintf('The import scheme "%s" is not supported.', $scheme));
}

public function clean(): void
{
$this->filesystem->remove(PathHelper::getRoot() . self::VENDOR_DIR);
$this->filesystem->remove(PathHelper::getRoot() . '/' . self::VENDOR_DIR);
}

/**
* @param string[] $args
*/
public function run(string $composerJsonFilePath, string $vendorDirectory, array $args, callable|OutputInterface $callback, bool $allowInteraction = false): void
public function run(string $composerJsonFilePath, string $vendorDirectory, array $args, callable|OutputInterface $callback, bool $interactive = false): void
{
$this->filesystem->mkdir($vendorDirectory);

$args[] = '--working-dir';
$args[] = \dirname($vendorDirectory);

if (!$allowInteraction) {
if (!$interactive) {
$args[] = '--no-interaction';
}

Expand Down
86 changes: 0 additions & 86 deletions src/Import/Remote/PackageImporter.php

This file was deleted.

21 changes: 6 additions & 15 deletions src/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
use Castor\Helper\PlatformHelper;
use Castor\Import\Importer;
use Castor\Import\Mount;
use Castor\Import\Remote\PackageImporter;
use Castor\Import\Remote\Composer;
use Symfony\Component\Console\Exception\ExceptionInterface;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
Expand All @@ -40,7 +40,7 @@ public function __construct(
#[Autowire(lazy: true)]
private readonly Importer $importer,
#[Autowire(lazy: true)]
private readonly PackageImporter $packageImporter,
private readonly Composer $composer,
private readonly FunctionResolver $functionResolver,
private readonly FunctionLoader $functionLoader,
private readonly ContextRegistry $contextRegistry,
Expand All @@ -49,17 +49,9 @@ public function __construct(

public function boot(InputInterface $input, OutputInterface $output): void
{
$this->packageImporter->requireAutoload();

$this->eventDispatcher->dispatch(new BeforeBootEvent($this->application));

$allowRemotePackage = true;

if ($_SERVER['CASTOR_NO_REMOTE'] ?? false) {
$allowRemotePackage = false;
} elseif (true !== $input->getParameterOption('--no-remote', true)) {
$allowRemotePackage = false;
}
$allowRemotePackage = $this->composer->isRemoteAllowed();

$this->addMount(new Mount($this->rootDir, allowRemotePackage: $allowRemotePackage));

Expand All @@ -69,6 +61,8 @@ public function boot(InputInterface $input, OutputInterface $output): void

$this->load($mount, $currentFunctions, $currentClasses, $input, $output);
}

$this->composer->requireAutoload();
}

public function addMount(Mount $mount): void
Expand All @@ -88,10 +82,7 @@ private function load(
OutputInterface $output
): void {
if ($mount->allowRemotePackage) {
$update = true !== $input->getParameterOption('--update-remotes', true);
$displayProgress = 'list' !== $input->getFirstArgument();

$this->packageImporter->install($mount, $update, $displayProgress);
$this->composer->install($mount->path);
}

try {
Expand Down
2 changes: 1 addition & 1 deletion tests/Generated/ImportComposerNotExistingTest.php.err.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ In castor.php line 5:
Could not import "foo/bar" in ".../tests/fixtures/broken/import-composer-not-existing/castor.php" on line 5. Reason: The package "foo/bar" is not installed, make sure you required it in your castor.composer.json file.


In PackageImporter.php line XXXX:
In Composer.php line XXXX:

The package "foo/bar" is not installed, make sure you required it in your castor.composer.json file.

Expand Down
2 changes: 1 addition & 1 deletion tests/Generated/ImportInvalidFormatTest.php.err.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ In castor.php line 5:
Could not import "invalid-package-name" in ".../tests/fixtures/broken/import-invalid-format/castor.php" on line 5. Reason: The import path must be formatted like this: "composer://<organization>/<repository>".


In PackageImporter.php line XXXX:
In Composer.php line XXXX:

The import path must be formatted like this: "composer://<organization>/<repository>".

Expand Down
2 changes: 1 addition & 1 deletion tests/Generated/ImportInvalidPackageTest.php.err.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ In castor.php line 5:
Could not import "foo/bar" in ".../tests/fixtures/broken/import-invalid-package/castor.php" on line 5. Reason: The package "foo/bar" is not installed, make sure you required it in your castor.composer.json file.


In PackageImporter.php line XXXX:
In Composer.php line XXXX:

The package "foo/bar" is not installed, make sure you required it in your castor.composer.json file.

Expand Down

0 comments on commit 636a246

Please sign in to comment.