Skip to content
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
128 changes: 128 additions & 0 deletions src/Phaseolies/Console/Commands/MakeSignalCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
<?php

namespace Phaseolies\Console\Commands;

use Phaseolies\Console\Schedule\Command;

class MakeSignalCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $name = 'make:signal {name} {--settle} {--connection=}';

/**
* The description of the console command.
*
* @var string
*/
protected $description = 'Create a new signal class';

/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
return $this->executeWithTiming(function () {
[$name, $parts, $className] = $this->splitGeneratedName((string) $this->argument('name'));
$connection = $this->option('connection');
$connection = is_string($connection) && $connection !== '' ? $connection : null;

if ($className === '' || $this->generatedNameError($name) !== null) {
$this->displayError('The signal name must be a valid class name.');
return Command::FAILURE;
}

if ($connection !== null && !preg_match('/^[A-Za-z0-9_.\-]+$/', $connection)) {
$this->displayError('The connection name may only contain letters, numbers, dots, dashes and underscores.');
return Command::FAILURE;
}

$namespace = 'App\\Signals' . (count($parts) > 0 ? '\\' . implode('\\', $parts) : '');
$filePath = $this->generatedFilePath('src/Signals', $name);

// Check if signal already exists
if (file_exists($filePath)) {
$this->displayError('Signal already exists at:');
$this->line('<fg=white>' . $this->relativePath($filePath) . '</>');
return Command::FAILURE;
}

// Create directory if needed
$directoryPath = dirname($filePath);
if (!is_dir($directoryPath)) {
mkdir($directoryPath, 0755, true);
}

// A connection only makes sense for a signal that waits for a transaction
$settle = (bool) $this->option('settle') || $connection !== null;

// Generate and save signal class
$content = $this->generateSignalContent($namespace, $className, $settle, $connection);
file_put_contents($filePath, $content);

$this->displaySuccess('Signal created successfully');
$this->line('<fg=yellow>📁 File:</> <fg=white>' . $this->relativePath($filePath) . '</>');
$this->newLine();
$this->line('<fg=yellow>📌 Signal Class:</> <fg=white>' . $className . '</>');

if ($settle) {
$this->newLine();
$this->line('<fg=yellow>⏳ Delivery:</> <fg=white>after the transaction commits'
. ($connection !== null ? " (connection: {$connection})" : '') . '</>');
}

return Command::SUCCESS;
});
}

/**
* Generate signal class content.
*
* @param string $namespace
* @param string $className
* @param bool $settle
* @param string|null $connection
* @return string
*/
protected function generateSignalContent(
string $namespace,
string $className,
bool $settle = false,
?string $connection = null
): string {
$import = '';
$attribute = '';

if ($settle) {
$import = "\nuse Phaseolies\\Signals\\Attributes\\DeliverOnSettle;\n";
$attribute = $connection !== null
? "#[DeliverOnSettle(connection: '{$connection}')]\n"
: "#[DeliverOnSettle]\n";
}

return <<<EOT
<?php

namespace {$namespace};
{$import}
{$attribute}class {$className}
{
/**
* Create a new signal instance
*
* @return void
*/
public function __construct()
{
//
}
}

EOT;
}
}
30 changes: 30 additions & 0 deletions src/Phaseolies/Console/Schedule/Command.php
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,31 @@ protected function normalizeGeneratedName(string $name): string
return trim($normalized, '/');
}

/**
* Check every segment of a generated class/path name
*
* @param string $name
* @return string|null
*/
protected function generatedNameError(string $name): ?string
{
$normalized = $this->normalizeGeneratedName($name);
if ($normalized === '') {
return 'The name must not be empty.';
}

foreach (explode('/', $normalized) as $segment) {
if ($segment === '.' || $segment === '..') {
return 'The name must not contain "." or ".." segments.';
}
if (!preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $segment)) {
return 'Every part of the name must be a valid class or namespace name; "' . $segment . '" is not.';
}
}

return null;
}

/**
* Split a generated class/path name into normalized name, path parts and final class name.
*
Expand Down Expand Up @@ -502,6 +527,11 @@ protected function generatedFilePath(string $baseDirectory, string $name, string
$normalizedName = $this->normalizeGeneratedName($name);
$relativePath = trim($baseDirectory, '/\\');

// Whatever the command validated, a generated file never leaves its directory.
if (in_array('..', explode('/', $normalizedName), true) || in_array('.', explode('/', $normalizedName), true)) {
throw new \InvalidArgumentException('A generated name must not contain "." or ".." segments.');
}

if ($normalizedName !== '') {
$relativePath .= '/' . $normalizedName;
}
Expand Down
108 changes: 103 additions & 5 deletions src/Phaseolies/Database/Database.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,13 @@ class Database
*/
protected static $transactions = [];

/**
* Signals waiting for a transaction to settle, per connection and nesting level
*
* @var array<string, array<int, array<int, array{0: \Phaseolies\Signals\SignalBus, 1: object}>>>
*/
protected static $pendingSignals = [];

/**
* The driver instances for each connection
*
Expand Down Expand Up @@ -200,12 +207,15 @@ public function commit(): void
{
$pdo = $this->getPdo();
$connection = $this->connection ?? config('database.default');
$level = static::$transactions[$connection] ?? 0;

if (static::$transactions[$connection] === 1) {
if ($level === 1) {
$pdo->commit();
}

static::$transactions[$connection] = max(0, static::$transactions[$connection] - 1);
static::$transactions[$connection] = max(0, $level - 1);

static::settleSignals($connection, $level);
}

/**
Expand All @@ -218,14 +228,99 @@ public function rollBack(): void
{
$pdo = $this->getPdo();
$connection = $this->connection ?? config('database.default');
$level = static::$transactions[$connection] ?? 0;

// Dropped first, so a rollback that itself fails can never leak them.
static::discardSignals($connection, $level);

if (static::$transactions[$connection] === 1) {
if ($level === 1) {
$pdo->rollBack();
} else {
$pdo->exec("ROLLBACK TO SAVEPOINT trans" . static::$transactions[$connection]);
$pdo->exec("ROLLBACK TO SAVEPOINT trans" . $level);
}

static::$transactions[$connection] = max(0, $level - 1);
}

/**
* Hold a signal until the open transaction on a connection settles
*
* @param \Phaseolies\Signals\SignalBus $bus
* @param object $signal
* @param string|null $connection
* @return bool
*/
public static function stageSignal(\Phaseolies\Signals\SignalBus $bus, object $signal, ?string $connection = null): bool
{
$connection = $connection ?: config('database.default');
$level = static::$transactions[$connection] ?? 0;

if ($level === 0) {
return false;
}

static::$pendingSignals[$connection][$level][] = [$bus, $signal];

return true;
}

/**
* Hand the signals of a committed level to the parent, or deliver them at the outermost level
*
* @param string $connection
* @param int $level
* @return void
*/
protected static function settleSignals(string $connection, int $level): void
{
$signals = static::$pendingSignals[$connection][$level] ?? null;

if ($signals === null) {
return;
}

unset(static::$pendingSignals[$connection][$level]);

if ($level > 1) {
static::$pendingSignals[$connection][$level - 1] = array_merge(
static::$pendingSignals[$connection][$level - 1] ?? [],
$signals
);

return;
}

if (empty(static::$pendingSignals[$connection])) {
unset(static::$pendingSignals[$connection]);
}

foreach ($signals as [$bus, $signal]) {
$bus->settle($signal);
}
}

static::$transactions[$connection] = max(0, static::$transactions[$connection] - 1);
/**
* Drop the signals held by a level and every level inside it
*
* @param string $connection
* @param int $level
* @return void
*/
protected static function discardSignals(string $connection, int $level): void
{
if (!isset(static::$pendingSignals[$connection])) {
return;
}

foreach (array_keys(static::$pendingSignals[$connection]) as $held) {
if ($held >= $level) {
unset(static::$pendingSignals[$connection][$held]);
}
}

if (empty(static::$pendingSignals[$connection])) {
unset(static::$pendingSignals[$connection]);
}
}

/**
Expand Down Expand Up @@ -631,6 +726,8 @@ public function disconnect(?string $connection = null): bool
static::$transactions[$connection] = 0;
}

unset(static::$pendingSignals[$connection]);

return true;
} catch (\Throwable $e) {
if (function_exists('error_log')) {
Expand Down Expand Up @@ -714,5 +811,6 @@ public function cleanupAllConnections(): void
static::$connections = [];
static::$drivers = [];
static::$transactions = [];
static::$pendingSignals = [];
}
}
19 changes: 19 additions & 0 deletions src/Phaseolies/Helpers/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,25 @@ function defer(callable $callback)
}
}

if (!function_exists('signal')) {
/**
* Get the signal bus, or emit a signal when one is given
*
* @param object|null $signal
* @return \Phaseolies\Signals\SignalBus|void
*/
function signal(?object $signal = null)
{
$bus = app('signal');

if ($signal === null) {
return $bus;
}

$bus->emit($signal);
}
}

if (!function_exists('request')) {
/**
* Creates a new request instance to handle HTTP requests.
Expand Down
5 changes: 5 additions & 0 deletions src/Phaseolies/Launchers/FacadeLauncher.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Phaseolies\Support\ViteManager;
use Phaseolies\Support\StringService;
use Phaseolies\Support\Storage\StorageFileService;
use Phaseolies\Signals\SignalBus;
use Phaseolies\Support\Session;
use Phaseolies\Support\Mail\MailService;
use Phaseolies\Support\LoggerService;
Expand Down Expand Up @@ -105,6 +106,10 @@ public function register()
// This handles db related jobs
$this->app->singleton('db', Database::class);

// Bind the 'signal' service to a singleton instance of the SignalBus class.
// This handles signals that can wait for a database transaction to settle
$this->app->singleton('signal', SignalBus::class);

// Bind the 'app' service to a singleton instance of the Application class.
// This handles app related jobs
$this->app->singleton('app', Application::class);
Expand Down
12 changes: 12 additions & 0 deletions src/Phaseolies/Signals/Attributes/DeliverOnSettle.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

namespace Phaseolies\Signals\Attributes;

#[\Attribute(\Attribute::TARGET_CLASS)]
class DeliverOnSettle
{
/**
* @param string|null $connection Connection whose transaction to wait for, null for the default one
*/
public function __construct(public readonly ?string $connection = null) {}
}
Loading
Loading