Метод warn
Метод warn применяется к экземпляру команды
в методе handle и выводит предупреждающее
сообщение в терминал. Сообщение окрашивается
в жёлтый цвет для привлечения внимания пользователя.
Метод принимает один параметр - строку с текстом
сообщения.
Синтаксис
<?php
$this->warn($message);
?>
Пример
Давайте выведем простое предупреждение о том, что операция может занять много времени:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class WarnExample extends Command
{
protected $signature = 'app:warn-example';
protected $description = 'Example of using warn method';
public function handle()
{
$this->warn('This operation may take a long time.');
}
}
?>
Результат выполнения команды php artisan app:warn-example:
"This operation may take a long time."
Сообщение будет выведено жёлтым цветом.
Пример
Давайте выведем предупреждение перед выполнением опасной операции:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Models\User;
class DangerousCommand extends Command
{
protected $signature = 'app:dangerous';
protected $description = 'Dangerous operation with warning';
public function handle()
{
$this->warn('WARNING: You are about to delete all users!');
$confirmed = $this->confirm('Do you really want to continue?');
if ($confirmed) {
User::truncate();
$this->info('All users deleted successfully.');
} else {
$this->info('Operation cancelled.');
}
}
}
?>
Результат выполнения команды php artisan app:dangerous:
"WARNING: You are about to delete all users!"
"Do you really want to continue? (yes/no) [no]:"
Сначала выводится предупреждение жёлтым цветом, затем запрос подтверждения.
Пример
Давайте используем предупреждение для отображения информации о приближении к лимиту:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Models\Article;
class CheckLimit extends Command
{
protected $signature = 'app:check-limit';
protected $description = 'Check article limit';
public function handle()
{
$count = Article::count();
$limit = 100;
if ($count >= $limit) {
$this->warn('Articles limit reached! Current count: ' . $count);
return;
}
if ($count > $limit * 0.8) {
$this->warn('Warning: You are close to articles limit.');
$this->info('Current articles: ' . $count . ' of ' . $limit);
} else {
$this->info('Articles count is normal: ' . $count);
}
}
}
?>
Результат выполнения команды php artisan app:check-limit:
"Warning: You are close to articles limit."
"Current articles: 85 of 100"
Если количество статей превышает 80% лимита, выводится предупреждение.