initial commit

This commit is contained in:
rsgrinko committed 2026-09-12 23:55:44 +03:00
commit 3f64f4a49a
221 files changed
+26665

No files matched your search

+239
View File
@@ -0,0 +1,239 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console;
use Rsgrinko\Proton\Support\Config;
use Throwable;
/**
* Консольная утилита: `php bin/proton <команда> [аргументы]`.
*
* Здесь только разбор аргументов, реестр команд и справка. Команды ядра
* перечислены в COMMANDS, свои приложение дописывает в config/commands.php —
* файл возвращает список классов.
*/
final class Application
{
/**
* Команды ядра по разделам — в этом же порядке печатается справка.
*
* @var array<string, array<int, class-string<Command>>>
*/
private const COMMANDS = [
'Установка и обслуживание' => [
Commands\InstallCommand::class,
Commands\MigrateCommand::class,
Commands\MigrateStatusCommand::class,
Commands\MigrateRollbackCommand::class,
Commands\SeedCommand::class,
Commands\AppKeyCommand::class,
Commands\StatusCommand::class,
Commands\RouteListCommand::class,
Commands\CacheClearCommand::class,
Commands\LogsPurgeCommand::class,
],
'Разработка' => [
Commands\ServeCommand::class,
Commands\TestCommand::class,
Commands\MakeCrudCommand::class,
Commands\MakeModelCommand::class,
Commands\MakeControllerCommand::class,
Commands\MakeMigrationCommand::class,
Commands\MakeJobCommand::class,
Commands\MakeCommandCommand::class,
Commands\MakeTestCommand::class,
],
'Очередь и расписание' => [
Commands\WorkerCommand::class,
Commands\WorkerRestartCommand::class,
Commands\ScheduleRunCommand::class,
Commands\QueueStatusCommand::class,
Commands\QueueRetryCommand::class,
Commands\QueuePurgeCommand::class,
],
'Пользователи и доступ' => [
Commands\UserCreateCommand::class,
Commands\UserListCommand::class,
Commands\UserPasswordCommand::class,
Commands\UserDeleteCommand::class,
Commands\RoleListCommand::class,
Commands\KeyCreateCommand::class,
Commands\KeyListCommand::class,
Commands\KeyRevokeCommand::class,
],
'Почта' => [
Commands\MailTestCommand::class,
],
];
/** @var array<int, string> Позиционные аргументы */
private array $args = [];
/** @var array<string, string> Опции вида --name=value */
private array $options = [];
/**
* @param array<int, string> $argv
*/
public function run(array $argv): int
{
$name = $argv[1] ?? 'help';
$this->parseArguments(array_slice($argv, 2));
if (in_array($name, ['help', '--help', '-h', 'list'], true)) {
return $this->help();
}
$command = $this->find($name);
if ($command === null) {
return $this->unknown($name);
}
try {
return $command->withInput($this->args, $this->options)->run();
} catch (Throwable $e) {
$this->line('ОШИБКА: ' . $e->getMessage());
if ((bool) Config::get('app.debug', false)) {
$this->line($e->getFile() . ':' . $e->getLine());
$this->line($e->getTraceAsString());
}
return 1;
}
}
/**
* Все команды — нужно справке и тестам.
*
* @return array<int, Command>
*/
public static function commands(): array
{
$commands = [];
foreach (self::groups() as $group) {
foreach ($group as $class) {
$commands[] = new $class();
}
}
return $commands;
}
/**
* Команды ядра плюс команды приложения.
*
* @return array<string, array<int, class-string<Command>>>
*/
public static function groups(): array
{
$groups = self::COMMANDS;
$file = APP_ROOT . '/config/commands.php';
if (is_file($file)) {
/** @var array<int, class-string<Command>> $own */
$own = (array) require $file;
if ($own !== []) {
$groups['Команды приложения'] = $own;
}
}
return $groups;
}
private function find(string $name): ?Command
{
foreach (self::commands() as $command) {
if ($command->name() === $name) {
return $command;
}
}
return null;
}
private function help(): int
{
$this->line((string) Config::get('app.name', 'Proton') . ' — консольная утилита');
$this->line('');
$this->line('Использование: php bin/proton <команда> [аргументы]');
foreach (self::groups() as $title => $classes) {
$this->line('');
$this->line($title . ':');
foreach ($classes as $class) {
/** @var Command $command */
$command = new $class();
$usage = $command->usage();
// Длинную строку вызова не растягиваем колонкой
if (mb_strlen($usage) > 40) {
$this->line(' ' . $usage);
$this->line(' ' . $command->description());
continue;
}
$this->line(' ' . $this->pad($usage, 42) . $command->description());
}
}
$this->line('');
$this->line('Настройки берутся из .env, см. .env.example.');
return 0;
}
private function unknown(string $command): int
{
$this->line('Неизвестная команда: ' . $command);
$this->line('Список команд: php bin/proton help');
return 1;
}
/**
* @param array<int, string> $arguments
*/
private function parseArguments(array $arguments): void
{
foreach ($arguments as $argument) {
if (str_starts_with($argument, '--')) {
$argument = substr($argument, 2);
if (str_contains($argument, '=')) {
[$name, $value] = explode('=', $argument, 2);
$this->options[$name] = $value;
} else {
$this->options[$argument] = '1';
}
continue;
}
$this->args[] = $argument;
}
}
private function pad(string $text, int $width): string
{
$length = mb_strlen($text);
return $length >= $width ? $text . ' ' : $text . str_repeat(' ', $width - $length);
}
private function line(string $text = ''): void
{
echo $text . PHP_EOL;
}
}
+183
View File
@@ -0,0 +1,183 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console;
/**
* Одна команда консольной утилиты.
*
* Новая команда — новый класс в Console/Commands (или в App\Commands) и строка
* в реестре Application. Аргументы и опции разбирает Application и передаёт
* готовыми; печать — через line(), колонки — через pad().
*/
abstract class Command
{
/** @var array<int, string> Позиционные аргументы */
protected array $args = [];
/** @var array<string, string> Опции вида --name=value */
protected array $options = [];
/** @var callable(string): void Куда печатать — подменяется в тестах */
private $output;
public function __construct()
{
$this->output = static function (string $line): void {
echo $line . PHP_EOL;
};
}
/**
* Имя команды: 'queue:retry'.
*/
abstract public function name(): string;
/**
* Строка для справки — что команда делает.
*/
abstract public function description(): string;
/**
* Как её звать: 'queue:retry <id>'. По умолчанию — просто имя.
*/
public function usage(): string
{
return $this->name();
}
/**
* Выполняет команду и возвращает код выхода: 0 — всё хорошо.
*/
abstract public function run(): int;
/**
* @param array<int, string> $args
* @param array<string, string> $options
* @param (callable(string): void)|null $output
*/
public function withInput(array $args, array $options, ?callable $output = null): static
{
$this->args = $args;
$this->options = $options;
if ($output !== null) {
$this->output = $output;
}
return $this;
}
protected function line(string $text = ''): void
{
($this->output)($text);
}
/**
* Заметное сообщение об успехе и об ошибке — просто чтобы глаз цеплялся.
*/
protected function ok(string $text): void
{
$this->line(' ' . $text);
}
protected function fail(string $text): void
{
$this->line('ОШИБКА: ' . $text);
}
/**
* Колонка нужной ширины. str_pad считает байты, а в русских словах их вдвое
* больше — выравнивание разъезжается.
*/
protected function pad(string $text, int $width): string
{
$length = mb_strlen($text);
return $length >= $width ? $text . ' ' : $text . str_repeat(' ', $width - $length);
}
/**
* Таблица: заголовок и строки. Ширина колонок считается по содержимому.
*
* @param array<int, string> $headers
* @param array<int, array<int, string>> $rows
*/
protected function table(array $headers, array $rows): void
{
$widths = [];
foreach ($headers as $index => $title) {
$widths[$index] = mb_strlen($title);
}
foreach ($rows as $row) {
foreach ($row as $index => $cell) {
$widths[$index] = max($widths[$index] ?? 0, mb_strlen((string) $cell));
}
}
$line = '';
foreach ($headers as $index => $title) {
$line .= $this->pad($title, $widths[$index] + 2);
}
$this->line(rtrim($line));
foreach ($rows as $row) {
$line = '';
foreach ($row as $index => $cell) {
$line .= $this->pad((string) $cell, $widths[$index] + 2);
}
$this->line(rtrim($line));
}
}
protected function arg(int $index, string $default = ''): string
{
return $this->args[$index] ?? $default;
}
protected function option(string $name, ?string $default = null): ?string
{
return $this->options[$name] ?? $default;
}
protected function hasOption(string $name): bool
{
return isset($this->options[$name]);
}
/**
* Спрашивает у человека. В неинтерактивном запуске возвращает значение
* по умолчанию — команда не должна вешаться в cron.
*/
protected function ask(string $question, string $default = ''): string
{
if (!stream_isatty(STDIN)) {
return $default;
}
$this->line($question . ($default !== '' ? ' [' . $default . ']' : '') . ':');
$answer = trim((string) fgets(STDIN));
return $answer !== '' ? $answer : $default;
}
/**
* Подтверждение опасного действия. Без --force в неинтерактивном запуске — «нет».
*/
protected function confirm(string $question): bool
{
if ($this->hasOption('force')) {
return true;
}
return in_array(strtolower($this->ask($question . ' (да/нет)', 'нет')), ['да', 'y', 'yes'], true);
}
}
@@ -0,0 +1,77 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Auth\Crypto;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Support\Config;
/**
* ключ приложения.
*
* Ключом подписываются куки и шифруются секреты в базе. Менять его на живом
* проекте нельзя: зашифрованные значения станут нечитаемыми, а все куки
* недействительными — поэтому существующий ключ команда не трогает без --force.
*/
final class AppKeyCommand extends Command
{
public function name(): string
{
return 'app:key';
}
public function description(): string
{
return 'создать APP_KEY и записать его в .env';
}
public function usage(): string
{
return 'app:key [--force] [--show]';
}
public function run(): int
{
$key = Crypto::generateKey();
if ($this->hasOption('show')) {
$this->line($key);
return 0;
}
$file = APP_ROOT . '/.env';
if (!is_file($file)) {
$this->fail('Файл .env не найден. Скопируйте .env.example в .env и повторите');
return 1;
}
$current = (string) Config::get('app.key', '');
if ($current !== '' && !$this->hasOption('force')) {
$this->fail('APP_KEY уже задан. Смена ключа сделает нечитаемым всё зашифрованное; если это осознанно — --force');
return 1;
}
$content = (string) file_get_contents($file);
$content = preg_match('/^APP_KEY=.*$/m', $content) === 1
? (string) preg_replace('/^APP_KEY=.*$/m', 'APP_KEY=' . $key, $content)
: rtrim($content) . PHP_EOL . 'APP_KEY=' . $key . PHP_EOL;
if (@file_put_contents($file, $content) === false) {
$this->fail('Не удалось записать .env');
return 1;
}
$this->ok('APP_KEY записан в .env');
return 0;
}
}
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Cache\Cache;
use Rsgrinko\Proton\Console\Command;
/**
* очистить кэш.
*/
final class CacheClearCommand extends Command
{
public function name(): string
{
return 'cache:clear';
}
public function description(): string
{
return 'очистить кэш приложения';
}
public function run(): int
{
Cache::flush();
$this->ok('Кэш очищен');
return 0;
}
}
@@ -0,0 +1,296 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Auth\Password;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Install\Installer;
use Rsgrinko\Proton\Models\User;
use Rsgrinko\Proton\Support\Config;
use Rsgrinko\Proton\Support\Validator;
/**
* Интерактивная установка.
*
* Спрашивает всё, что нужно, и делает всё, что нужно: пишет .env, создаёт ключ,
* при необходимости заводит базу, накатывает схему и заводит администратора.
* То же самое умеет веб-мастер на /install — движок у них общий (Install\Installer),
* иначе два установщика неизбежно разъехались бы.
*
* В неинтерактивном запуске (деплой, CI) ответы передаются опциями:
* php bin/proton install --force --name="Проект" --url=https://example.com \
* --db=mysql --db-host=127.0.0.1 --db-name=proton --db-user=proton --db-password=… \
* --admin=admin --admin-password=… --admin-email=admin@example.com
*/
final class InstallCommand extends Command
{
public function name(): string
{
return 'install';
}
public function description(): string
{
return 'установить приложение: .env, ключ, база, схема, администратор';
}
public function usage(): string
{
return 'install [--force] [--name=] [--url=] [--db=sqlite|mysql] [--admin=] [--admin-password=]';
}
public function run(): int
{
$this->line('Установка ' . (string) Config::get('app.name', 'Proton'));
$this->line('');
if (Installer::installed() && !$this->hasOption('force')) {
$this->line('Приложение уже установлено. Повторить установку — с ключом --force');
return 0;
}
if (!$this->requirements()) {
return 1;
}
$env = $this->basics();
$database = $this->database($env);
if ($database === null) {
return 1;
}
$env = array_merge($env, $database['env']);
$env = array_merge($env, $this->mail());
Installer::writeEnv($env);
$this->ok('.env записан');
Installer::ensureKey();
$this->ok('Ключ приложения на месте');
$applied = Installer::migrate();
$this->ok($applied === [] ? 'Схема уже накатана' : 'Применено миграций: ' . count($applied));
if (!$this->admin()) {
return 1;
}
$this->line('');
$this->line('Готово. Дальше:');
$this->line(' php bin/proton serve — поднять сервер для разработки');
$this->line(' php bin/proton status — самопроверка');
$this->line(' php bin/proton worker — воркер очереди (на бою — службой)');
return 0;
}
/**
* Проверка окружения: без неё установка упадёт на середине.
*/
private function requirements(): bool
{
$rows = [];
$ok = true;
foreach (Installer::requirements() as $check) {
$rows[] = [$check['ok'] ? '[+]' : '[!]', $check['title'], $check['value']];
if (!$check['ok']) {
$ok = false;
}
}
$this->table(['', 'Проверка', 'Значение'], $rows);
$this->line('');
if ($ok) {
return true;
}
foreach (Installer::requirements() as $check) {
if ($check['hint'] !== '') {
$this->fail($check['title'] . ': ' . $check['hint']);
}
}
return false;
}
/**
* Название, адрес, часовой пояс.
*
* @return array<string, string>
*/
private function basics(): array
{
$name = (string) $this->option('name', '') ?: $this->ask('Название приложения', (string) Config::get('app.name', 'Proton'));
$url = (string) $this->option('url', '') ?: $this->ask('Адрес приложения', (string) Config::get('app.url', 'http://localhost:8000'));
$zone = (string) $this->option('timezone', '') ?: $this->ask('Часовой пояс', (string) Config::get('app.timezone', 'Europe/Moscow'));
return [
'APP_NAME' => $name,
'APP_URL' => rtrim($url, '/'),
'APP_TIMEZONE' => $zone,
'APP_ENV' => (string) $this->option('env', 'production'),
// На бою отладка выключена: тексты ошибок посторонним видеть незачем
'APP_DEBUG' => $this->hasOption('debug') ? 'true' : 'false',
];
}
/**
* Настройки базы и проверка, что до неё можно достучаться.
*
* @param array<string, string> $env
*
* @return array{env: array<string, string>}|null
*/
private function database(array $env): ?array
{
$driver = (string) $this->option('db', '') ?: $this->ask('База данных: sqlite или mysql', 'sqlite');
$driver = strtolower(trim($driver)) === 'mysql' ? 'mysql' : 'sqlite';
if ($driver === 'sqlite') {
$path = (string) $this->option('db-path', '') ?: APP_ROOT . '/var/app.sqlite';
$settings = Installer::databaseSettings(['DB_DRIVER' => 'sqlite', 'DB_PATH' => $path]);
$error = Installer::checkDatabase($settings);
if ($error !== null) {
$this->fail('Файл базы не открывается: ' . $error);
return null;
}
$this->ok('SQLite: ' . $path);
return ['env' => ['DB_DRIVER' => 'sqlite', 'DB_PATH' => $path]];
}
$answers = [
'DB_DRIVER' => 'mysql',
'DB_HOST' => (string) $this->option('db-host', '') ?: $this->ask('Хост MySQL', '127.0.0.1'),
'DB_PORT' => (string) $this->option('db-port', '') ?: $this->ask('Порт', '3306'),
'DB_DATABASE' => (string) $this->option('db-name', '') ?: $this->ask('Имя базы', 'proton'),
'DB_USERNAME' => (string) $this->option('db-user', '') ?: $this->ask('Пользователь', 'root'),
'DB_PASSWORD' => (string) $this->option('db-password', '') ?: $this->ask('Пароль', ''),
];
$settings = Installer::databaseSettings($answers);
$error = Installer::checkDatabase($settings);
if ($error !== null) {
// Базы может просто не быть — это обычный шаг установки
$created = Installer::createMysqlDatabase($settings);
if ($created !== null) {
$this->fail('Не подключиться к MySQL: ' . $error);
return null;
}
$this->ok('База ' . $answers['DB_DATABASE'] . ' создана');
$error = Installer::checkDatabase($settings);
if ($error !== null) {
$this->fail('Не подключиться к MySQL: ' . $error);
return null;
}
}
$this->ok('MySQL: ' . $answers['DB_DATABASE'] . ' на ' . $answers['DB_HOST']);
return ['env' => $answers];
}
/**
* Чем отправлять письма.
*
* @return array<string, string>
*/
private function mail(): array
{
$driver = (string) $this->option('mail', '') ?: $this->ask('Почта: mail, smtp, mailer, log или null', 'mail');
$driver = in_array($driver, ['mail', 'smtp', 'mailer', 'log', 'null'], true) ? $driver : 'mail';
$from = (string) $this->option('mail-from', '') ?: $this->ask('Адрес отправителя', 'noreply@example.com');
if (!Validator::isEmail($from)) {
$this->line(' Адрес отправителя выглядит странно — поправьте MAIL_FROM в .env позже');
}
$env = ['MAIL_DRIVER' => $driver, 'MAIL_FROM' => $from];
if ($driver === 'smtp') {
$env['SMTP_HOST'] = $this->ask('SMTP-хост', 'smtp.yandex.ru');
$env['SMTP_PORT'] = $this->ask('SMTP-порт', '587');
$env['SMTP_USER'] = $this->ask('Пользователь SMTP', $from);
$env['SMTP_PASSWORD'] = $this->ask('Пароль SMTP', '');
$env['SMTP_ENCRYPTION'] = $this->ask('Шифрование: tls, ssl или пусто', 'tls');
}
if ($driver === 'mailer') {
$env['MAIL_SERVICE_URL'] = $this->ask('Адрес почтового сервиса', '');
$env['MAIL_SERVICE_KEY'] = $this->ask('Ключ проекта', '');
}
return $env;
}
/**
* Первый пользователь — администратор.
*/
private function admin(): bool
{
if (User::query()->count() > 0) {
$this->ok('Пользователи уже есть — администратора не завожу');
return true;
}
$login = (string) $this->option('admin', '') ?: $this->ask('Логин администратора', 'admin');
$email = (string) $this->option('admin-email', '') ?: $this->ask('Почта администратора', '');
$password = (string) $this->option('admin-password', '');
$generated = false;
if ($password === '') {
$password = $this->ask('Пароль (пусто — придумаю сам)', '');
}
if ($password === '') {
$password = Password::generate();
$generated = true;
}
$error = Password::check($password);
if ($error !== null) {
$this->fail($error);
return false;
}
$user = Installer::createAdmin($login, $password, $email);
$this->ok('Администратор ' . (string) $user->login . ' заведён');
if ($generated) {
$this->line(' Пароль: ' . $password);
$this->line(' Он больше нигде не сохранён — запишите сейчас');
}
return true;
}
}
@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Models\ApiToken;
use Rsgrinko\Proton\Models\User;
/**
* выпустить ключ API.
*/
final class KeyCreateCommand extends Command
{
public function name(): string
{
return 'key:create';
}
public function description(): string
{
return 'выпустить ключ доступа к API';
}
public function usage(): string
{
return 'key:create <название> --owner=<логин> [--ips=]';
}
public function run(): int
{
$name = trim($this->arg(0));
$login = (string) $this->option('owner', '');
if ($login === '') {
$this->fail('Укажите владельца: --owner=логин');
return 1;
}
$user = User::findBy('login', $login);
if ($user === null) {
$this->fail('Пользователь не найден: ' . $login);
return 1;
}
$issued = ApiToken::issue($name, $user->id(), (string) $this->option('ips', ''));
$this->ok('Ключ выпущен для ' . $login);
$this->line('');
$this->line(' ' . $issued['key']);
$this->line('');
// В базе только хеш: показать ключ второй раз будет негде
$this->line(' Сохраните его сейчас — больше он нигде не появится');
return 0;
}
}
@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Models\ApiToken;
use Rsgrinko\Proton\Models\User;
/**
* список ключей API.
*/
final class KeyListCommand extends Command
{
public function name(): string
{
return 'key:list';
}
public function description(): string
{
return 'список ключей доступа к API';
}
public function run(): int
{
/** @var array<int, ApiToken> $tokens */
$tokens = ApiToken::query()->orderBy('id')->get();
if ($tokens === []) {
$this->line('Ключей нет');
return 0;
}
$owners = [];
foreach (User::all() as $user) {
$owners[$user->id()] = (string) $user->login;
}
$rows = [];
foreach ($tokens as $token) {
$rows[] = [
(string) $token->id(),
(string) $token->name,
$token->mask(),
$owners[(int) $token->raw('user_id')] ?? '—',
(int) $token->raw('active') === 1 ? 'да' : 'нет',
(string) ($token->raw('last_used_at') ?? '—'),
];
}
$this->table(['id', 'Название', 'Ключ', 'Владелец', 'Активен', 'Последнее использование'], $rows);
return 0;
}
}
@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Models\ApiToken;
/**
* отключить ключ API.
*/
final class KeyRevokeCommand extends Command
{
public function name(): string
{
return 'key:revoke';
}
public function description(): string
{
return 'отключить ключ доступа';
}
public function usage(): string
{
return 'key:revoke <id>';
}
public function run(): int
{
$token = ApiToken::find((int) $this->arg(0));
if ($token === null) {
$this->fail('Ключ не найден');
return 1;
}
// Не удаляем, а отключаем: строка нужна, чтобы понимать, чем ходили раньше
$token->forceFill(['active' => 0])->save();
$this->ok('Ключ ' . $token->mask() . ' отключён');
return 0;
}
}
@@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Support\Logger;
/**
* удалить старые логи.
*/
final class LogsPurgeCommand extends Command
{
public function name(): string
{
return 'logs:purge';
}
public function description(): string
{
return 'удалить логи старше указанного срока';
}
public function usage(): string
{
return 'logs:purge [--days=30]';
}
public function run(): int
{
$days = $this->hasOption('days') ? (int) $this->option('days') : null;
$removed = (new Logger())->purge($days);
if ($removed === []) {
$this->line('Удалять нечего');
return 0;
}
foreach ($removed as $file) {
$this->ok('удалён ' . $file);
}
return 0;
}
}
@@ -0,0 +1,79 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Mail\Mail;
use Rsgrinko\Proton\Mail\Message;
use Rsgrinko\Proton\Support\Config;
use Rsgrinko\Proton\Support\Validator;
use Throwable;
/**
* проверить отправку почты.
*/
final class MailTestCommand extends Command
{
public function name(): string
{
return 'mail:test';
}
public function description(): string
{
return 'отправить пробное письмо текущим драйвером';
}
public function usage(): string
{
return 'mail:test <адрес> [--queue]';
}
public function run(): int
{
$to = trim($this->arg(0));
if (!Validator::isEmail($to)) {
$this->fail('Укажите адрес: php bin/proton mail:test user@example.com');
return 1;
}
$driver = Mail::driver()->name();
$message = Message::to($to)
->subject('Пробное письмо ' . (string) Config::get('app.name', 'Proton'))
->text(
"Это пробное письмо.\n\n"
. 'Драйвер: ' . $driver . "\n"
. 'Отправитель: ' . (string) Config::get('mail.from_email', '') . "\n"
. 'Время: ' . date('d.m.Y H:i:s') . "\n"
);
try {
if ($this->hasOption('queue')) {
$id = $message->queue();
$this->ok('Письмо поставлено в очередь, задача ' . $id . ' — его отправит воркер');
return 0;
}
$message->send();
$this->ok('Письмо отправлено драйвером ' . $driver);
if ($driver === 'log') {
$this->line(' Файл лежит в ' . (string) Config::get('paths.log') . '/mail');
}
return 0;
} catch (Throwable $e) {
$this->fail($e->getMessage());
return 1;
}
}
}
+126
View File
@@ -0,0 +1,126 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Support\Str;
/**
* Общая часть генераторов: взять заготовку из stubs/, подставить имя, положить
* файл на место. Сами генераторы отличаются только заготовкой и каталогом.
*
* Существующий файл не перезаписываем никогда: генератор не должен затирать код.
*/
abstract class MakeCommand extends Command
{
/**
* Имя файла заготовки в каталоге stubs/.
*/
abstract protected function stub(): string;
/**
* Каталог, куда класть результат, — от корня проекта.
*/
abstract protected function directory(): string;
/**
* Что за штука создаётся — для сообщения.
*/
abstract protected function what(): string;
/**
* Суффикс имени класса: Controller, Job, Test.
*/
protected function suffix(): string
{
return '';
}
public function run(): int
{
$raw = trim($this->arg(0));
if ($raw === '') {
$this->fail('Укажите имя: php bin/proton ' . $this->name() . ' Имя');
return 1;
}
$class = Str::studly($raw);
$suffix = $this->suffix();
if ($suffix !== '' && !str_ends_with($class, $suffix)) {
$class .= $suffix;
}
$path = APP_ROOT . '/' . trim($this->directory(), '/') . '/' . $class . '.php';
if (is_file($path)) {
// Существующий файл не трогаем никогда: генератор не должен затирать код
$this->fail('Уже есть — ' . $this->what() . ': ' . $this->relative($path));
return 1;
}
$content = $this->render($class);
$dir = dirname($path);
if (!is_dir($dir) && !@mkdir($dir, 0775, true) && !is_dir($dir)) {
$this->fail('Не удалось создать каталог ' . $dir);
return 1;
}
if (@file_put_contents($path, $content) === false) {
$this->fail('Не удалось записать файл ' . $path);
return 1;
}
$this->ok('Создано — ' . $this->what() . ': ' . $this->relative($path));
$this->after($class, $path);
return 0;
}
/**
* Что напечатать после создания — подсказка про реестр, миграцию и прочее.
*/
protected function after(string $class, string $path): void
{
}
/**
* Подстановки в заготовке: {{class}}, {{table}} и так далее.
*
* @return array<string, string>
*/
protected function replacements(string $class): array
{
return [
'{{class}}' => $class,
'{{table}}' => Str::plural(Str::snake($class)),
'{{slug}}' => Str::snake($class),
];
}
private function render(string $class): string
{
$stub = APP_ROOT . '/stubs/' . $this->stub();
if (!is_file($stub)) {
return "<?php\n\ndeclare(strict_types=1);\n";
}
return strtr((string) file_get_contents($stub), $this->replacements($class));
}
protected function relative(string $path): string
{
return str_replace(APP_ROOT . '/', '', str_replace('\\', '/', $path));
}
}
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
/**
* создать консольную команду.
*/
final class MakeCommandCommand extends MakeCommand
{
public function name(): string
{
return 'make:command';
}
public function description(): string
{
return 'создать консольную команду в app/Commands';
}
public function usage(): string
{
return 'make:command <Имя>';
}
protected function stub(): string
{
return 'command.stub';
}
protected function directory(): string
{
return 'app/Commands';
}
protected function what(): string
{
return 'Команда';
}
protected function suffix(): string
{
return 'Command';
}
protected function after(string $class, string $path): void
{
$this->line(' Впишите её в config/commands.php — иначе она не появится в справке.');
}
}
@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
/**
* создать контроллер.
*/
final class MakeControllerCommand extends MakeCommand
{
public function name(): string
{
return 'make:controller';
}
public function description(): string
{
return 'создать контроллер в app/Controllers';
}
public function usage(): string
{
return 'make:controller <Имя> [--admin]';
}
protected function stub(): string
{
return 'controller.stub';
}
protected function directory(): string
{
return $this->hasOption('admin') ? 'app/Controllers/Admin' : 'app/Controllers/Web';
}
protected function what(): string
{
return 'Контроллер';
}
protected function suffix(): string
{
return 'Controller';
}
/**
* @return array<string, string>
*/
protected function replacements(string $class): array
{
return array_merge(parent::replacements($class), [
'{{namespace}}' => $this->hasOption('admin') ? 'App\\Controllers\\Admin' : 'App\\Controllers\\Web',
]);
}
protected function after(string $class, string $path): void
{
$this->line(' Осталось добавить маршрут в routes/' . ($this->hasOption('admin') ? 'admin.php' : 'web.php'));
}
}
@@ -0,0 +1,527 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Support\Str;
/**
* Раздел целиком: модель, миграция, контроллер, три вьюхи и тест.
*
* Остальные make-команды делают по одному файлу — здесь их шесть, и все они
* должны сойтись друг с другом: имена полей в форме, правила проверки, колонки
* таблицы и подстановки во вьюхах. Руками это собирается полчаса, и каждый раз
* что-нибудь забывается.
*
* php bin/proton make:crud Order --fields="title:string:Название,total:decimal:Сумма,paid:bool:Оплачен"
*
* Поле описывается как имя:тип[:подпись]. Типы: string, text, int, decimal,
* bool, date, datetime, email. Подпись — то, что увидит человек в форме и в
* сообщении об ошибке; без неё берётся имя поля.
*
* Маршруты, право и пункт меню команда не дописывает, а печатает готовыми
* кусками: routes/web.php и config/menu.php — код приложения, и лезть в них
* автоматической правкой опаснее, чем скопировать три строки.
*/
final class MakeCrudCommand extends Command
{
/** Типы полей: как их писать в миграции, чем проверять, во что приводить */
private const TYPES = [
'string' => ['schema' => "string('%s')", 'rule' => 'nullable|max:191', 'cast' => '', 'input' => 'text'],
'text' => ['schema' => "text('%s')", 'rule' => 'nullable|max:20000', 'cast' => '', 'input' => 'textarea'],
'int' => ['schema' => "integer('%s')", 'rule' => 'nullable|integer', 'cast' => 'int', 'input' => 'number'],
'decimal' => ['schema' => "decimal('%s')", 'rule' => 'nullable|numeric', 'cast' => 'float', 'input' => 'decimal'],
'bool' => ['schema' => "boolean('%s')", 'rule' => 'nullable|boolean', 'cast' => 'bool', 'input' => 'checkbox'],
'date' => ['schema' => "date('%s')", 'rule' => 'nullable|date', 'cast' => '', 'input' => 'date'],
'datetime' => ['schema' => "dateTime('%s')", 'rule' => 'nullable|date', 'cast' => '', 'input' => 'datetime-local'],
'email' => ['schema' => "string('%s')", 'rule' => 'nullable|email|max:191', 'cast' => '', 'input' => 'email'],
];
public function name(): string
{
return 'make:crud';
}
public function description(): string
{
return 'создать раздел целиком: модель, миграция, контроллер, вьюхи, тест';
}
public function usage(): string
{
return 'make:crud <Имя> [--fields="имя:тип:подпись,…"] [--no-soft-delete] [--force]';
}
public function run(): int
{
$raw = trim($this->arg(0));
if ($raw === '') {
$this->fail('Укажите имя раздела: php bin/proton make:crud Order');
return 1;
}
$class = Str::studly($raw);
$fields = $this->fields();
if ($fields === []) {
$this->fail('Не разобрал ни одного поля. Пример: --fields="title:string:Название,total:decimal:Сумма"');
return 1;
}
$names = $this->names($class);
$plan = $this->plan($names, $fields);
// Сначала смотрим все файлы разом: раздел, собранный наполовину,
// хуже, чем не собранный вовсе
$existing = [];
foreach ($plan as $path => $content) {
if (is_file($path)) {
$existing[] = $this->relative($path);
}
}
if ($existing !== [] && !$this->hasOption('force')) {
$this->fail('Уже есть: ' . implode(', ', $existing));
$this->line(' Сначала уберите их или дайте другое имя (--force перезапишет).');
return 1;
}
foreach ($plan as $path => $content) {
$dir = dirname($path);
if (!is_dir($dir) && !@mkdir($dir, 0775, true) && !is_dir($dir)) {
$this->fail('Не удалось создать каталог ' . $dir);
return 1;
}
if (@file_put_contents($path, $content) === false) {
$this->fail('Не удалось записать файл ' . $path);
return 1;
}
$this->ok('Создано: ' . $this->relative($path));
}
$this->hints($names, $fields);
return 0;
}
/**
* Имена, которые понадобятся во всех заготовках сразу.
*
* @return array<string, string>
*/
private function names(string $class): array
{
$snake = Str::snake($class);
$plural = Str::plural($snake);
return [
'class' => $class,
'variable' => lcfirst($class),
'table' => $plural,
'route' => str_replace('_', '-', $plural),
'views' => $plural,
'title' => $this->option('title', $class) ?? $class,
];
}
/**
* Разбирает --fields в список полей.
*
* @return array<int, array{name: string, type: string, label: string}>
*/
private function fields(): array
{
$raw = trim((string) $this->option('fields', ''));
if ($raw === '') {
// Без описания полей раздел всё равно должен получиться рабочим
$raw = 'title:string:Название,body:text:Текст';
}
$fields = [];
foreach (explode(',', $raw) as $chunk) {
$parts = array_map('trim', explode(':', trim($chunk)));
$name = Str::snake((string) ($parts[0] ?? ''));
if ($name === '' || !preg_match('/^[a-z][a-z0-9_]*$/', $name)) {
continue;
}
$type = strtolower((string) ($parts[1] ?? 'string'));
if (!isset(self::TYPES[$type])) {
$this->line(' Тип «' . $type . '» не знаю, беру string для поля ' . $name);
$type = 'string';
}
$fields[] = [
'name' => $name,
'type' => $type,
'label' => ($parts[2] ?? '') !== '' ? (string) $parts[2] : $name,
];
}
return $fields;
}
/**
* Что и куда записать: путь файла -> его содержимое.
*
* @param array<string, string> $names
* @param array<int, array{name: string, type: string, label: string}> $fields
*
* @return array<string, string>
*/
private function plan(array $names, array $fields): array
{
$soft = !$this->hasOption('no-soft-delete');
$replacements = [
'{{class}}' => $names['class'],
'{{plural}}' => Str::plural($names['class']),
'{{variable}}' => $names['variable'],
'{{table}}' => $names['table'],
'{{route}}' => $names['route'],
'{{views}}' => $names['views'],
'{{title}}' => $names['title'],
'{{fillable}}' => $this->fillable($fields),
'{{casts}}' => $this->casts($fields),
'{{soft}}' => $soft ? "\n /** Запись не пропадает совсем: помечается deleted_at и уходит из списков */\n protected bool \$softDelete = true;\n" : '',
'{{softSchema}}' => $soft ? "\n \$table->softDeletes();" : '',
'{{schema}}' => $this->schema($fields),
'{{rules}}' => $this->rules($fields),
'{{labels}}' => $this->labels($fields),
'{{before}}' => $this->before($fields),
'{{after}}' => $this->after($fields),
'{{form}}' => $this->form($fields),
'{{heads}}' => $this->columns($fields)['heads'],
'{{cells}}' => $this->columns($fields)['cells'],
'{{props}}' => $this->props($fields),
'{{first}}' => $fields[0]['name'],
'{{firstLabel}}' => $fields[0]['label'],
'{{testValue}}' => $this->testValue($fields[0]),
];
$root = APP_ROOT;
return [
$root . '/app/Models/' . $names['class'] . '.php' => $this->render('crud/model.stub', $replacements),
$root . '/app/Controllers/Web/' . Str::plural($names['class']) . 'Controller.php' => $this->render('crud/controller.stub', $replacements),
$root . '/migrations/' . date('YmdHis') . '_create_' . $names['table'] . '.php' => $this->render('crud/migration.stub', $replacements),
$root . '/resources/views/' . $names['views'] . '/index.php' => $this->render('crud/index.stub', $replacements),
$root . '/resources/views/' . $names['views'] . '/form.php' => $this->render('crud/form.stub', $replacements),
$root . '/resources/views/' . $names['views'] . '/show.php' => $this->render('crud/show.stub', $replacements),
$root . '/tests/' . Str::plural($names['class']) . 'Test.php' => $this->render('crud/test.stub', $replacements),
];
}
/**
* @param array<int, array{name: string, type: string, label: string}> $fields
*/
private function fillable(array $fields): string
{
return implode(', ', array_map(static fn (array $f): string => "'" . $f['name'] . "'", $fields));
}
/**
* @param array<int, array{name: string, type: string, label: string}> $fields
*/
private function casts(array $fields): string
{
$lines = [];
$width = max($this->width($fields), mb_strlen('user_id'));
foreach ($fields as $field) {
$cast = self::TYPES[$field['type']]['cast'];
if ($cast !== '') {
$pad = str_repeat(' ', $width - mb_strlen($field['name']));
$lines[] = " '" . $field['name'] . "'" . $pad . " => '" . $cast . "',";
}
}
$lines[] = " 'user_id'" . str_repeat(' ', $width - mb_strlen('user_id')) . " => 'int',";
return implode("\n", $lines);
}
/**
* @param array<int, array{name: string, type: string, label: string}> $fields
*/
private function schema(array $fields): string
{
$lines = [];
foreach ($fields as $field) {
$call = sprintf(self::TYPES[$field['type']]['schema'], $field['name']);
$lines[] = ' $table->' . $call . ($field['type'] === 'bool' ? '->default(0)' : '->nullable()') . ';';
}
return implode("\n", $lines);
}
/**
* @param array<int, array{name: string, type: string, label: string}> $fields
*/
private function rules(array $fields): string
{
$lines = [];
$width = $this->width($fields);
foreach ($fields as $index => $field) {
// Первое поле — название раздела, без него запись не опознать
$rule = $index === 0 && $field['type'] === 'string' ? 'required|max:191' : self::TYPES[$field['type']]['rule'];
$lines[] = " '" . $field['name'] . "'" . str_repeat(' ', $width - mb_strlen($field['name'])) . " => '" . $rule . "',";
}
return implode("\n", $lines);
}
/**
* @param array<int, array{name: string, type: string, label: string}> $fields
*/
private function labels(array $fields): string
{
$lines = [];
$width = $this->width($fields);
foreach ($fields as $field) {
$lines[] = " '" . $field['name'] . "'" . str_repeat(' ', $width - mb_strlen($field['name'])) . " => '" . $field['label'] . "',";
}
return implode("\n", $lines);
}
/**
* Снимок значений до правки — для журнала изменений.
*
* @param array<int, array{name: string, type: string, label: string}> $fields
*/
private function before(array $fields): string
{
$parts = array_map(
static fn (array $f): string => "'" . $f['name'] . "' => \$record->raw('" . $f['name'] . "')",
$fields
);
return implode(', ', $parts);
}
/**
* @param array<int, array{name: string, type: string, label: string}> $fields
*/
private function after(array $fields): string
{
$lines = [];
foreach ($fields as $field) {
$lines[] = " '" . $field['name'] . "' => \$record->raw('" . $field['name'] . "'),";
}
return implode("\n", $lines);
}
/**
* Поля формы: у каждого типа свой вид ввода.
*
* @param array<int, array{name: string, type: string, label: string}> $fields
*/
private function form(array $fields): string
{
$blocks = [];
foreach ($fields as $index => $field) {
$name = $field['name'];
$label = $field['label'];
$input = self::TYPES[$field['type']]['input'];
$auto = $index === 0 ? ' autofocus' : '';
$need = $index === 0 && $field['type'] === 'string' ? ' required' : '';
if ($input === 'textarea') {
$blocks[] = <<<HTML
<label>
<span>{$label}</span>
<textarea name="{$name}"><?= View::e((string) \$record->{$name}) ?></textarea>
</label>
HTML;
continue;
}
if ($input === 'checkbox') {
$blocks[] = <<<HTML
<label class="inline" style="margin-bottom: 12px;">
<input type="checkbox" name="{$name}" value="1" <?= \$record->{$name} ? 'checked' : '' ?>>
<span>{$label}</span>
</label>
HTML;
continue;
}
$type = $input === 'decimal' ? 'number" step="0.01' : $input;
$blocks[] = <<<HTML
<label>
<span>{$label}</span>
<input type="{$type}" name="{$name}" value="<?= View::e((string) \$record->raw('{$name}')) ?>"{$auto}{$need}>
</label>
HTML;
}
return implode("\n\n", $blocks);
}
/**
* Колонки списка: первое поле — ссылка на карточку, дальше ещё два.
*
* @param array<int, array{name: string, type: string, label: string}> $fields
*
* @return array{heads: string, cells: string}
*/
private function columns(array $fields): array
{
$extra = array_slice($fields, 1, 2);
$heads = '';
$cells = '';
foreach ($extra as $field) {
$heads .= "\n <th class=\"hide-sm\">" . $field['label'] . '</th>';
$value = $field['type'] === 'bool'
? "<?= \$record->" . $field['name'] . " ? 'да' : 'нет' ?>"
: "<?= View::e(Str::limit((string) \$record->raw('" . $field['name'] . "'), 80)) ?>";
$cells .= "\n <td class=\"hide-sm muted small\">" . $value . '</td>';
}
return ['heads' => $heads, 'cells' => $cells];
}
/**
* Пары «подпись — значение» для карточки.
*
* @param array<int, array{name: string, type: string, label: string}> $fields
*/
private function props(array $fields): string
{
$lines = [];
foreach ($fields as $field) {
$value = $field['type'] === 'bool'
? "\$record->" . $field['name'] . " ? 'да' : 'нет'"
: "(string) \$record->raw('" . $field['name'] . "')";
$lines[] = " '" . $field['label'] . "' => " . $value . ',';
}
return implode("\n", $lines);
}
/**
* @param array{name: string, type: string, label: string} $field
*/
private function testValue(array $field): string
{
return match ($field['type']) {
'int', 'decimal' => '42',
'bool' => '1',
'date' => "'2026-01-01'",
'datetime' => "'2026-01-01 10:00:00'",
'email' => "'test@example.com'",
default => "'Проверка'",
};
}
/**
* @param array<int, array{name: string, type: string, label: string}> $fields
*/
private function width(array $fields): int
{
$width = 0;
foreach ($fields as $field) {
$width = max($width, mb_strlen($field['name']));
}
return $width;
}
/**
* Что осталось сделать руками: маршруты, право, меню.
*
* @param array<string, string> $names
* @param array<int, array{name: string, type: string, label: string}> $fields
*/
private function hints(array $names, array $fields): void
{
$route = $names['route'];
$class = Str::plural($names['class']) . 'Controller';
$title = $names['title'];
$this->line('');
$this->line('Осталось три шага.');
$this->line('');
$this->line('1. Маршруты — routes/web.php, внутрь группы auth:');
$this->line('');
$this->line(' $router->group([\'prefix\' => \'/' . $route . '\'], function (Router $router): void {');
$this->line(' $router->get(\'\', [' . $class . '::class, \'index\'])->middleware(\'can:' . $route . '.view\')->name(\'' . $route . '.index\');');
$this->line(' $router->get(\'/new\', [' . $class . '::class, \'create\'])->middleware(\'can:' . $route . '.manage\')->name(\'' . $route . '.create\');');
$this->line(' $router->post(\'/new\', [' . $class . '::class, \'store\'])->middleware(\'can:' . $route . '.manage\');');
$this->line(' $router->get(\'/{id:\d+}\', [' . $class . '::class, \'show\'])->middleware(\'can:' . $route . '.view\')->name(\'' . $route . '.show\');');
$this->line(' $router->get(\'/{id:\d+}/edit\', [' . $class . '::class, \'edit\'])->middleware(\'can:' . $route . '.manage\')->name(\'' . $route . '.edit\');');
$this->line(' $router->post(\'/{id:\d+}/edit\', [' . $class . '::class, \'update\'])->middleware(\'can:' . $route . '.manage\');');
$this->line(' $router->post(\'/{id:\d+}/delete\', [' . $class . '::class, \'delete\'])->middleware(\'can:' . $route . '.manage\')->name(\'' . $route . '.delete\');');
$this->line(' });');
$this->line('');
$this->line(' use App\Controllers\Web\\' . $class . '; — вверху файла');
$this->line('');
$this->line('2. Права — config/permissions.php:');
$this->line('');
$this->line(' Permission::register(\'' . $route . '.view\', \'Смотреть: ' . $title . '\', \'' . $title . '\');');
$this->line(' Permission::register(\'' . $route . '.manage\', \'Заводить и править: ' . $title . '\', \'' . $title . '\');');
$this->line('');
$this->line('3. Пункт меню — config/menu.php:');
$this->line('');
$this->line(' [\'title\' => \'' . $title . '\', \'route\' => \'' . $route . '.index\', \'permission\' => \'' . $route . '.view\'],');
$this->line('');
$this->line('Потом: php bin/proton migrate и php bin/proton test');
}
/**
* @param array<string, string> $replacements
*/
private function render(string $stub, array $replacements): string
{
$path = APP_ROOT . '/stubs/' . $stub;
if (!is_file($path)) {
return "<?php\n\ndeclare(strict_types=1);\n";
}
return strtr((string) file_get_contents($path), $replacements);
}
private function relative(string $path): string
{
return str_replace(APP_ROOT . '/', '', str_replace('\\', '/', $path));
}
}
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
/**
* создать задачу очереди.
*/
final class MakeJobCommand extends MakeCommand
{
public function name(): string
{
return 'make:job';
}
public function description(): string
{
return 'создать задачу очереди в app/Jobs';
}
public function usage(): string
{
return 'make:job <Имя>';
}
protected function stub(): string
{
return 'job.stub';
}
protected function directory(): string
{
return 'app/Jobs';
}
protected function what(): string
{
return 'Задача';
}
protected function after(string $class, string $path): void
{
$this->line(' Поставить в очередь: Queue::push(App\\Jobs\\' . $class . '::class, [...]);');
}
}
@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Support\Str;
/**
* создать миграцию.
*
* Имя файла — отметка времени плюс имя: 20260912093000_create_notes.php.
* По отметке считается порядок наката, поэтому берётся текущее время, а не
* номер по счёту: два человека, работающие параллельно, не столкнутся.
*/
final class MakeMigrationCommand extends Command
{
public function name(): string
{
return 'make:migration';
}
public function description(): string
{
return 'создать файл миграции';
}
public function usage(): string
{
return 'make:migration <имя_миграции> [--table=]';
}
public function run(): int
{
$raw = trim($this->arg(0));
if ($raw === '') {
$this->fail('Укажите имя: php bin/proton make:migration create_notes');
return 1;
}
$slug = strtolower((string) preg_replace('/[^a-zA-Z0-9_]+/', '_', $raw));
$slug = trim($slug, '_');
if ($slug === '') {
$this->fail('Имя миграции должно состоять из латиницы, цифр и подчёркиваний');
return 1;
}
$class = Str::studly($slug);
$name = date('YmdHis') . '_' . $slug;
$path = APP_ROOT . '/migrations/' . $name . '.php';
// Таблицу угадываем по имени: create_notes -> notes
$table = (string) $this->option('table', '');
if ($table === '' && preg_match('/^(create|add_.*_to|drop)_([a-z0-9_]+?)(_table)?$/', $slug, $matches) === 1) {
$table = $matches[2];
}
$stub = APP_ROOT . '/stubs/migration.stub';
$content = is_file($stub)
? strtr((string) file_get_contents($stub), ['{{class}}' => $class, '{{table}}' => $table !== '' ? $table : 'table_name'])
: "<?php\n\ndeclare(strict_types=1);\n";
if (@file_put_contents($path, $content) === false) {
$this->fail('Не удалось записать файл ' . $path);
return 1;
}
$this->ok('Миграция создана: migrations/' . $name . '.php');
$this->line(' Накатить: php bin/proton migrate');
return 0;
}
}
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
/**
* создать модель.
*/
final class MakeModelCommand extends MakeCommand
{
public function name(): string
{
return 'make:model';
}
public function description(): string
{
return 'создать модель в app/Models';
}
public function usage(): string
{
return 'make:model <Имя>';
}
protected function stub(): string
{
return 'model.stub';
}
protected function directory(): string
{
return 'app/Models';
}
protected function what(): string
{
return 'Модель';
}
protected function after(string $class, string $path): void
{
$this->line(' Не забудьте миграцию: php bin/proton make:migration create_' . $this->replacements($class)['{{table}}']);
}
}
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
/**
* создать файл тестов.
*/
final class MakeTestCommand extends MakeCommand
{
public function name(): string
{
return 'make:test';
}
public function description(): string
{
return 'создать файл тестов в tests';
}
public function usage(): string
{
return 'make:test <Имя>';
}
protected function stub(): string
{
return 'test.stub';
}
protected function directory(): string
{
return 'tests';
}
protected function what(): string
{
return 'Файл тестов';
}
protected function suffix(): string
{
return 'Test';
}
protected function after(string $class, string $path): void
{
$this->line(' Запустить только его: php bin/proton test --filter=' . $class);
}
}
@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Database\Migrator;
/**
* применить миграции.
*/
final class MigrateCommand extends Command
{
public function name(): string
{
return 'migrate';
}
public function description(): string
{
return 'применить новые миграции';
}
public function usage(): string
{
return 'migrate [--pretend]';
}
public function run(): int
{
$migrator = new Migrator();
if ($this->hasOption('pretend')) {
$plan = $migrator->pretend();
if ($plan === []) {
$this->line('Новых миграций нет');
return 0;
}
foreach ($plan as $name => $queries) {
$this->line($name . ':');
foreach ($queries as $query) {
$this->line(' ' . $query);
}
}
return 0;
}
$applied = $migrator->run();
if ($applied === []) {
$this->line('Новых миграций нет');
return 0;
}
foreach ($applied as $name) {
$this->ok('применена ' . $name);
}
// Шаги, которые уже были в базе: так выглядит докат миграции,
// упавшей на середине, — молчать об этом нельзя
$skipped = $migrator->skipped();
if ($skipped !== []) {
$this->line('');
$this->line('Пропущено как уже выполненное:');
foreach ($skipped as $query) {
$this->line(' ' . $query);
}
}
return 0;
}
}
@@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Database\Migrator;
/**
* откатить последнюю пачку миграций.
*/
final class MigrateRollbackCommand extends Command
{
public function name(): string
{
return 'migrate:rollback';
}
public function description(): string
{
return 'откатить последнюю пачку миграций';
}
public function usage(): string
{
return 'migrate:rollback [--steps=1] [--force]';
}
public function run(): int
{
// Откат удаляет колонки вместе с данными — на живой базе это крайняя мера
if (!$this->confirm('Откат удалит колонки вместе с данными. Продолжать?')) {
$this->line('Отменено');
return 1;
}
$steps = max(1, (int) $this->option('steps', '1'));
$rolledBack = (new Migrator())->rollback($steps);
if ($rolledBack === []) {
$this->line('Откатывать нечего');
return 0;
}
foreach ($rolledBack as $name) {
$this->ok('откачена ' . $name);
}
return 0;
}
}
@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Database\Migrator;
/**
* что применено, что ждёт.
*/
final class MigrateStatusCommand extends Command
{
public function name(): string
{
return 'migrate:status';
}
public function description(): string
{
return 'показать состояние миграций';
}
public function run(): int
{
$migrator = new Migrator();
$applied = $migrator->applied();
$pending = $migrator->pending();
$unknown = $migrator->unknown();
$rows = [];
foreach (array_keys($migrator->migrations()) as $name) {
$rows[] = [$name, in_array($name, $applied, true) ? 'применена' : 'ждёт'];
}
if ($rows === []) {
$this->line('Миграций нет');
return 0;
}
$this->table(['Миграция', 'Состояние'], $rows);
if ($unknown !== []) {
$this->line('');
$this->line('Есть в базе, но нет в коде (откат релиза?):');
foreach ($unknown as $name) {
$this->line(' ' . $name);
}
}
$this->line('');
$this->line('Применено: ' . count($applied) . ', ждёт: ' . count($pending));
return 0;
}
}
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Queue\Queue;
/**
* подчистить очередь.
*/
final class QueuePurgeCommand extends Command
{
public function name(): string
{
return 'queue:purge';
}
public function description(): string
{
return 'удалить выполненные задачи старше срока';
}
public function usage(): string
{
return 'queue:purge [--days=7]';
}
public function run(): int
{
$days = max(0, (int) $this->option('days', '7'));
$removed = Queue::purge($days);
$stuck = Queue::releaseStuck();
$this->ok('Удалено выполненных: ' . $removed);
if ($stuck > 0) {
$this->ok('Возвращено зависших: ' . $stuck);
}
return 0;
}
}
@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Database\Connection;
use Rsgrinko\Proton\Queue\Queue;
/**
* повторить задачи.
*/
final class QueueRetryCommand extends Command
{
public function name(): string
{
return 'queue:retry';
}
public function description(): string
{
return 'вернуть в очередь неудавшуюся задачу или все сразу';
}
public function usage(): string
{
return 'queue:retry <id|--failed>';
}
public function run(): int
{
if ($this->hasOption('failed')) {
$ids = Connection::instance()->select(
'SELECT id FROM jobs WHERE status = :status',
['status' => Queue::FAILED]
);
foreach ($ids as $row) {
Queue::retry((int) $row['id']);
}
$this->ok('Возвращено в очередь: ' . count($ids));
return 0;
}
$id = (int) $this->arg(0);
if ($id === 0) {
$this->fail('Укажите номер задачи или --failed');
return 1;
}
if (!Queue::retry($id)) {
$this->fail('Задача ' . $id . ' не найдена');
return 1;
}
$this->ok('Задача ' . $id . ' возвращена в очередь');
return 0;
}
}
@@ -0,0 +1,88 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Database\Connection;
use Rsgrinko\Proton\Queue\Queue;
/**
* состояние очереди.
*/
final class QueueStatusCommand extends Command
{
public function name(): string
{
return 'queue:status';
}
public function description(): string
{
return 'сколько задач в очереди и что упало';
}
public function usage(): string
{
return 'queue:status [--failed]';
}
public function run(): int
{
$stats = Queue::stats();
if ($stats === []) {
$this->line('Таблицы очереди ещё нет — накатите миграции');
return 0;
}
$labels = [
Queue::QUEUED => 'в очереди',
Queue::RUNNING => 'выполняется',
Queue::DONE => 'выполнено',
Queue::FAILED => 'с ошибкой',
];
$rows = [];
foreach ($labels as $status => $label) {
$rows[] = [$label, (string) ($stats[$status] ?? 0)];
}
$this->table(['Состояние', 'Задач'], $rows);
if (!$this->hasOption('failed')) {
return 0;
}
$failed = Connection::instance()->select(
'SELECT id, job_class, attempts, error FROM jobs WHERE status = :status ORDER BY id DESC LIMIT 20',
['status' => Queue::FAILED]
);
if ($failed === []) {
$this->line('');
$this->line('Неудавшихся задач нет');
return 0;
}
$this->line('');
$this->table(
['id', 'Задача', 'Попыток', 'Ошибка'],
array_map(
static fn (array $row): array => [
(string) $row['id'],
(string) $row['job_class'],
(string) $row['attempts'],
mb_substr((string) $row['error'], 0, 60),
],
$failed
)
);
return 0;
}
}
@@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Access\Permission;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Models\Role;
/**
* роли и их права.
*/
final class RoleListCommand extends Command
{
public function name(): string
{
return 'role:list';
}
public function description(): string
{
return 'роли и их права (правятся в панели)';
}
public function usage(): string
{
return 'role:list [название]';
}
public function run(): int
{
$name = trim($this->arg(0));
if ($name !== '') {
$role = Role::findBy('name', $name);
if ($role === null) {
$this->fail('Роль не найдена: ' . $name);
return 1;
}
$this->line('Роль «' . $role->name . '»' . ($role->isSystem() ? ' (встроенная)' : ''));
$this->line('');
foreach ($role->permissions() as $code) {
$this->line(' ' . $this->pad($code, 24) . Permission::label($code));
}
return 0;
}
$rows = [];
foreach (Role::all() as $role) {
$rows[] = [
(string) $role->id(),
(string) $role->name,
$role->isSystem() ? 'встроенная' : 'обычная',
(string) count($role->permissions()),
(string) $role->usersCount(),
];
}
if ($rows === []) {
$this->line('Ролей нет — накатите миграции');
return 0;
}
$this->table(['id', 'Название', 'Тип', 'Прав', 'Пользователей'], $rows);
return 0;
}
}
@@ -0,0 +1,74 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Http\Kernel;
/**
* карта адресов.
*/
final class RouteListCommand extends Command
{
public function name(): string
{
return 'route:list';
}
public function description(): string
{
return 'показать все маршруты приложения';
}
public function usage(): string
{
return 'route:list [строка для поиска]';
}
public function run(): int
{
$needle = mb_strtolower($this->arg(0));
$rows = [];
foreach ((new Kernel())->router()->routes() as $route) {
$line = implode('|', $route->methods) . ' ' . $route->pattern . ' ' . (string) $route->name;
if ($needle !== '' && !str_contains(mb_strtolower($line), $needle)) {
continue;
}
$handler = is_array($route->handler)
? $this->shortClass((string) $route->handler[0]) . '::' . (string) $route->handler[1]
: 'функция';
$rows[] = [
implode('|', $route->methods),
$route->pattern,
$handler,
implode(', ', $route->middleware),
(string) $route->name,
];
}
if ($rows === []) {
$this->line('Ничего не нашлось');
return 0;
}
$this->table(['Метод', 'Путь', 'Обработчик', 'Прослойки', 'Имя'], $rows);
$this->line('');
$this->line('Всего: ' . count($rows));
return 0;
}
private function shortClass(string $class): string
{
$short = strrchr($class, '\\');
return $short === false ? $class : substr($short, 1);
}
}
@@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Queue\Scheduler;
/**
* прогнать расписание.
*
* Нужна там, где вместо воркера-демона используется cron: строка
* `* * * * * php bin/proton schedule:run` делает то же, что воркер между задачами.
*/
final class ScheduleRunCommand extends Command
{
public function name(): string
{
return 'schedule:run';
}
public function description(): string
{
return 'выполнить задачи расписания, которым пора';
}
public function usage(): string
{
return 'schedule:run [--list]';
}
public function run(): int
{
if ($this->hasOption('list')) {
$rows = [];
foreach (Scheduler::tasks() as $task) {
$rows[] = [
$task['name'],
$task['at'] !== '' ? 'ежедневно в ' . $task['at'] : 'раз в ' . $task['interval'] . ' с',
$task['last'] !== '' ? $task['last'] : 'ни разу',
];
}
if ($rows === []) {
$this->line('Расписание пусто — задачи объявляются в config/schedule.php');
return 0;
}
$this->table(['Задача', 'Когда', 'Последний запуск'], $rows);
return 0;
}
$done = Scheduler::run();
if ($done === []) {
$this->line('Пока нечего выполнять');
return 0;
}
foreach ($done as $name) {
$this->ok('выполнена ' . $name);
}
return 0;
}
}
@@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
/**
* стартовые данные.
*
* Сам файл лежит в приложении (database/seed.php) и возвращает функцию:
* ядро не знает, чем наполнять чужой проект. Роли и первый пользователь
* заводятся миграциями и страницей первого запуска, а не здесь.
*/
final class SeedCommand extends Command
{
public function name(): string
{
return 'seed';
}
public function description(): string
{
return 'залить стартовые данные (database/seed.php)';
}
public function run(): int
{
$file = APP_ROOT . '/database/seed.php';
if (!is_file($file)) {
$this->line('Файл database/seed.php не найден — заливать нечего');
return 0;
}
$seed = require $file;
if (!is_callable($seed)) {
$this->fail('database/seed.php должен возвращать функцию');
return 1;
}
$seed(function (string $message): void {
$this->ok($message);
});
$this->line('Готово');
return 0;
}
}
@@ -0,0 +1,97 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Support\Config;
/**
* поднять встроенный веб-сервер PHP.
*
* Ровно для разработки: сервер однопоточный, статику отдаёт сам и на бою
* не используется. Порт можно не задавать — если он занят, команда возьмёт
* следующий свободный и скажет об этом.
*/
final class ServeCommand extends Command
{
public function name(): string
{
return 'serve';
}
public function description(): string
{
return 'запустить встроенный сервер для разработки';
}
public function usage(): string
{
return 'serve [--host=127.0.0.1] [--port=8000] [--tries=10]';
}
public function run(): int
{
$host = (string) $this->option('host', (string) Config::get('app.serve_host', '127.0.0.1'));
$port = (int) $this->option('port', (string) Config::get('app.serve_port', '8000'));
$tries = max(1, (int) $this->option('tries', '10'));
$root = APP_ROOT . '/public';
if (!is_file($root . '/index.php')) {
$this->fail('Не найден public/index.php — сервер запускать нечего');
return 1;
}
$free = $this->freePort($host, $port, $tries);
if ($free === 0) {
$this->fail('Свободный порт не нашёлся: занято всё от ' . $port . ' до ' . ($port + $tries - 1));
return 1;
}
if ($free !== $port) {
$this->line('Порт ' . $port . ' занят, беру ' . $free);
}
$this->line((string) Config::get('app.name', 'Proton') . ' слушает http://' . $host . ':' . $free);
$this->line('Каталог: ' . $root);
$this->line('Остановить — Ctrl+C');
$this->line('');
// Роутер отдаёт существующие файлы как есть, остальное уводит в index.php —
// так встроенный сервер ведёт себя похоже на nginx с try_files
$router = APP_ROOT . '/public/router.php';
$command = escapeshellarg(PHP_BINARY)
. ' -S ' . escapeshellarg($host . ':' . $free)
. ' -t ' . escapeshellarg($root)
. (is_file($router) ? ' ' . escapeshellarg($router) : '');
// passthru, а не exec: вывод сервера должен идти человеку в терминал
passthru($command, $code);
return $code;
}
/**
* Первый свободный порт начиная с указанного. 0 — не нашлось.
*/
private function freePort(string $host, int $port, int $tries): int
{
for ($candidate = $port; $candidate < $port + $tries; $candidate++) {
$socket = @stream_socket_server('tcp://' . $host . ':' . $candidate, $code, $error);
if ($socket !== false) {
fclose($socket);
return $candidate;
}
}
return 0;
}
}
@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Support\Diagnostics;
/**
* состояние приложения.
*/
final class StatusCommand extends Command
{
public function name(): string
{
return 'status';
}
public function description(): string
{
return 'самопроверка: окружение, база, ключи, очередь';
}
public function run(): int
{
$checks = Diagnostics::run();
$rows = [];
foreach ($checks as $check) {
$rows[] = [$this->mark($check['level']), $check['title'], $check['value']];
}
$this->table(['', 'Проверка', 'Значение'], $rows);
$hints = array_filter($checks, static fn (array $check): bool => $check['hint'] !== '');
if ($hints !== []) {
$this->line('');
$this->line('Что сделать:');
foreach ($hints as $check) {
$this->line(' ' . $check['title'] . ': ' . $check['hint']);
}
}
return Diagnostics::worst($checks) === Diagnostics::ERROR ? 1 : 0;
}
private function mark(string $level): string
{
return match ($level) {
Diagnostics::ERROR => '[!]',
Diagnostics::WARN => '[~]',
default => '[+]',
};
}
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
/**
* прогнать тесты.
*/
final class TestCommand extends Command
{
public function name(): string
{
return 'test';
}
public function description(): string
{
return 'прогнать тесты приложения';
}
public function usage(): string
{
return 'test [--filter=] [--stop-on-failure] [--shuffle[=seed]]';
}
public function run(): int
{
$runner = APP_ROOT . '/tests/run.php';
if (!is_file($runner)) {
$this->fail('Раннер тестов не найден: tests/run.php');
return 1;
}
// Опции передаём раннеру как есть — он разбирает их сам
$GLOBALS['test_options'] = $this->options;
return (int) require $runner;
}
}
@@ -0,0 +1,108 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Auth\Password;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Models\Role;
use Rsgrinko\Proton\Models\User;
use Rsgrinko\Proton\Support\Validator;
/**
* завести пользователя.
*/
final class UserCreateCommand extends Command
{
public function name(): string
{
return 'user:create';
}
public function description(): string
{
return 'завести пользователя';
}
public function usage(): string
{
return 'user:create <логин> [--password=] [--email=] [--name=] [--role=]';
}
public function run(): int
{
$login = trim($this->arg(0));
if ($login === '') {
$this->fail('Укажите логин: php bin/proton user:create ivan');
return 1;
}
if (User::findBy('login', $login) !== null) {
$this->fail('Пользователь с таким логином уже есть');
return 1;
}
$email = (string) $this->option('email', '');
if ($email !== '' && !Validator::isEmail($email)) {
$this->fail('Неверный адрес почты: ' . $email);
return 1;
}
// Пароль не спрашиваем в открытую в неинтерактивном запуске: сгенерируем
// и напечатаем один раз — в базе он всё равно только хешем
$password = (string) $this->option('password', '');
$generated = $password === '';
if ($generated) {
$password = Password::generate();
}
$error = Password::check($password);
if ($error !== null) {
$this->fail($error);
return 1;
}
$role = $this->role();
$user = User::register($login, $password, [
'email' => $email,
'name' => (string) $this->option('name', $login),
'role_id' => $role?->id() ?? 0,
]);
$this->ok('Пользователь ' . $user->login . ' заведён' . ($role !== null ? ', роль «' . $role->name . '»' : ''));
if ($generated) {
$this->line(' Пароль: ' . $password);
$this->line(' Он больше нигде не сохранён — запишите сейчас');
}
return 0;
}
private function role(): ?Role
{
$name = (string) $this->option('role', '');
if ($name !== '') {
return Role::findBy('name', $name);
}
// Роль не указали: первому пользователю даём администратора,
// остальным — обычную, если она есть
if (User::query()->count() === 0) {
return Role::admin();
}
return Role::query()->where('is_system', 0)->first();
}
}
@@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Models\User;
/**
* удалить пользователя.
*/
final class UserDeleteCommand extends Command
{
public function name(): string
{
return 'user:delete';
}
public function description(): string
{
return 'удалить пользователя';
}
public function usage(): string
{
return 'user:delete <логин> [--force]';
}
public function run(): int
{
$login = trim($this->arg(0));
$user = User::findBy('login', $login);
if ($user === null) {
$this->fail('Пользователь не найден: ' . $login);
return 1;
}
// Последнего активного не удаляем: войти станет некем, а страница
// первого запуска откроется всем подряд
if (User::query()->where('active', 1)->count() <= 1 && $user->isActive()) {
$this->fail('Это последний активный пользователь — удалять его нельзя');
return 1;
}
if (!$this->confirm('Удалить пользователя ' . $login . '?')) {
$this->line('Отменено');
return 1;
}
$user->logoutEverywhere();
$user->delete();
$this->ok('Пользователь удалён');
return 0;
}
}
@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Models\Role;
use Rsgrinko\Proton\Models\User;
/**
* список пользователей.
*/
final class UserListCommand extends Command
{
public function name(): string
{
return 'user:list';
}
public function description(): string
{
return 'список пользователей';
}
public function run(): int
{
/** @var array<int, User> $users */
$users = User::query()->orderBy('id')->get();
if ($users === []) {
$this->line('Пользователей нет. Заведите первого: php bin/proton user:create ivan');
return 0;
}
$roles = [];
foreach (Role::all() as $role) {
$roles[$role->id()] = (string) $role->name;
}
$rows = [];
foreach ($users as $user) {
$rows[] = [
(string) $user->id(),
(string) $user->login,
(string) $user->email,
$roles[(int) $user->raw('role_id')] ?? '—',
$user->isActive() ? 'да' : 'нет',
(string) ($user->raw('last_login_at') ?? '—'),
];
}
$this->table(['id', 'Логин', 'Почта', 'Роль', 'Активен', 'Последний вход'], $rows);
return 0;
}
}
@@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Auth\Password;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Models\User;
/**
* сменить пароль.
*/
final class UserPasswordCommand extends Command
{
public function name(): string
{
return 'user:password';
}
public function description(): string
{
return 'сменить пароль пользователю';
}
public function usage(): string
{
return 'user:password <логин> [--password=]';
}
public function run(): int
{
$login = trim($this->arg(0));
$user = User::findBy('login', $login);
if ($user === null) {
$this->fail('Пользователь не найден: ' . $login);
return 1;
}
$password = (string) $this->option('password', '');
$generated = $password === '';
if ($generated) {
$password = Password::generate();
}
$error = Password::check($password);
if ($error !== null) {
$this->fail($error);
return 1;
}
// setPassword заодно гасит все сеансы: пароль меняют, когда его увели
$user->setPassword($password);
$user->save();
$this->ok('Пароль изменён, все сеансы завершены');
if ($generated) {
$this->line(' Новый пароль: ' . $password);
}
return 0;
}
}
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Queue\Queue;
use Rsgrinko\Proton\Queue\Worker;
/**
* воркер очереди.
*/
final class WorkerCommand extends Command
{
public function name(): string
{
return 'worker';
}
public function description(): string
{
return 'разбирать очередь задач и вести расписание';
}
public function usage(): string
{
return 'worker [--once] [--queue=default]';
}
public function run(): int
{
$queue = (string) $this->option('queue', Queue::DEFAULT_QUEUE);
$result = (new Worker($queue))->run($this->hasOption('once'));
$this->line('Выполнено: ' . $result['done'] . ', с ошибкой: ' . $result['failed']);
return 0;
}
}
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Queue\Worker;
/**
* попросить воркер перезапуститься.
*/
final class WorkerRestartCommand extends Command
{
public function name(): string
{
return 'worker:restart';
}
public function description(): string
{
return 'воркер доработает круг и выйдет (служба поднимет его заново)';
}
public function run(): int
{
Worker::requestRestart();
// После выкладки кода это обязательный шаг: воркер держит классы
// в памяти и продолжал бы выполнять задачи старым кодом
$this->ok('Запрос отправлен. Воркер выйдет после текущего круга');
return 0;
}
}