Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generate key command #52

Merged
merged 2 commits into from
Jan 13, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,8 @@ If you discover a security vulnerability within Phenix, please send an e-mail to
## License

The Phenix framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).

## Credits

- [Amphp team](https://amphp.org/)
- [Laravel team](https://laravel.com/)
75 changes: 75 additions & 0 deletions src/Console/Commands/GenerateKey.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
<?php

declare(strict_types=1);

namespace Phenix\Console\Commands;

use Phenix\Facades\Config;
use Phenix\Facades\File;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class GenerateKey extends Command
{
/**
* @var string
*
* @phpcsSuppress SlevomatCodingStandard.TypeHints.PropertyTypeHint
*/
protected static $defaultName = 'key:generate';

/**
* @var string
*
* @phpcsSuppress SlevomatCodingStandard.TypeHints.PropertyTypeHint
*/
protected static $defaultDescription = 'Set the application key.';

protected function configure(): void
{
$this->setHelp('This command allows you to generate and set the application key.');

$this->addArgument('environment', InputArgument::OPTIONAL, 'The environment file', '.env');

$this->addOption('force', 'f', InputOption::VALUE_NONE, 'Force to create queries');
}

protected function execute(InputInterface $input, OutputInterface $output): int
{
$force = $input->getOption('force');

$currentKey = Config::get('app.key');

if ($currentKey && ! $force) {
$output->writeln('<error>Application key is already set. Use --force to override it.</error>');

return Command::FAILURE;
}

$key = 'base64:' . base64_encode(random_bytes(32));
$environment = $input->getArgument('environment');

$environmentData = File::get(base_path($environment));

$replaced = preg_replace(
"/^APP_KEY=.*$/m",
"APP_KEY={$key}",
$environmentData
);

if (empty($replaced) || $replaced === $environmentData) {
$output->writeln('<error>Failed to set the application key.</error>');

return Command::FAILURE;
}

File::put(base_path($environment), $replaced);

$output->writeln('<info>Application key set successfully!.</info>');

return Command::SUCCESS;
}
}
2 changes: 2 additions & 0 deletions src/Providers/CommandsServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Phenix\Providers;

use Phenix\Console\Commands\GenerateKey;
use Phenix\Console\Commands\MakeCollection;
use Phenix\Console\Commands\MakeController;
use Phenix\Console\Commands\MakeMiddleware;
Expand All @@ -26,6 +27,7 @@ public function boot(): void
MakeCollection::class,
MakeQuery::class,
MakeServiceProvider::class,
GenerateKey::class,
]);
}
}
2 changes: 1 addition & 1 deletion src/Testing/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ protected function tearDown(): void
$this->app = null;
}

protected function phenix(string $signature, array $arguments, array $inputs = []): CommandTester
protected function phenix(string $signature, array $arguments = [], array $inputs = []): CommandTester
{
$phenix = App::make(Phenix::class);

Expand Down
73 changes: 73 additions & 0 deletions tests/Unit/Console/GenerateKeyCommandTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?php

declare(strict_types=1);

use Phenix\Contracts\Filesystem\File;
use Phenix\Facades\Config;
use Phenix\Testing\Mock;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Tester\CommandTester;

it('sets the application key', function () {
$mock = Mock::of(File::class)->expect(
get: function (string $path): string {
return 'APP_KEY=' . PHP_EOL;
},
put: fn (string $path) => true,
);

$this->app->swap(File::class, $mock);

/** @var CommandTester $command */
$command = $this->phenix('key:generate');

$command->assertCommandIsSuccessful();

expect($command->getDisplay())->toContain('Application key set successfully!');
});

it('does not set the application key if it is already set', function () {
Config::set('app.key', 'base64:' . base64_encode(random_bytes(32)));

/** @var CommandTester $command */
$command = $this->phenix('key:generate');

expect($command->getStatusCode())->toBe(Command::FAILURE);
expect($command->getDisplay())->toContain('Application key is already set. Use --force to override it.');
});

it('fails on set application key', function () {
$mock = Mock::of(File::class)->expect(
get: fn (string $path): string => '',
);

$this->app->swap(File::class, $mock);

/** @var CommandTester $command */
$command = $this->phenix('key:generate');

expect($command->getStatusCode())->toBe(Command::FAILURE);
expect($command->getDisplay())->toContain('Failed to set the application key');
});

it('sets application key with force option', function () {
Config::set('app.key', 'base64:' . base64_encode(random_bytes(32)));

$mock = Mock::of(File::class)->expect(
get: function (string $path): string {
return 'APP_KEY=' . PHP_EOL;
},
put: fn (string $path) => true,
);

$this->app->swap(File::class, $mock);

/** @var CommandTester $command */
$command = $this->phenix('key:generate', [
'--force' => true,
]);

$command->assertCommandIsSuccessful();

expect($command->getDisplay())->toContain('Application key set successfully!');
});
1 change: 1 addition & 0 deletions tests/fixtures/application/config/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
'env' => env('APP_ENV', fn () => 'local'),
'url' => env('APP_URL', fn () => 'http://127.0.0.1'),
'port' => env('APP_PORT', fn () => 1337),
'key' => env('APP_KEY'),
'middlewares' => [
'global' => [
\Phenix\Http\Middlewares\HandleCors::class,
Expand Down
Loading