master

laravel/framework

Last updated at: 29/12/2023 09:21

ConfirmableTrait.php

TLDR

This file is a trait named ConfirmableTrait, located at Illuminate\Console\ConfirmableTrait.php. It provides methods for confirming an action before proceeding.

Methods

confirmToProceed

This method asks for confirmation before proceeding with an action. It takes two optional parameters:

  • $warning: A warning message displayed before asking for confirmation. The default value is "Application In Production".
  • $callback: A closure or boolean value to determine whether confirmation is required. If not provided, a default callback is used to check if the Laravel environment is set to "production". Returns a boolean value indicating whether the action should proceed.

getDefaultConfirmCallback

This method returns the default confirmation callback. The callback is a closure that checks if the Laravel environment is set to "production".

<?php

namespace Illuminate\Console;

use function Laravel\Prompts\confirm;

trait ConfirmableTrait
{
    /**
     * Confirm before proceeding with the action.
     *
     * This method only asks for confirmation in production.
     *
     * @param  string  $warning
     * @param  \Closure|bool|null  $callback
     * @return bool
     */
    public function confirmToProceed($warning = 'Application In Production', $callback = null)
    {
        $callback = is_null($callback) ? $this->getDefaultConfirmCallback() : $callback;

        $shouldConfirm = value($callback);

        if ($shouldConfirm) {
            if ($this->hasOption('force') && $this->option('force')) {
                return true;
            }

            $this->components->alert($warning);

            $confirmed = confirm('Are you sure you want to run this command?', default: false);

            if (! $confirmed) {
                $this->components->warn('Command cancelled.');

                return false;
            }
        }

        return true;
    }

    /**
     * Get the default confirmation callback.
     *
     * @return \Closure
     */
    protected function getDefaultConfirmCallback()
    {
        return function () {
            return $this->getLaravel()->environment() === 'production';
        };
    }
}