<?php

namespace PeskyCMF\Scaffold\Form;

use PeskyCMF\Scaffold\AbstractValueViewer;
use PeskyCMF\Scaffold\RenderableValueViewer;
use PeskyCMF\Scaffold\ScaffoldSectionConfig;
use PeskyCMF\Scaffold\ScaffoldSectionConfigException;
use PeskyCMF\Scaffold\ValueRenderer;
use PeskyORM\ORM\Column;
use PeskyORM\ORM\Relation;
use Swayok\Utils\Set;
use Swayok\Utils\StringUtils;

class FormConfig extends ScaffoldSectionConfig {

    protected $template = 'cmf::scaffold.form';
    protected $bulkEditingTemplate = 'cmf::scaffold.bulk_edit_form';

    protected $allowRelationsInValueViewers = true;
    protected $allowComplexValueViewerNames = true;

    /**
     * Fields list that can be edited in bulk (for many records at once)
     * @var FormInput[]
     */
    protected $bulkEditableColumns = [];
    /**
     * @var null|mixed
     */
    protected $itemId = null;
    /**
     * @var bool
     */
    protected $hasFiles = false;

    /** @var bool */
    protected $hasOptionsLoader = null;
    /** @var \Closure */
    protected $validators;
    /** @var \Closure */
    protected $validatorsForCreate;
    /** @var \Closure */
    protected $validatorsForEdit;
    /** @var array|\Closure|null */
    protected $defaultValuesModifier = [];

    /** @var string|\Closure */
    protected $additionalHtmlForForm = '';

    const VALIDATOR_FOR_ID = 'required|integer|min:1';
    /** @var \Closure|null */
    protected $incomingDataModifier;
    /** @var \Closure|null */
    protected $incomingDataModifierForBulkEdit;
    /** @var \Closure|null */
    protected $beforeSaveCallback;
     /** @var \Closure|null */
    protected $afterSaveCallback;
    /** @var bool */
    protected $revalidateDataAfterBeforeSaveCallbackForCreation = false;
    /** @var bool */
    protected $revalidateDataAfterBeforeSaveCallbackForUpdate = false;
    /** @var \Closure|null */
    protected $beforeValidateCallback;
    /** @var \Closure|null */
    protected $validationSuccessCallback;
    /** @var \Closure|null */
    protected $beforeBulkEditDataSaveCallback;
    /** @var \Closure|null */
    protected $afterBulkEditDataSaveCallback;

    /** @var array */
    protected $tabs = [];
    /** @var null|int */
    protected $currentTab;
    /** @var array */
    protected $inputGroups = [];
    /** @var null|int */
    protected $currentInputsGroup;

    /** @var array|null */
    protected $tooltips;
    /** @var bool */
    protected $showInDialog = true;

    /**
     * @param string $laravelViewPath
     * @return $this
     */
    public function setBulkEditingTemplate($laravelViewPath) {
        $this->bulkEditingTemplate = $laravelViewPath;
        return $this;
    }

    /**
     * @return string
     * @throws ScaffoldSectionConfigException
     */
    public function getBulkEditingTemplate() {
        if (empty($this->bulkEditingTemplate)) {
            throw new ScaffoldSectionConfigException($this, 'The view file for bulk editing is not set');
        }
        return $this->bulkEditingTemplate;
    }

    /**
     * @return InputRenderer
     */
    protected function createValueRenderer() {
        return InputRenderer::create();
    }

    /**
     * @param array $formInputs
     * @return $this
     * @throws \UnexpectedValueException
     * @throws \InvalidArgumentException
     * @throws \BadMethodCallException
     */
    public function setValueViewers(array $formInputs) {
        /** @var AbstractValueViewer|null $config */
        foreach ($formInputs as $name => $config) {
            if (is_array($config)) {
                /** @var array $config */
                $this->newInputsGroup(is_int($name) ? '' : $name);
                foreach ((array)$config as $groupInputName => $groupInputConfig) {
                    if (is_int($groupInputName)) {
                        $groupInputName = $groupInputConfig;
                        $groupInputConfig = null;
                    }
                    $this->addValueViewer($groupInputName, $groupInputConfig);
                }
                $this->currentInputsGroup = null;
            } else {
                if (is_int($name)) {
                    $name = $config;
                    $config = null;
                }
                $this->addValueViewer($name, $config);
            }
        }
        return $this;
    }

    /**
     * Alias for setValueViewers
     * @param array $formInputs - formats:
     * - ['name1', 'name2' => FormInput::create(), ...]
     * - ['group lablel' => ['name1', 'name2' => FormInput::create(), ...]
     * Also you may use '/' as value to separate inputs with <hr>
     * @return $this
     * @throws \UnexpectedValueException
     * @throws \InvalidArgumentException
     * @throws \BadMethodCallException
     */
    public function setFormInputs(array $formInputs) {
        return $this->setValueViewers($formInputs);
    }

    /**
     * @param string $tabLabel
     * @param array $formInputs
     * @return $this
     * @throws \UnexpectedValueException
     * @throws \BadMethodCallException
     * @throws \PeskyCMF\Scaffold\ScaffoldSectionConfigException
     * @throws \InvalidArgumentException
     * @throws \PeskyCMF\Scaffold\ScaffoldException
     */
    public function addTab($tabLabel, array $formInputs) {
        $this->newTab($tabLabel);
        $this->setFormInputs($formInputs);
        $this->currentTab = null;
        return $this;
    }

    /**
     * Add inputs to existing tab. If tab not exists - new one will be created
     * @param $tabLabel
     * @param array $formInputs
     * @return $this
     * @throws \UnexpectedValueException
     * @throws \InvalidArgumentException
     * @throws \BadMethodCallException
     */
    public function updateTab($tabLabel, array $formInputs) {
        $tabExists = false;
        foreach ($this->getTabs() as $tabIndex => $tabInfo) {
            if (array_get($tabInfo, 'label') === $tabLabel) {
                $this->currentTab = $tabIndex;
                $this->currentInputsGroup = null;
                if (count((array)array_get($tabInfo, 'groups', [])) === 1 && is_int(array_keys($tabInfo['groups'])[0])) {
                    $this->currentInputsGroup = array_keys($tabInfo['groups'])[0];
                }
                $tabExists = true;
                break;
            }
        }
        if (!$tabExists) {
            $this->newTab($tabLabel);
        }
        $this->setFormInputs($formInputs);
        $this->currentTab = null;
        $this->currentInputsGroup = null;
        return $this;
    }

    /**
     * @param $label
     */
    protected function newInputsGroup($label) {
        if ($this->currentTab === null) {
            $this->newTab('');
        }
        $this->currentInputsGroup = count($this->inputGroups);
        $this->tabs[$this->currentTab]['groups'][] = $this->currentInputsGroup;
        $this->inputGroups[] = [
            'label' => $label,
            'inputs_names' => []
        ];
    }

    /**
     * @param $label
     */
    protected function newTab($label) {
        $this->currentTab = count($this->tabs);
        $this->tabs[] = [
            'label' => $label,
            'groups' => []
        ];
        $this->currentInputsGroup = null;
    }

    /**
     * @return FormInput[]|AbstractValueViewer[]
     */
    public function getFormInputs() {
        return $this->getValueViewers();
    }

    /**
     * @param string $name
     * @return bool
     */
    public function hasFormInput($name) {
        return $this->hasValueViewer($name);
    }

    /**
     * @param string $name
     * @return FormInput|AbstractValueViewer
     * @throws \InvalidArgumentException
     * @throws \PeskyCMF\Scaffold\ScaffoldSectionConfigException
     */
    public function getFormInput($name) {
        return $this->getValueViewer($name);
    }

    /**
     * @return array
     */
    public function getTabs() {
        return $this->tabs;
    }

    /**
     * @return array
     */
    public function getInputsGroups() {
        return $this->inputGroups;
    }

    /**
     * @param string $name
     * @param AbstractValueViewer|null $viewer
     * @return $this
     * @throws \UnexpectedValueException
     * @throws \BadMethodCallException
     * @throws \InvalidArgumentException
     */
    public function addValueViewer($name, AbstractValueViewer $viewer = null) {
        parent::addValueViewer($name, $viewer);
        if (!$viewer) {
            // make sure viewer exists
            $this->getValueViewer($name);
        }
        if ($this->currentInputsGroup === null) {
            $this->newInputsGroup('');
        }
        $this->inputGroups[$this->currentInputsGroup]['inputs_names'][] = $name;
        return $this;
    }

    /**
     * @param bool $isCreation
     * @return array
     */
    protected function collectPresetValidators($isCreation) {
        $validators = [];
        foreach ($this->getFormInputs() as $formInput) {
            /** @noinspection SlowArrayOperationsInLoopInspection */
            if (($isCreation && !$formInput->isShownOnCreate()) || (!$isCreation && !$formInput->isShownOnEdit())) {
                continue; //< input not shown
            }
            $validators = array_merge($validators, $formInput->getValidators($isCreation));
        }
        return $validators;
    }

    /**
     * @param array $tooltips - anything except array will be ignored so it won't crash when there is no
     *      translations for tooltips in dictionaries (ex: trans('cmf.admins.form.tooltip') may be array or string)
     * @return $this
     */
    public function setTooltipsForInputs($tooltips) {
        if (is_array($tooltips)) {
            $this->tooltips = $tooltips;
        }
        return $this;
    }

    /**
     * @return array
     * @throws \UnexpectedValueException
     */
    public function getTooltipsForInputs() {
        if ($this->tooltips === null) {
            $resourceName = $this->getScaffoldConfig()->getResourceName();
            if (!empty($resourceName)) {
                /** @noinspection PhpParamsInspection */
                $this->setTooltipsForInputs($this->translate(null, 'tooltip'));
            }
            // make sure tooltips is always an array
            if (!is_array($this->tooltips)) {
                $this->tooltips = [];
            }
        }
        return $this->tooltips;
    }

    /**
     * @param string $inputName
     * @return bool
     * @throws \PeskyCMF\Scaffold\ScaffoldSectionConfigException
     * @throws \InvalidArgumentException
     * @throws \UnexpectedValueException
     */
    public function hasTooltipForInput($inputName) {
        return (
            ($this->hasFormInput($inputName) && $this->getFormInput($inputName)->hasTooltip())
            || !empty($this->getTooltipsForInputs()[$inputName])
        );
    }

    /**
     * @param string $inputName
     * @return mixed
     * @throws \InvalidArgumentException
     * @throws \UnexpectedValueException
     * @throws \PeskyCMF\Scaffold\ScaffoldSectionConfigException
     */
    public function getTooltipForInput($inputName) {
        if ($this->hasFormInput($inputName) && $this->getFormInput($inputName)->hasTooltip()) {
            return $this->getFormInput($inputName)->hasTooltip();
        } else {
            return array_get($this->getTooltipsForInputs(), $inputName, '');
        }
    }

    protected function configureDefaultValueRenderer(ValueRenderer $renderer, RenderableValueViewer $formInput) {
        parent::configureDefaultValueRenderer($renderer, $formInput);
        if (
            $formInput->isLinkedToDbColumn()
            && (
                !$formInput->hasRelation()
                || $formInput->getRelation()->getType() !== Relation::HAS_MANY
            )
        ) {
            $this->configureRendererByColumnConfig($renderer, $formInput);
        }
        if ($formInput->hasDefaultRendererConfigurator()) {
            call_user_func($formInput->getDefaultRendererConfigurator(), $renderer, $formInput);
        }
    }

    /**
     * @param InputRenderer|ValueRenderer $renderer
     * @param Column $columnConfig
     * @throws \BadMethodCallException
     * @throws \UnexpectedValueException
     */
    protected function configureRendererByColumnConfig(ValueRenderer $renderer, FormInput $formInput) {
        if ($formInput::isComplexViewerName($formInput->getName())) {
            $renderer->setIsRequired(false);
        } else {
            $renderer->setIsRequired($formInput->getTableColumn()->isValueRequiredToBeNotEmpty());
        }
    }

    /**
     * @param array $columns
     * @return $this
     * @throws \UnexpectedValueException
     * @throws \PeskyCMF\Scaffold\ScaffoldSectionConfigException
     * @throws \PeskyCMF\Scaffold\ScaffoldException
     * @throws \InvalidArgumentException
     * @throws \BadMethodCallException
     */
    public function setBulkEditableColumns(array $columns) {
        if (empty($this->valueViewers)) {
            throw new \BadMethodCallException('setValueViewers() method must be called before');
        }
        foreach ($columns as $name => $config) {
            if (is_int($name)) {
                $name = $config;
                $config = null;
            }
            $this->addBulkEditableColumn($name, $config);
        }
        return $this;
    }

    /**
     * @param string $name
     * @param null|FormInput $formInput - null: FormInput will be imported from $this->fields or created default one
     * @return $this
     * @throws \UnexpectedValueException
     * @throws \BadMethodCallException
     * @throws \PeskyCMF\Scaffold\ScaffoldSectionConfigException
     * @throws \InvalidArgumentException
     * @throws \PeskyCMF\Scaffold\ScaffoldException
     */
    public function addBulkEditableColumn($name, FormInput $formInput = null) {
        if ((!$formInput || $formInput->isLinkedToDbColumn()) && !$this->getTable()->getTableStructure()->hasColumn($name)) {
            throw new \InvalidArgumentException("Table {$this->getTable()->getName()} has no column [$name]");
        } else if ($this->getTable()->getTableStructure()->getColumn($name)->isItAFile()) {
            throw new ScaffoldSectionConfigException(
                $this,
                "Attaching files in bulk editing form is not suppoted. Table column: [$name]"
            );
        }
        if (empty($formInput)) {
            /** @noinspection CallableParameterUseCaseInTypeContextInspection */
            $formInput = $this->hasValueViewer($name) ? $this->getValueViewer($name) : $this->createValueViewer();
        }
        /** @var FormInput $formInput */
        $formInput->setName($name);
        $formInput->setPosition($this->getNextBulkEditableColumnPosition($formInput));
        $formInput->setScaffoldSectionConfig($this);
        $this->bulkEditableColumns[$name] = $formInput;
        return $this;
    }

    /**
     * @return FormInput[]
     */
    public function getBulkEditableColumns() {
        return $this->bulkEditableColumns;
    }

    /**
     * @param FormInput $formInput
     * @return int
     */
    protected function getNextBulkEditableColumnPosition(FormInput $formInput) {
        return count($this->bulkEditableColumns);
    }

    /**
     * @return mixed|null
     */
    public function getItemId() {
        return $this->itemId;
    }

    /**
     * @param mixed $itemId
     * @return $this
     */
    public function setItemId($itemId) {
        $this->itemId = $itemId;
        return $this;
    }

    /**
     * @return bool
     * @throws \UnexpectedValueException
     * @throws \InvalidArgumentException
     * @throws \BadMethodCallException
     */
    public function hasFiles() {
        if ($this->hasFiles === null) {
            $this->hasFiles = !empty(
                array_intersect($this->getValueViewers(), $this->getTable()->getTableStructure()->getFileColumns())
            );
        }
        return $this->hasFiles;
    }

    /**
     * @return bool
     */
    public function hasOptionsLoader() {
        if ($this->hasOptionsLoader === null) {
            $this->hasOptionsLoader = false;
            /** @var FormInput $viewer */
            foreach ($this->getValueViewers() as $viewer) {
                if ($viewer->hasOptionsLoader()) {
                    $this->hasOptionsLoader = true;
                    break;
                }
            }
        }
        return $this->hasOptionsLoader;
    }

    /**
     * @param int|string|null $pkValue - primary key value
     * @return array[]
     * @throws \PeskyCMF\Scaffold\ValueViewerConfigException
     */
    public function loadOptions($pkValue) {
        $options = array();
        /** @var FormInput $viewer */
        foreach ($this->getValueViewers() as $viewer) {
            if ($viewer->hasOptionsLoader()) {
                $options[$viewer->getName()] = call_user_func(
                    $viewer->getOptionsLoader(),
                    $pkValue,
                    '',
                    $viewer,
                    $this
                );
            }
        }
        return $options;
    }

    /**
     * @param string $inputName
     * @param int|string|null $pkValue - primary key value
     * @param string|null $keywords - keywords for filtering
     * @return array
     * @throws \InvalidArgumentException
     */
    public function loadOptionsForInput($inputName, $pkValue, $keywords) {
        $viewer = $this->getValueViewer($inputName);
        if ($viewer->hasOptionsLoader()) {
            $optionsMap = call_user_func(
                $viewer->getOptionsLoader(),
                $pkValue,
                $keywords,
                $viewer,
                $this
            );
        }
        $options = [];
        foreach ($optionsMap as $value => $label) {
            if (is_array($label)) {
                $options[] = $label;
            } else {
                $options[] = [
                    'value' => $value,
                    'text' => $label,
                ];
            }
        }
        return $options;
    }

    /**
     * @inheritdoc
     */
    public function createValueViewer() {
        return FormInput::create();
    }

    /**
     * @return FormInput[]
     */
    public function getInputsWithOwnValueSavingMethods() {
        $ret = [];
        foreach ($this->getFormInputs() as $key => $viewer) {
            if ($viewer->hasOwnValueSavingMethod()) {
                $ret[$key] = $viewer;
            }
        }
        return $ret;
    }

    /**
     * @param array $data
     * @param mixed $itemId - primary key value for current item
     * @return array
     */
    public function getValidatorsForEdit(array $data, $itemId) {
        return array_merge(
            $this->collectPresetValidators(false),
            $this->validators ? call_user_func($this->validators, $data) : [],
            $this->validatorsForCreate ? call_user_func($this->validatorsForEdit, $data, $itemId) : []
        );
    }

    /**
     * @param \Closure $validatorsForEdit - function (array $data, $itemId) { return []; }
     * Note: You can insert fields from received data via '{{field_name}}'
     * @return $this
     */
    public function addValidatorsForEdit(\Closure $validatorsForEdit) {
        $this->validatorsForEdit = $validatorsForEdit;
        return $this;
    }

    /**
     * @param array $data
     * @return array
     */
    public function getValidatorsForCreate(array $data) {
        return array_merge(
            $this->collectPresetValidators(true),
            $this->validators ? call_user_func($this->validators, $data) : [],
            $this->validatorsForCreate ? call_user_func($this->validatorsForCreate, $data) : []
        );
    }

    /**
     * @param \Closure $validatorsForCreate = function (array $data) { return []; }
     * Note: You can insert fields from received data via '{{field_name}}'
     * @return $this
     */
    public function addValidatorsForCreate(\Closure $validatorsForCreate) {
        $this->validatorsForCreate = $validatorsForCreate;
        return $this;
    }

    /**
     * @param \Closure $validators = function (array $data) { return []; }
     * Note: You can insert fields from received data via '{{field_name}}'
     * @return $this
     */
    public function setValidators(\Closure $validators) {
        $this->validators = $validators;
        return $this;
    }

    /**
     * @param array $data
     * @param array $messages
     * @param bool $isRevalidation
     * @return array
     * @throws \UnexpectedValueException
     * @throws \PeskyORM\Exception\OrmException
     * @throws \PeskyCMF\Scaffold\ScaffoldSectionConfigException
     * @throws \LogicException
     * @throws \InvalidArgumentException
     * @throws \BadMethodCallException
     */
    public function validateDataForCreate(array $data, array $messages = [], $isRevalidation = false) {
        return $this->validateData(
            $data,
            $this->getValidatorsForCreate($data),
            $messages,
            $isRevalidation
        );
    }

    /**
     * @param array $data
     * @param array $messages
     * @param bool $isRevalidation
     * @return array
     * @throws \UnexpectedValueException
     * @throws \PeskyORM\Exception\OrmException
     * @throws \PeskyCMF\Scaffold\ScaffoldSectionConfigException
     * @throws \LogicException
     * @throws \InvalidArgumentException
     * @throws \BadMethodCallException
     */
    public function validateDataForEdit(array $data, array $messages = [], $isRevalidation = false) {
        return $this->validateData(
            $data,
            $this->getValidatorsForEdit(
                $data,
                array_get($data, $this->getTable()->getPkColumnName(), null)
            ),
            $messages,
            $isRevalidation
        );
    }

    /**
     * @param array $data
     * @param array $messages
     * @param bool $isRevalidation
     * @return array
     * @throws \UnexpectedValueException
     * @throws \PeskyORM\Exception\OrmException
     * @throws \PeskyCMF\Scaffold\ScaffoldSectionConfigException
     * @throws \LogicException
     * @throws \InvalidArgumentException
     * @throws \BadMethodCallException
     */
    public function validateDataForBulkEdit(array $data, array $messages = [], $isRevalidation = false) {
        $rules = array_intersect_key($this->getValidatorsForEdit($data, null), $data);
        if (empty($rules)) {
            return [];
        }
        return $this->validateData($data, $rules, $messages, $isRevalidation, true);
    }

    /**
     * @param \Closure $callback - function (array $data, $isRevalidation) { return true; }
     * Note: callback MUST return true if everything is ok, otherwise - returned values treated as error
     * @return $this
     */
    public function setBeforeValidateCallback(\Closure $callback) {
        $this->beforeValidateCallback = $callback;
        return $this;
    }

    /**
     * @param array $data
     * @param $isRevalidation
     * @return array|bool|string - true: no errors | other: errors detected
     * @throws \InvalidArgumentException
     * @throws \PeskyCMF\Scaffold\ScaffoldSectionConfigException
     */
    public function beforeValidate(array $data, $isRevalidation) {
        if (!empty($this->beforeValidateCallback)) {
            $success = call_user_func($this->beforeValidateCallback, $data, $isRevalidation);
            if ($success !== true) {
                return (array)$success;
            }
        }
        return true;
    }

    /**
     * @param array $data
     * @param bool $isCreation
     * @param bool $isBulkEdit
     * @return array
     * @throws \PeskyCMF\Scaffold\ScaffoldSectionConfigException
     * @throws \InvalidArgumentException
     * @throws \UnexpectedValueException
     */
    public function modifyIncomingDataBeforeValidation(array $data, $isCreation, $isBulkEdit = false) {
        /** @var FormInput[] $inputs */
        $inputs = $isBulkEdit ? $this->getBulkEditableColumns() : $this->getFormInputs();
        foreach ($inputs as $inputName => $formInput) {
            if (($isCreation && !$formInput->isShownOnCreate()) || (!$isCreation && !$formInput->isShownOnEdit())) {
                continue;
            }
            if ($formInput::isComplexViewerName($inputName)) {
                $inputName = implode('.', $formInput::splitComplexViewerName($inputName));
            }
            if (!$isBulkEdit || array_has($data, $inputName)) {
                array_set($data, $inputName, $formInput->modifySubmitedValueBeforeValidation(array_get($data, $inputName, ''), $data));
            }
        }
        if ($isBulkEdit) {
            if ($this->incomingDataModifierForBulkEdit) {
                $data = call_user_func($this->incomingDataModifierForBulkEdit, $data, $isCreation, $this);
                if (!is_array($data)) {
                    throw new \UnexpectedValueException('incomingDataModifierForBulkEdit closure must return an array');
                }
            }
        } else {
            if ($this->incomingDataModifier) {
                $data = call_user_func($this->incomingDataModifier, $data, $isCreation, $this);
                if (!is_array($data)) {
                    throw new \UnexpectedValueException('incomingDataModifier closure must return an array');
                }
            }
        }
        return $data;
    }

    /**
     * @param \Closure $modifier - function (array $data, $isCreation, FormConfig $formConfig) { return $data; }
     * @return $this
     */
    public function setIncomingDataModifier(\Closure $modifier) {
        $this->incomingDataModifier = $modifier;
        return $this;
    }

    /**
     * @param \Closure $modifier - function (array $data, FormConfig $formConfig) { return $data; }
     * @return $this
     */
    public function setIncomingDataModifierForBulkEdit(\Closure $modifier) {
        $this->incomingDataModifierForBulkEdit = $modifier;
        return $this;
    }

    /**
     * @param array $data
     * @param array $validators - supports inserts in format "{{id}}" where "id" can be any key from $data
     * @param array $messages
     * @param bool $isRevalidation
     * @param bool $isBulkEdit
     * @return array|string|bool
     * @throws \PeskyCMF\Scaffold\ScaffoldSectionConfigException
     * @throws \InvalidArgumentException
     * @throws \LogicException
     */
    public function validateData(
        array $data,
        array $validators,
        array $messages = [],
        $isRevalidation = false,
        $isBulkEdit = false
    ) {
        $success = $this->beforeValidate($data, $isRevalidation);
        if ($success !== true) {
            return $success;
        }

        if (empty($validators)) {
            return [];
        }
        if (empty($messages)) {
            /** @noinspection CallableParameterUseCaseInTypeContextInspection */
            $messages = cmfTransCustom('.' . $this->getTable()->getName() . '.form.validation');
        }
        if (!is_array($messages)) {
            $messages = [];
        } else {
            $messages = Set::flatten($messages);
        }
        $columnsWithArrayType = [];
        $dataForInserts = $data;
        array_walk_recursive($dataForInserts, function (&$value) {
            if ($value === null) {
                $value = 'NULL';
            }
        });
        // add 'NULL' inserts for all columns registered in table structure to prevent '{{colname}}' parts in validators
        foreach ($this->getTable()->getTableStructure()->getColumns() as $column) {
            if (!array_key_exists($column->getName(), $dataForInserts)) {
                $dataForInserts[$column->getName()] = 'NULL';
            }
        }
        foreach ($validators as $key => &$value) {
            if (is_string($value)) {
                $value = StringUtils::insert($value, $dataForInserts, ['before' => '{{', 'after' => '}}']);
                if (preg_match('%(^|\|)array%i', $value)) {
                    $columnsWithArrayType[] = $key;
                }
            } else if (is_array($value)) {
                /** @var array $value */
                foreach ($value as &$validator) {
                    if (is_string($validator)) {
                        $validator = StringUtils::insert($validator, $dataForInserts, ['before' => '{{', 'after' => '}}']);
                    }
                    if ($validator === 'array') {
                        $columnsWithArrayType[] = $key;
                    }
                }
                unset($validator);
            }
        }
        unset($value);
        $validator = \Validator::make($data, $validators, $messages);
        if ($validator->fails()) {
            $errors = $validator->getMessageBag()->toArray();
            foreach ($errors as $viewerName => $error) {
                if (in_array($viewerName, $columnsWithArrayType, true)) {
                    $errors[$viewerName . '[]'] = $error;
                    unset($errors[$viewerName]);
                }
            }
            return $errors;
        }

        $success = $this->onValidationSuccess($data, $isRevalidation, $isBulkEdit);
        if ($success !== true) {
            return $success;
        }

        return [];
    }

    /**
     * Called after request data validation and before specific callbacks and data saving.
     * Note: if you need to revalidate data after callback - use setRevalidateDataAfterBeforeSaveCallback() method
     * Note: is not applied to bulk edit!
     * @param \Closure $callback = function ($isCreation, array $validatedData, FormConfig $formConfig) { return $validatedData; }
     * @return $this
     */
    public function setBeforeSaveCallback(\Closure $callback) {
        $this->beforeSaveCallback = $callback;
        return $this;
    }

    /**
     * @return bool
     */
    public function hasBeforeSaveCallback() {
        return !empty($this->beforeSaveCallback);
    }

    /**
     * @return \Closure
     */
    public function getBeforeSaveCallback() {
        return $this->beforeSaveCallback;
    }

    /**
     * Called after request data validation and before specific callbacks and data saving.
     * Note: if you need to revalidate data after callback - use setRevalidateDataAfterBeforeSaveCallback() method
     * Note: is not applied to bulk edit!
     * @param \Closure $callback = function (array $validatedData, FormConfig $formConfig) { return $validatedData; }
     * @return $this
     */
    public function setBeforeBulkEditDataSaveCallback(\Closure $callback) {
        $this->beforeBulkEditDataSaveCallback = $callback;
        return $this;
    }

    /**
     * @return bool
     */
    public function hasBeforeBulkEditDataSaveCallback() {
        return !empty($this->beforeBulkEditDataSaveCallback);
    }

    /**
     * @return \Closure
     */
    public function getBeforeBulkEditDataSaveCallback() {
        return $this->beforeBulkEditDataSaveCallback;
    }

    /**
     * @param bool $forCreation
     * @param bool $forUpdate
     * @return $this
     */
    public function setRevalidateDataAfterBeforeSaveCallback($forCreation, $forUpdate) {
        $this->revalidateDataAfterBeforeSaveCallbackForCreation = (bool)$forCreation;
        $this->revalidateDataAfterBeforeSaveCallbackForUpdate = (bool)$forUpdate;
        return $this;
    }

    /**
     * @param bool $isCreation
     * @return bool
     */
    public function shouldRevalidateDataAfterBeforeSaveCallback($isCreation) {
        return $isCreation
            ? $this->revalidateDataAfterBeforeSaveCallbackForCreation
            : $this->revalidateDataAfterBeforeSaveCallbackForUpdate;
    }

    /**
     * @param \Closure $calback = function (array $data, $isRevalidation, $isBulkEdit) { return true }
     * Note: callback MUST return true if everything is ok, otherwise - returned values treated as error
     * Values allowed to be returned:
     *      - true: no errors
     *      - string: custom "validation failed" message (without errors for certain fields)
     *      - array: validation errors for certain fields, may contain "_mesasge" key to be displayed instead of
     *               default "validation failed" message
     * @return $this
     */
    public function setValidationSuccessCallback(\Closure $calback) {
        $this->validationSuccessCallback = $calback;
        return $this;
    }

    /**
     * @param array $data
     * @param bool $isRevalidation
     * @param bool $isBulkEdit
     * @return array|bool - true: no errors | other - validation errors
     * @throws \LogicException
     */
    protected function onValidationSuccess(array $data, $isRevalidation, $isBulkEdit) {
        if (!empty($this->validationSuccessCallback)) {
            $success = call_user_func($this->validationSuccessCallback, $data, $isRevalidation, $isBulkEdit);
            if ($success !== true) {
                if (is_string($success)) {
                    return ['_message' => $success];
                } else if (is_array($success)) {
                    return $success;
                } else {
                    throw new \LogicException(
                        'validationSuccessCallback must return true, string or array with key-value pairs'
                    );
                }
            }
        }
        return true;
    }

    /**
     * Callback is called after successfully saving data but before model's commit()
     * It must return true if everything is ok or instance of \Symfony\Component\HttpFoundation\JsonResponse
     * Response success detected by HTTP code of \Illuminate\Http\JsonResponse: code < 400 - success; code >= 400 - error
     * @param \Closure $callback - function ($isCreation, array $validatedData, CmfDbRecord $object, FormConfig $formConfig) { return true; }
     * @return $this
     */
    public function setAfterSaveCallback(\Closure $callback) {
        $this->afterSaveCallback = $callback;
        return $this;
    }

    /**
     * @return bool
     */
    public function hasAfterSaveCallback() {
        return !empty($this->afterSaveCallback);
    }

    /**
     * @return \Closure
     */
    public function getAfterSaveCallback() {
        return $this->afterSaveCallback;
    }

    /**
     * Callback is called after successfully saving data but before model's commit()
     * It must return true if everything is ok or instance of \Symfony\Component\HttpFoundation\JsonResponse
     * Response success detected by HTTP code of \Illuminate\Http\JsonResponse: code < 400 - success; code >= 400 - error
     * @param \Closure $callback - function (array $validatedData, FormConfig $formConfig) { return []; }
     * @return $this
     */
    public function setAfterBulkEditDataSaveCallback(\Closure $callback) {
        $this->afterBulkEditDataSaveCallback = $callback;
        return $this;
    }

    /**
     * @return bool
     */
    public function hasAfterBulkEditDataAfterSaveCallback() {
        return !empty($this->afterBulkEditDataSaveCallback);
    }

    /**
     * @return \Closure
     */
    public function getAfterBulkEditDataAfterSaveCallback() {
        return $this->afterBulkEditDataSaveCallback;
    }

    /**
     * @param array|\Closure $arrayOrClosure
     *      - \Closure: funciton (array $defaults, FormConfig $formConfig) { return $defaults; }
     * @return $this
     * @throws \InvalidArgumentException
     */
    public function setDefaultValuesModifier($arrayOrClosure) {
        if (!is_array($arrayOrClosure) && !($arrayOrClosure instanceof \Closure)) {
            throw new \InvalidArgumentException('$stringOfFunction argument must be a string or \Closure');
        }
        $this->defaultValuesModifier = $arrayOrClosure;
        return $this;
    }

    /**
     * @param array $defaults
     * @return array
     * @throws \UnexpectedValueException
     */
    public function alterDefaultValues(array $defaults) {
        if (!empty($this->defaultValuesModifier)) {
            if ($this->defaultValuesModifier instanceof \Closure) {
                $defaults = call_user_func($this->defaultValuesModifier, $defaults, $this);
                if (!is_array($defaults)) {
                    throw new \UnexpectedValueException('Default values modifier must return array');
                }
            } else {
                return array_merge($defaults, $this->defaultValuesModifier);
            }
        }
        return $defaults;
    }

    /**
     * @param $stringOfClosure - function (FormConfig $formConfig) { return '<div>'; }
     * @return $this
     * @throws \InvalidArgumentException
     */
    public function setAdditionalHtmlForForm($stringOfClosure) {
        if (!is_string($stringOfClosure) && !($stringOfClosure instanceof \Closure)) {
            throw new \InvalidArgumentException('$stringOfFunction argument must be a string or \Closure');
        }
        $this->additionalHtmlForForm = $stringOfClosure;
        return $this;
    }

    /**
     * @return string
     */
    public function getAdditionalHtmlForForm() {
        if (empty($this->additionalHtmlForForm)) {
            return '';
        } else if (is_string($this->additionalHtmlForForm)) {
            return $this->additionalHtmlForForm;
        } else {
            return call_user_func($this->additionalHtmlForForm, $this);
        }
    }

    public function beforeRender() {
        foreach ($this->getTooltipsForInputs() as $inputName => $tooltip) {
            if ($this->hasFormInput($inputName)) {
                $input = $this->getFormInput($inputName);
                if (!$input->hasTooltip()) {
                    $input->setTooltip($tooltip);
                }
            }
        }
    }

    protected function getSectionTranslationsPrefix($subtype = null) {
        return $subtype === 'value_viewer' ? 'form.input' : 'form';
    }

    /**
     * @param bool $useDialog
     * @return $this
     */
    public function setShowAsDialog($useDialog) {
        $this->showInDialog = (bool)$useDialog;
        return $this;
    }

    /**
     * @return bool
     */
    public function isUsingDialog() {
        return $this->showInDialog;
    }

}


<?php

namespace Ekyna\Component\Commerce\Pricing\Resolver;

use Ekyna\Component\Commerce\Common\Country\CountryProviderInterface;
use Ekyna\Component\Commerce\Common\Model\CountryInterface;
use Ekyna\Component\Commerce\Common\Model\SaleInterface;
use Ekyna\Component\Commerce\Customer\Model\CustomerInterface;
use Ekyna\Component\Commerce\Exception\InvalidArgumentException;
use Ekyna\Component\Commerce\Pricing\Model\TaxableInterface;
use Ekyna\Component\Commerce\Pricing\Model\TaxRuleInterface;
use Ekyna\Component\Commerce\Pricing\Model\VatNumberSubjectInterface;
use Ekyna\Component\Commerce\Pricing\Repository\TaxRuleRepositoryInterface;

/**
 * Class TaxResolver
 * @package Ekyna\Component\Commerce\Pricing\Resolver
 * @author  Etienne Dauvergne <contact@ekyna.com>
 */
class TaxResolver implements TaxResolverInterface
{
    /**
     * @var CountryProviderInterface
     */
    protected $countryProvider;

    /**
     * @var TaxRuleRepositoryInterface
     */
    protected $taxRuleRepository;

    /**
     * @var array
     */
    protected $cache;

    /**
     * Constructor.
     *
     * @param CountryProviderInterface   $countryProvider
     * @param TaxRuleRepositoryInterface $taxRuleRepository
     */
    public function __construct(
        CountryProviderInterface $countryProvider,
        TaxRuleRepositoryInterface $taxRuleRepository
    ) {
        $this->countryProvider = $countryProvider;
        $this->taxRuleRepository = $taxRuleRepository;

        $this->cache = new ResolvedTaxesCache();
    }

    /**
     * @inheritdoc
     *
     * @see https://ec.europa.eu/taxation_customs/business/vat/eu-vat-rules-topic/where-tax_fr
     */
    public function resolveTaxes(TaxableInterface $taxable, $target = null): array
    {
        // TODO @param ContextInterface $context (instead of $target)

        // Abort if taxable does not have tax group
        if (null === $taxGroup = $taxable->getTaxGroup()) {
            return [];
        }

        // Abort if tax group does not have taxes
        if (!$taxGroup->hasTaxes()) {
            return [];
        }

        $country = $this->resolveTargetCountry($target);
        $business = $target instanceof VatNumberSubjectInterface
            ? $target->isBusiness()
            : false;

        // Use cached resolved taxes if any
        if (null !== $taxes = $this->cache->get($taxGroup, $country, $business)) {
            return $taxes;
        }

        // Abort if no matching tax rule
        if (null === $taxRule = $this->resolveTaxRule($country, $business)) {
            return [];
        }

        // Abort if tax rule does not have taxes
        if (!$taxRule->hasTaxes()) {
            return [];
        }

        // Resolves the taxes
        $applicableTaxes = $taxRule->getTaxes()->toArray();
        $resolvedTaxes = [];
        foreach ($taxGroup->getTaxes() as $tax) {
            if (in_array($tax, $applicableTaxes, true)) {
                $resolvedTaxes[] = $tax;
            }
        }

        // Caches the resolved taxes
        $this->cache->set($taxGroup, $country, $business, $resolvedTaxes);

        return $resolvedTaxes;
    }

    /**
     * Resolves the sale tax rule.
     *
     * @param SaleInterface $sale
     *
     * @return TaxRuleInterface|null
     */
    public function resolveSaleTaxRule(SaleInterface $sale): ?TaxRuleInterface
    {
        return $this->resolveTaxRule($this->resolveTargetCountry($sale), $sale->isBusiness());
    }

    /**
     * Resolves the target country.
     *
     * @param mixed $target
     *
     * @return CountryInterface
     */
    protected function resolveTargetCountry($target): CountryInterface
    {
        if (null === $target) {
            return $this->countryProvider->getCountry();
        }

        if ($target instanceof CountryInterface) {
            return $target;
        }

        if ($target instanceof SaleInterface) {
            $country = $this->resolveSaleTargetCountry($target);
        } elseif ($target instanceof CustomerInterface) {
            $country = $this->resolveCustomerTargetCountry($target);
        } elseif(is_string($target) && 2 == strlen($target)) {
            $country = $this->getCountryByCode($target);
        } else {
            throw new InvalidArgumentException("Unexpected taxation target.");
        }

        return $country ?: $this->countryProvider->getCountry();
    }

    /**
     * Resolves the tax rule for the given sale.
     *
     * @param CountryInterface $country
     * @param bool             $business
     *
     * @return TaxRuleInterface|null
     */
    protected function resolveTaxRule(CountryInterface $country, $business = false): ?TaxRuleInterface
    {
        if ($business) {
            return $this->taxRuleRepository->findOneByCountryForBusiness($country);
        }

        return $this->taxRuleRepository->findOneByCountryForCustomer($country);
    }

    /**
     * Resolves the sales's taxation target country.
     *
     * @param SaleInterface $sale
     *
     * @return CountryInterface|null
     */
    protected function resolveSaleTargetCountry(SaleInterface $sale): ?CountryInterface
    {
        // Get the country from the sale's delivery address
        if (null !== $country = $sale->getDeliveryCountry()) {
            return $country;
        }

        // If none, resolves the customer's taxation target address
        if (null !== $customer = $sale->getCustomer()) {
            return $this->resolveCustomerTargetCountry($customer);
        }

        return null;
    }

    /**
     * Resolves the customer's taxation target country.
     *
     * @param CustomerInterface $customer
     *
     * @return CountryInterface|null
     */
    protected function resolveCustomerTargetCountry(CustomerInterface $customer): ?CountryInterface
    {
        if (null !== $address = $customer->getDefaultDeliveryAddress()) {
            return $address->getCountry();
        }

        return null;
    }

    /**
     * Returns the country by its code.
     *
     * @param string $code
     *
     * @return CountryInterface|null
     */
    protected function getCountryByCode(string $code): ?CountryInterface
    {
        return $this->countryProvider->getCountry($code);
    }
}


<?php

namespace mii\util;

class Arr
{

    /**
     * @var  string  default delimiter for path()
     */
    public static $delimiter = '.';

    /**
     * Tests if an array is associative or not.
     *
     *     // Returns true
     *     Arr::isAssoc(array('username' => 'john.doe'));
     *
     *     // Returns false
     *     Arr::isAssoc('foo', 'bar');
     *
     * @param   array $array array to check
     * @return  boolean
     */
    public static function is_assoc(array $array) {
        // Keys of the array
        $keys = array_keys($array);

        // If the array keys of the keys match the keys, then the array must
        // not be associative (e.g. the keys array looked like {0:0, 1:1...}).
        return array_keys($keys) !== $keys;
    }

    /**
     * Test if a value is an array with an additional check for array-like objects.
     *
     *
     * @param   mixed $value value to check
     * @return  boolean
     */
    public static function is_array($value) {
        if (is_array($value)) {
            return true;
        }
        // Traversable is the interface that makes an object foreach'able,
        // it is implemented by the SPL Iterator and IteratorAggregate classes.
        return (is_object($value) && $value instanceof \Traversable);
    }

    /**
     * Gets a value from an array using a dot separated path.
     *
     *     // Get the value of $array['foo']['bar']
     *     $value = Arr::path($array, 'foo.bar');
     *
     * @param   array $array array to search
     * @param   mixed $path key path string (delimiter separated) or array of keys
     * @param   mixed $default default value if the path is not set
     * @param   string $delimiter key path delimiter
     * @return  mixed
     */
    public static function path($array, $path, $default = null, $delimiter = null) {
        if (!static::is_array($array)) {
            // This is not an array!
            return $default;
        }

        if (is_array($path)) {
            // The path has already been separated into keys
            $keys = $path;
        } else {
            if (array_key_exists($path, $array)) {
                // No need to do extra processing
                return $array[$path];
            }

            if (!$delimiter) {
                // Use the default delimiter
                $delimiter = static::$delimiter;
            }

            // Remove  delimiters and spaces
            $path = trim($path, "{$delimiter} ");

            // Split the keys by delimiter
            $keys = explode($delimiter, $path);
        }

        do {
            $key = array_shift($keys);

            if (ctype_digit($key)) {
                // Make the key an integer
                $key = (int)$key;
            }

            if (isset($array[$key])) {
                if (!$keys) {
                    // Found the path requested
                    return $array[$key];
                }
                if (!static::is_array($array[$key])) {
                    // Unable to dig deeper
                    break;
                }
                // Dig down into the next part of the path
                $array = $array[$key];
            } else {
                // Unable to dig deeper
                break;
            }
        } while ($keys);

        // Unable to find the value requested
        return $default;
    }

    /**
     * Set a value on an array by path.
     *
     * @see Arr::path()
     * @param array $array Array to update
     * @param string $path Path
     * @param mixed $value Value to set
     * @param string $delimiter Path delimiter
     */
    public static function set_path(&$array, $path, $value, $delimiter = null): void {
        if (!$delimiter) {
            // Use the default delimiter
            $delimiter = static::$delimiter;
        }

        // The path has already been separated into keys
        $keys = $path;
        if (!is_array($path)) {
            // Split the keys by delimiter
            $keys = explode($delimiter, $path);
        }

        // Set current $array to inner-most array path
        while (count($keys) > 1) {
            $key = array_shift($keys);

            if (is_string($key) && ctype_digit($key)) {
                // Make the key an integer
                $key = (int)$key;
            }

            if (!isset($array[$key])) {
                $array[$key] = array();
            }

            $array =& $array[$key];
        }

        // Set key on inner-most array
        $array[array_shift($keys)] = $value;
    }

    /**
     * Fill an array with a range of numbers.
     *
     *     // Fill an array with values 5, 10, 15, 20
     *     $values = Arr::range(5, 20);
     *
     * @param   integer $step stepping
     * @param   integer $max ending number
     * @return  array
     */
    public static function range($step = 10, $max = 100) {
        if ($step < 1) {
            return array();
        }

        $array = array();
        for ($i = $step; $i <= $max; $i += $step) {
            $array[$i] = $i;
        }

        return $array;
    }

    /**
     * Retrieve a single key from an array. If the key does not exist in the
     * array, the default value will be returned instead.
     *
     *     // Get the value "username" from $_POST, if it exists
     *     $username = Arr::get($_POST, 'username');
     *
     *     // Get the value "sorting" from $_GET, if it exists
     *     $sorting = Arr::get($_GET, 'sorting');
     *
     * @param   array $array array to extract from
     * @param   string $key key name
     * @param   mixed $default default value
     * @return  mixed
     */
    public static function get($array, $key, $default = null) {
        return isset($array[$key]) ? $array[$key] : $default;
    }

    /**
     * Retrieves multiple paths from an array. If the path does not exist in the
     * array, the default value will be added instead.
     *
     *     // Get the values "username", "password" from $_POST
     *     $auth = Arr::extract($_POST, array('username', 'password'));
     *
     *     // Get the value "level1.level2a" from $data
     *     $data = array('level1' => array('level2a' => 'value 1', 'level2b' => 'value 2'));
     *     Arr::extract($data, array('level1.level2a', 'password'));
     *
     * @param   array $array array to extract paths from
     * @param   array $paths list of path
     * @param   mixed $default default value
     * @return  array
     */
    public static function extract($array, array $paths, $default = null) {
        $found = array();
        foreach ($paths as $path) {
            static::set_path($found, $path, static::path($array, $path, $default));
        }

        return $found;
    }

    /**
     * Retrieves multiple single-key values from a list of arrays.
     *
     *     // Get all of the "id" values from a result
     *     $ids = Arr::pluck($result, 'id');
     *
     * [!!] A list of arrays is an array that contains arrays, eg: array(array $a, array $b, array $c, ...)
     *
     * @param   array $array list of arrays to check
     * @param   string $key key to pluck
     * @return  array
     */
    public static function pluck($array, $key) {
        $values = array();

        foreach ($array as $row) {
            if (isset($row[$key])) {
                // Found a value in this row
                $values[] = $row[$key];
            }
        }

        return $values;
    }

    /**
     * Adds a value to the beginning of an associative array.
     *
     *     // Add an empty value to the start of a select list
     *     Arr::unshift($array, 'none', 'Select a value');
     *
     * @param   array $array array to modify
     * @param   string $key array key name
     * @param   mixed $val array value
     * @return  array
     */
    public static function unshift(array &$array, $key, $val) {
        $array = array_reverse($array, true);
        $array[$key] = $val;
        $array = array_reverse($array, true);

        return $array;
    }

    /**
     * Recursive version of [array_map](http://php.net/array_map), applies one or more
     * callbacks to all elements in an array, including sub-arrays.
     *
     *     // Apply "strip_tags" to every element in the array
     *     $array = Arr::map('strip_tags', $array);
     *
     *     // Apply $this->filter to every element in the array
     *     $array = Arr::map(array(array($this,'filter')), $array);
     *
     *     // Apply strip_tags and $this->filter to every element
     *     $array = Arr::map(array('strip_tags',array($this,'filter')), $array);
     *
     * [!!] Because you can pass an array of callbacks, if you wish to use an array-form callback
     * you must nest it in an additional array as above. Calling Arr::map(array($this,'filter'), $array)
     * will cause an error.
     * [!!] Unlike `array_map`, this method requires a callback and will only map
     * a single array.
     *
     * @param   mixed $callbacks array of callbacks to apply to every element in the array
     * @param   array $array array to map
     * @param   array $keys array of keys to apply to
     * @return  array
     */
    public static function map($callbacks, $array, $keys = null) {
        foreach ($array as $key => $val) {
            if (is_array($val)) {
                $array[$key] = static::map($callbacks, $array[$key]);
            } elseif (!is_array($keys) || in_array($key, $keys)) {
                if (is_array($callbacks)) {
                    foreach ($callbacks as $cb) {
                        $array[$key] = call_user_func($cb, $array[$key]);
                    }
                } else {
                    $array[$key] = call_user_func($callbacks, $array[$key]);
                }
            }
        }

        return $array;
    }

    /**
     * Recursively merge two or more arrays. Values in an associative array
     * overwrite previous values with the same key. Values in an indexed array
     * are appended, but only when they do not already exist in the result.
     *
     * Note that this does not work the same as [array_merge_recursive](http://php.net/array_merge_recursive)!
     *
     *     $john = array('name' => 'john', 'children' => array('fred', 'paul', 'sally', 'jane'));
     *     $mary = array('name' => 'mary', 'children' => array('jane'));
     *
     *     // John and Mary are married, merge them together
     *     $john = Arr::merge($john, $mary);
     *
     *     // The output of $john will now be:
     *     array('name' => 'mary', 'children' => array('fred', 'paul', 'sally', 'jane'))
     *
     * @param   array $array1 initial array
     * @param   array $array2,... array to merge
     * @return  array
     */
    public static function merge($array1, $array2) {
        if (static::is_assoc($array2)) {
            foreach ($array2 as $key => $value) {
                if (is_array($value)
                    && isset($array1[$key])
                    && is_array($array1[$key])
                ) {
                    $array1[$key] = static::merge($array1[$key], $value);
                } else {
                    $array1[$key] = $value;
                }
            }
        } else {
            foreach ($array2 as $value) {
                if (!in_array($value, $array1, true)) {
                    $array1[] = $value;
                }
            }
        }

        if (func_num_args() > 2) {
            foreach (array_slice(func_get_args(), 2) as $array2) {
                if (static::is_assoc($array2)) {
                    foreach ($array2 as $key => $value) {
                        if (is_array($value)
                            && isset($array1[$key])
                            && is_array($array1[$key])
                        ) {
                            $array1[$key] = static::merge($array1[$key], $value);
                        } else {
                            $array1[$key] = $value;
                        }
                    }
                } else {
                    foreach ($array2 as $value) {
                        if (!in_array($value, $array1, true)) {
                            $array1[] = $value;
                        }
                    }
                }
            }
        }

        return $array1;
    }

    /**
     * Overwrites an array with values from input arrays.
     * Keys that do not exist in the first array will not be added!
     *
     *     $a1 = array('name' => 'john', 'mood' => 'happy', 'food' => 'bacon');
     *     $a2 = array('name' => 'jack', 'food' => 'tacos', 'drink' => 'beer');
     *
     *     // Overwrite the values of $a1 with $a2
     *     $array = Arr::overwrite($a1, $a2);
     *
     *     // The output of $array will now be:
     *     array('name' => 'jack', 'mood' => 'happy', 'food' => 'tacos')
     *
     * @param   array $array1 master array
     * @param   array $array2 input arrays that will overwrite existing values
     * @return  array
     */
    public static function overwrite($array1, $array2) {
        foreach (array_intersect_key($array2, $array1) as $key => $value) {
            $array1[$key] = $value;
        }

        if (func_num_args() > 2) {
            foreach (array_slice(func_get_args(), 2) as $array2) {
                foreach (array_intersect_key($array2, $array1) as $key => $value) {
                    $array1[$key] = $value;
                }
            }
        }

        return $array1;
    }

    /**
     * Creates a callable function and parameter list from a string representation.
     * Note that this function does not validate the callback string.
     *
     *     // Get the callback function and parameters
     *     list($func, $params) = Arr::callback('Foo::bar(apple,orange)');
     *
     *     // Get the result of the callback
     *     $result = call_user_func_array($func, $params);
     *
     * @param   string $str callback string
     * @return  array   function, params
     */
    public static function callback($str) {
        // Overloaded as parts are found
        $command = $params = null;

        // command[param,param]
        if (preg_match('/^([^\(]*+)\((.*)\)$/', $str, $match)) {
            // command
            $command = $match[1];

            if ($match[2] !== '') {
                // param,param
                $params = preg_split('/(?<!\\\\),/', $match[2]);
                $params = str_replace('\,', ',', $params);
            }
        } else {
            // command
            $command = $str;
        }

        if (strpos($command, '::') !== false) {
            // Create a static method callable command
            $command = explode('::', $command, 2);
        }

        return array($command, $params);
    }

    /**
     * Convert a multi-dimensional array into a single-dimensional array.
     *
     *     $array = array('set' => array('one' => 'something'), 'two' => 'other');
     *
     *     // Flatten the array
     *     $array = Arr::flatten($array);
     *
     *     // The array will now be
     *     array('one' => 'something', 'two' => 'other');
     *
     * [!!] The keys of array values will be discarded.
     *
     * @param   array $array array to flatten
     * @return  array
     * @since   3.0.6
     */
    public static function flatten($array) {
        $is_assoc = static::is_assoc($array);

        $flat = array();
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $flat = array_merge($flat, static::flatten($value));
            } else {
                if ($is_assoc) {
                    $flat[$key] = $value;
                } else {
                    $flat[] = $value;
                }
            }
        }
        return $flat;
    }

    public static function to_array($object, $properties = [], $recursive = true) {
        if (is_array($object)) {
            if ($recursive) {
                foreach ($object as $key => $value) {
                    if (is_array($value) || is_object($value)) {
                        $object[$key] = static::to_array($value, $properties, true);
                    }
                }
            }
            return $object;
        } elseif ($object instanceof \Traversable) {

            $result = [];
            foreach ($object as $obj) {
                $result[] = static::to_array($obj, $properties, $recursive);
            }
            return $result;

        } elseif (is_object($object)) {
            if (!empty($properties)) {
                $result = [];
                foreach ($properties as $key => $name) {
                    if (is_int($key)) {
                        $result[$name] = $object->$name;
                    } else {
                        if (is_string($name)) {
                            $result[$key] = $object->$name;
                        } elseif ($name instanceof \Closure) {
                            $result[$key] = $name($object);
                        }
                    }
                }

                return $recursive ? static::to_array($result, $properties) : $result;
            }

            $result = [];
            foreach ($object as $key => $value) {
                $result[$key] = $value;
            }

            return $recursive ? static::to_array($result) : $result;
        } else {
            return [$object];
        }
    }

}


<?php

/**
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @author Carsten Brandt <mail@cebe.cc>
 */

namespace mii\util;

class Console
{
    const FG_BLACK = 30;
    const FG_RED = 31;
    const FG_GREEN = 32;
    const FG_YELLOW = 33;
    const FG_BLUE = 34;
    const FG_PURPLE = 35;
    const FG_CYAN = 36;
    const FG_GREY = 37;

    const BG_BLACK = 40;
    const BG_RED = 41;
    const BG_GREEN = 42;
    const BG_YELLOW = 43;
    const BG_BLUE = 44;
    const BG_PURPLE = 45;
    const BG_CYAN = 46;
    const BG_GREY = 47;

    const RESET = 0;
    const NORMAL = 0;
    const BOLD = 1;
    const ITALIC = 3;
    const UNDERLINE = 4;
    const BLINK = 5;
    const NEGATIVE = 7;
    const CONCEALED = 8;
    const CROSSED_OUT = 9;
    const FRAMED = 51;
    const ENCIRCLED = 52;
    const OVERLINED = 53;

    /**
     * Moves the terminal cursor up by sending ANSI control code CUU to the terminal.
     * If the cursor is already at the edge of the screen, this has no effect.
     * @param integer $rows number of rows the cursor should be moved up
     */
    public static function moveCursorUp($rows = 1) {
        echo "\033[" . (int)$rows . 'A';
    }

    /**
     * Moves the terminal cursor down by sending ANSI control code CUD to the terminal.
     * If the cursor is already at the edge of the screen, this has no effect.
     * @param integer $rows number of rows the cursor should be moved down
     */
    public static function moveCursorDown($rows = 1) {
        echo "\033[" . (int)$rows . 'B';
    }

    /**
     * Moves the terminal cursor forward by sending ANSI control code CUF to the terminal.
     * If the cursor is already at the edge of the screen, this has no effect.
     * @param integer $steps number of steps the cursor should be moved forward
     */
    public static function moveCursorForward($steps = 1) {
        echo "\033[" . (int)$steps . 'C';
    }

    /**
     * Moves the terminal cursor backward by sending ANSI control code CUB to the terminal.
     * If the cursor is already at the edge of the screen, this has no effect.
     * @param integer $steps number of steps the cursor should be moved backward
     */
    public static function moveCursorBackward($steps = 1) {
        echo "\033[" . (int)$steps . 'D';
    }

    /**
     * Moves the terminal cursor to the beginning of the next line by sending ANSI control code CNL to the terminal.
     * @param integer $lines number of lines the cursor should be moved down
     */
    public static function moveCursorNextLine($lines = 1) {
        echo "\033[" . (int)$lines . 'E';
    }

    /**
     * Moves the terminal cursor to the beginning of the previous line by sending ANSI control code CPL to the terminal.
     * @param integer $lines number of lines the cursor should be moved up
     */
    public static function moveCursorPrevLine($lines = 1) {
        echo "\033[" . (int)$lines . 'F';
    }

    /**
     * Moves the cursor to an absolute position given as column and row by sending ANSI control code CUP or CHA to the terminal.
     * @param integer $column 1-based column number, 1 is the left edge of the screen.
     * @param integer|null $row 1-based row number, 1 is the top edge of the screen. if not set, will move cursor only in current line.
     */
    public static function moveCursorTo($column, $row = null) {
        if ($row === null) {
            echo "\033[" . (int)$column . 'G';
        } else {
            echo "\033[" . (int)$row . ';' . (int)$column . 'H';
        }
    }

    /**
     * Scrolls whole page up by sending ANSI control code SU to the terminal.
     * New lines are added at the bottom. This is not supported by ANSI.SYS used in windows.
     * @param integer $lines number of lines to scroll up
     */
    public static function scrollUp($lines = 1) {
        echo "\033[" . (int)$lines . "S";
    }

    /**
     * Scrolls whole page down by sending ANSI control code SD to the terminal.
     * New lines are added at the top. This is not supported by ANSI.SYS used in windows.
     * @param integer $lines number of lines to scroll down
     */
    public static function scrollDown($lines = 1) {
        echo "\033[" . (int)$lines . "T";
    }

    /**
     * Saves the current cursor position by sending ANSI control code SCP to the terminal.
     * Position can then be restored with [[restoreCursorPosition()]].
     */
    public static function saveCursorPosition() {
        echo "\033[s";
    }

    /**
     * Restores the cursor position saved with [[saveCursorPosition()]] by sending ANSI control code RCP to the terminal.
     */
    public static function restoreCursorPosition() {
        echo "\033[u";
    }

    /**
     * Hides the cursor by sending ANSI DECTCEM code ?25l to the terminal.
     * Use [[showCursor()]] to bring it back.
     * Do not forget to show cursor when your application exits. Cursor might stay hidden in terminal after exit.
     */
    public static function hide_cursor() {
        echo "\033[?25l";
    }

    /**
     * Will show a cursor again when it has been hidden by [[hideCursor()]]  by sending ANSI DECTCEM code ?25h to the terminal.
     */
    public static function show_cursor() {
        echo "\033[?25h";
    }

    /**
     * Clears entire screen content by sending ANSI control code ED with argument 2 to the terminal.
     * Cursor position will not be changed.
     * **Note:** ANSI.SYS implementation used in windows will reset cursor position to upper left corner of the screen.
     */
    public static function clear_screen() {
        echo "\033[2J";
    }

    /**
     * Clears text from cursor to the beginning of the screen by sending ANSI control code ED with argument 1 to the terminal.
     * Cursor position will not be changed.
     */
    public static function clearScreenBeforeCursor() {
        echo "\033[1J";
    }

    /**
     * Clears text from cursor to the end of the screen by sending ANSI control code ED with argument 0 to the terminal.
     * Cursor position will not be changed.
     */
    public static function clearScreenAfterCursor() {
        echo "\033[0J";
    }

    /**
     * Clears the line, the cursor is currently on by sending ANSI control code EL with argument 2 to the terminal.
     * Cursor position will not be changed.
     */
    public static function clear_line() {
        echo "\033[2K";
    }

    /**
     * Clears text from cursor position to the beginning of the line by sending ANSI control code EL with argument 1 to the terminal.
     * Cursor position will not be changed.
     */
    public static function clearLineBeforeCursor() {
        echo "\033[1K";
    }

    /**
     * Clears text from cursor position to the end of the line by sending ANSI control code EL with argument 0 to the terminal.
     * Cursor position will not be changed.
     */
    public static function clearLineAfterCursor() {
        echo "\033[0K";
    }

    /**
     * Returns the ANSI format code.
     *
     * @param array $format An array containing formatting values.
     * You can pass any of the FG_*, BG_* and TEXT_* constants
     * and also [[xtermFgColor]] and [[xtermBgColor]] to specify a format.
     * @return string The ANSI format code according to the given formatting constants.
     */
    public static function ansi_format_code($format) {
        return "\033[" . implode(';', $format) . 'm';
    }

    /**
     * Echoes an ANSI format code that affects the formatting of any text that is printed afterwards.
     *
     * @param array $format An array containing formatting values.
     * You can pass any of the FG_*, BG_* and TEXT_* constants
     * and also [[xtermFgColor]] and [[xtermBgColor]] to specify a format.
     * @see ansiFormatCode()
     * @see endAnsiFormat()
     */
    public static function begin_ansi_format($format) {
        echo "\033[" . implode(';', $format) . 'm';
    }

    /**
     * Resets any ANSI format set by previous method [[beginAnsiFormat()]]
     * Any output after this will have default text format.
     * This is equal to calling
     *
     * ```php
     * echo Console::ansiFormatCode([Console::RESET])
     * ```
     */
    public static function end_ansi_format() {
        echo "\033[0m";
    }

    /**
     * Will return a string formatted with the given ANSI style
     *
     * @param string $string the string to be formatted
     * @param array $format An array containing formatting values.
     * You can pass any of the FG_*, BG_* and TEXT_* constants
     * and also [[xtermFgColor]] and [[xtermBgColor]] to specify a format.
     * @return string
     */
    public static function ansi_format($string, $format = []) {
        $code = implode(';', $format);

        return "\033[0m" . ($code !== '' ? "\033[" . $code . "m" : '') . $string . "\033[0m";
    }

    /**
     * Returns the ansi format code for xterm foreground color.
     * You can pass the return value of this to one of the formatting methods:
     * [[ansiFormat]], [[ansiFormatCode]], [[beginAnsiFormat]]
     *
     * @param integer $colorCode xterm color code
     * @return string
     * @see http://en.wikipedia.org/wiki/Talk:ANSI_escape_code#xterm-256colors
     */
    public static function xtermFgColor($colorCode) {
        return '38;5;' . $colorCode;
    }

    /**
     * Returns the ansi format code for xterm background color.
     * You can pass the return value of this to one of the formatting methods:
     * [[ansiFormat]], [[ansiFormatCode]], [[beginAnsiFormat]]
     *
     * @param integer $colorCode xterm color code
     * @return string
     * @see http://en.wikipedia.org/wiki/Talk:ANSI_escape_code#xterm-256colors
     */
    public static function xtermBgColor($colorCode) {
        return '48;5;' . $colorCode;
    }

    /**
     * Strips ANSI control codes from a string
     *
     * @param string $string String to strip
     * @return string
     */
    public static function stripAnsiFormat($string) {
        return preg_replace('/\033\[[\d;?]*\w/', '', $string);
    }

    /**
     * Returns the length of the string without ANSI color codes.
     * @param string $string the string to measure
     * @return integer the length of the string not counting ANSI format characters
     */
    public static function ansiStrlen($string) {
        return mb_strlen(static::stripAnsiFormat($string));
    }

    /**
     * Converts an ANSI formatted string to HTML
     *
     * Note: xTerm 256 bit colors are currently not supported.
     *
     * @param string $string the string to convert.
     * @param array $styleMap an optional mapping of ANSI control codes such as
     * [[FG_COLOR]] or [[BOLD]] to a set of css style definitions.
     * The CSS style definitions are represented as an array where the array keys correspond
     * to the css style attribute names and the values are the css values.
     * values may be arrays that will be merged and imploded with `' '` when rendered.
     * @return string HTML representation of the ANSI formatted string
     */
    public static function ansiToHtml($string, $styleMap = []) {
        $styleMap = [
                // http://www.w3.org/TR/CSS2/syndata.html#value-def-color
                self::FG_BLACK => ['color' => 'black'],
                self::FG_BLUE => ['color' => 'blue'],
                self::FG_CYAN => ['color' => 'aqua'],
                self::FG_GREEN => ['color' => 'lime'],
                self::FG_GREY => ['color' => 'silver'],
                // http://meyerweb.com/eric/thoughts/2014/06/19/rebeccapurple/
                // http://dev.w3.org/csswg/css-color/#valuedef-rebeccapurple
                self::FG_PURPLE => ['color' => 'rebeccapurple'],
                self::FG_RED => ['color' => 'red'],
                self::FG_YELLOW => ['color' => 'yellow'],
                self::BG_BLACK => ['background-color' => 'black'],
                self::BG_BLUE => ['background-color' => 'blue'],
                self::BG_CYAN => ['background-color' => 'aqua'],
                self::BG_GREEN => ['background-color' => 'lime'],
                self::BG_GREY => ['background-color' => 'silver'],
                self::BG_PURPLE => ['background-color' => 'rebeccapurple'],
                self::BG_RED => ['background-color' => 'red'],
                self::BG_YELLOW => ['background-color' => 'yellow'],
                self::BOLD => ['font-weight' => 'bold'],
                self::ITALIC => ['font-style' => 'italic'],
                self::UNDERLINE => ['text-decoration' => ['underline']],
                self::OVERLINED => ['text-decoration' => ['overline']],
                self::CROSSED_OUT => ['text-decoration' => ['line-through']],
                self::BLINK => ['text-decoration' => ['blink']],
                self::CONCEALED => ['visibility' => 'hidden'],
            ] + $styleMap;

        $tags = 0;
        $result = preg_replace_callback(
            '/\033\[([\d;]+)m/',
            function ($ansi) use (&$tags, $styleMap) {
                $style = [];
                $reset = false;
                $negative = false;
                foreach (explode(';', $ansi[1]) as $controlCode) {
                    if ($controlCode == 0) {
                        $style = [];
                        $reset = true;
                    } elseif ($controlCode == self::NEGATIVE) {
                        $negative = true;
                    } elseif (isset($styleMap[$controlCode])) {
                        $style[] = $styleMap[$controlCode];
                    }
                }

                $return = '';
                while ($reset && $tags > 0) {
                    $return .= '';
                    $tags--;
                }
                if (empty($style)) {
                    return $return;
                }

                $currentStyle = [];
                foreach ($style as $content) {
                    $currentStyle = ArrayHelper::merge($currentStyle, $content);
                }

                // if negative is set, invert background and foreground
                if ($negative) {
                    if (isset($currentStyle['color'])) {
                        $fgColor = $currentStyle['color'];
                        unset($currentStyle['color']);
                    }
                    if (isset($currentStyle['background-color'])) {
                        $bgColor = $currentStyle['background-color'];
                        unset($currentStyle['background-color']);
                    }
                    if (isset($fgColor)) {
                        $currentStyle['background-color'] = $fgColor;
                    }
                    if (isset($bgColor)) {
                        $currentStyle['color'] = $bgColor;
                    }
                }

                $styleString = '';
                foreach ($currentStyle as $name => $value) {
                    if (is_array($value)) {
                        $value = implode(' ', $value);
                    }
                    $styleString .= "$name: $value;";
                }
                $tags++;
                return "$return";
            },
            $string
        );
        while ($tags > 0) {
            $result .= '';
            $tags--;
        }
        return $result;
    }

    /**
     * Converts a string to ansi formatted by replacing patterns like %y (for yellow) with ansi control codes
     *
     * Uses almost the same syntax as https://github.com/pear/Console_Color2/blob/master/Console/Color2.php
     * The conversion table is: ('bold' meaning 'light' on some
     * terminals). It's almost the same conversion table irssi uses.
     *

     *                  text      text            background
     *      ------------------------------------------------
     *      %k %K %0    black     dark grey       black
     *      %r %R %1    red       bold red        red
     *      %g %G %2    green     bold green      green
     *      %y %Y %3    yellow    bold yellow     yellow
     *      %b %B %4    blue      bold blue       blue
     *      %m %M %5    magenta   bold magenta    magenta
     *      %p %P       magenta (think: purple)
     *      %c %C %6    cyan      bold cyan       cyan
     *      %w %W %7    white     bold white      white
     *
     *      %F     Blinking, Flashing
     *      %U     Underline
     *      %8     Reverse
     *      %_,%9  Bold
     *
     *      %n     Resets the color
     *      %%     A single %
     *

     * First param is the string to convert, second is an optional flag if
     * colors should be used. It defaults to true, if set to false, the
     * color codes will just be removed (And %% will be transformed into %)
     *
     * @param string $string String to convert
     * @param boolean $colored Should the string be colored?
     * @return string
     */
    public static function render_colored_string($string, $colored = true) {
        // TODO rework/refactor according to https://github.com/yiisoft/yii2/issues/746
        static $conversions = [
            '%y' => [self::FG_YELLOW],
            '%g' => [self::FG_GREEN],
            '%b' => [self::FG_BLUE],
            '%r' => [self::FG_RED],
            '%p' => [self::FG_PURPLE],
            '%m' => [self::FG_PURPLE],
            '%c' => [self::FG_CYAN],
            '%w' => [self::FG_GREY],
            '%k' => [self::FG_BLACK],
            '%n' => [0], // reset
            '%Y' => [self::FG_YELLOW, self::BOLD],
            '%G' => [self::FG_GREEN, self::BOLD],
            '%B' => [self::FG_BLUE, self::BOLD],
            '%R' => [self::FG_RED, self::BOLD],
            '%P' => [self::FG_PURPLE, self::BOLD],
            '%M' => [self::FG_PURPLE, self::BOLD],
            '%C' => [self::FG_CYAN, self::BOLD],
            '%W' => [self::FG_GREY, self::BOLD],
            '%K' => [self::FG_BLACK, self::BOLD],
            '%N' => [0, self::BOLD],
            '%3' => [self::BG_YELLOW],
            '%2' => [self::BG_GREEN],
            '%4' => [self::BG_BLUE],
            '%1' => [self::BG_RED],
            '%5' => [self::BG_PURPLE],
            '%6' => [self::BG_PURPLE],
            '%7' => [self::BG_CYAN],
            '%0' => [self::BG_GREY],
            '%F' => [self::BLINK],
            '%U' => [self::UNDERLINE],
            '%8' => [self::NEGATIVE],
            '%9' => [self::BOLD],
            '%_' => [self::BOLD],
        ];

        if ($colored) {
            $string = str_replace('%%', '% ', $string);
            foreach ($conversions as $key => $value) {
                $string = str_replace(
                    $key,
                    static::ansiFormatCode($value),
                    $string
                );
            }
            $string = str_replace('% ', '%', $string);
        } else {
            $string = preg_replace('/%((%)|.)/', '$2', $string);
        }

        return $string;
    }

    /**
     * Escapes % so they don't get interpreted as color codes when
     * the string is parsed by [[renderColoredString]]
     *
     * @param string $string String to escape
     *
     * @access public
     * @return string
     */
    public static function escape($string) {
        // TODO rework/refactor according to https://github.com/yiisoft/yii2/issues/746
        return str_replace('%', '%%', $string);
    }

    /**
     * Returns true if the stream supports colorization. ANSI colors are disabled if not supported by the stream.
     *
     * - windows without ansicon
     * - not tty consoles
     *
     * @param mixed $stream
     * @return boolean true if the stream supports ANSI colors, otherwise false.
     */
    public static function stream_supports_ansi_colors($stream) {
        return DIRECTORY_SEPARATOR == '\\'
            ? getenv('ANSICON') !== false || getenv('ConEmuANSI') === 'ON'
            : function_exists('posix_isatty') && @posix_isatty($stream);
    }

    /**
     * Returns true if the console is running on windows
     * @return bool
     */
    public static function is_running_on_windows() {
        return DIRECTORY_SEPARATOR == '\\';
    }

    /**
     * Usage: list($width, $height) = ConsoleHelper::getScreenSize();
     *
     * @param boolean $refresh whether to force checking and not re-use cached size value.
     * This is useful to detect changing window size while the application is running but may
     * not get up to date values on every terminal.
     * @return array|boolean An array of ($width, $height) or false when it was not able to determine size.
     */
    public static function get_screen_size($refresh = false) {
        static $size;
        if ($size !== null && !$refresh) {
            return $size;
        }

        if (static::is_running_on_windows()) {
            $output = [];
            exec('mode con', $output);
            if (isset($output, $output[1]) && strpos($output[1], 'CON') !== false) {
                return $size = [(int)preg_replace('~[^0-9]~', '', $output[3]), (int)preg_replace('~[^0-9]~', '', $output[4])];
            }
        } else {
            // try stty if available
            $stty = [];
            if (exec('stty -a 2>&1', $stty) && preg_match('/rows\s+(\d+);\s*columns\s+(\d+);/mi', implode(' ', $stty), $matches)) {
                return $size = [$matches[2], $matches[1]];
            }

            // fallback to tput, which may not be updated on terminal resize
            if (($width = (int)exec('tput cols 2>&1')) > 0 && ($height = (int)exec('tput lines 2>&1')) > 0) {
                return $size = [$width, $height];
            }

            // fallback to ENV variables, which may not be updated on terminal resize
            if (($width = (int)getenv('COLUMNS')) > 0 && ($height = (int)getenv('LINES')) > 0) {
                return $size = [$width, $height];
            }
        }

        return $size = false;
    }

    /**
     * Word wrap text with indentation to fit the screen size
     *
     * If screen size could not be detected, or the indentation is greater than the screen size, the text will not be wrapped.
     *
     * The first line will **not** be indented, so `Console::wrapText("Lorem ipsum dolor sit amet.", 4)` will result in the
     * following output, given the screen width is 16 characters:
     *
     * ```
     * Lorem ipsum
     *     dolor sit
     *     amet.
     * ```
     *
     * @param string $text the text to be wrapped
     * @param integer $indent number of spaces to use for indentation.
     * @param boolean $refresh whether to force refresh of screen size.
     * This will be passed to [[getScreenSize()]].
     * @return string the wrapped text.
     * @since 2.0.4
     */
    public static function wrapText($text, $indent = 0, $refresh = false) {
        $size = static::getScreenSize($refresh);
        if ($size === false || $size[0] <= $indent) {
            return $text;
        }
        $pad = str_repeat(' ', $indent);
        $lines = explode("\n", wordwrap($text, $size[0] - $indent, "\n", true));
        $first = true;
        foreach ($lines as $i => $line) {
            if ($first) {
                $first = false;
                continue;
            }
            $lines[$i] = $pad . $line;
        }
        return implode("\n", $lines);
    }

    /**
     * Gets input from STDIN and returns a string right-trimmed for EOLs.
     *
     * @param boolean $raw If set to true, returns the raw string without trimming
     * @return string the string read from stdin
     */
    public static function stdin($raw = false) {
        return $raw ? fgets(\STDIN) : rtrim(fgets(\STDIN), PHP_EOL);
    }

    /**
     * Prints a string to STDOUT.
     *
     * @param string $string the string to print
     * @return int|boolean Number of bytes printed or false on error
     */
    public static function stdout($string) {
        return fwrite(\STDOUT, $string);
    }

    /**
     * Prints a string to STDERR.
     *
     * @param string $string the string to print
     * @return int|boolean Number of bytes printed or false on error
     */
    public static function stderr($string) {
        return fwrite(\STDERR, $string);
    }

    /**
     * Asks the user for input. Ends when the user types a carriage return (PHP_EOL). Optionally, It also provides a
     * prompt.
     *
     * @param string $prompt the prompt to display before waiting for input (optional)
     * @return string the user's input
     */
    public static function input($prompt = null) {
        if (isset($prompt)) {
            static::stdout($prompt);
        }

        return static::stdin();
    }

    /**
     * Prints text to STDOUT appended with a carriage return (PHP_EOL).
     *
     * @param string $string the text to print
     * @return integer|boolean number of bytes printed or false on error.
     */
    public static function output($string = null) {
        return static::stdout($string . PHP_EOL);
    }

    /**
     * Prints text to STDERR appended with a carriage return (PHP_EOL).
     *
     * @param string $string the text to print
     * @return integer|boolean number of bytes printed or false on error.
     */
    public static function error($string = null) {
        return static::stderr($string . PHP_EOL);
    }

    /**
     * Prompts the user for input and validates it
     *
     * @param string $text prompt string
     * @param array $options the options to validate the input:
     *
     * - `required`: whether it is required or not
     * - `default`: default value if no input is inserted by the user
     * - `pattern`: regular expression pattern to validate user input
     * - `validator`: a callable function to validate input. The function must accept two parameters:
     * - `input`: the user input to validate
     * - `error`: the error value passed by reference if validation failed.
     *
     * @return string the user input
     */
    public static function prompt($text, $options = []) {
        $options = ArrayHelper::merge(
            [
                'required' => false,
                'default' => null,
                'pattern' => null,
                'validator' => null,
                'error' => 'Invalid input.',
            ],
            $options
        );
        $error = null;

        top:
        $input = $options['default']
            ? static::input("$text [" . $options['default'] . '] ')
            : static::input("$text ");

        if (!strlen($input)) {
            if (isset($options['default'])) {
                $input = $options['default'];
            } elseif ($options['required']) {
                static::output($options['error']);
                goto top;
            }
        } elseif ($options['pattern'] && !preg_match($options['pattern'], $input)) {
            static::output($options['error']);
            goto top;
        } elseif ($options['validator'] &&
            !call_user_func_array($options['validator'], [$input, &$error])
        ) {
            static::output(isset($error) ? $error : $options['error']);
            goto top;
        }

        return $input;
    }

    /**
     * Asks user to confirm by typing y or n.
     *
     * @param string $message to print out before waiting for user input
     * @param boolean $default this value is returned if no selection is made.
     * @return boolean whether user confirmed
     */
    public static function confirm($message, $default = false) {
        while (true) {
            static::stdout($message . ' (yes|no) [' . ($default ? 'yes' : 'no') . ']:');
            $input = trim(static::stdin());

            if (empty($input)) {
                return $default;
            }

            if (!strcasecmp($input, 'y') || !strcasecmp($input, 'yes')) {
                return true;
            }

            if (!strcasecmp($input, 'n') || !strcasecmp($input, 'no')) {
                return false;
            }
        }
    }

    /**
     * Gives the user an option to choose from. Giving '?' as an input will show
     * a list of options to choose from and their explanations.
     *
     * @param string $prompt the prompt message
     * @param array $options Key-value array of options to choose from
     *
     * @return string An option character the user chose
     */
    public static function select($prompt, $options = []) {
        top:
        static::stdout("$prompt [" . implode(',', array_keys($options)) . ",?]: ");
        $input = static::stdin();
        if ($input === '?') {
            foreach ($options as $key => $value) {
                static::output(" $key - $value");
            }
            static::output(" ? - Show help");
            goto top;
        } elseif (!array_key_exists($input, $options)) {
            goto top;
        }

        return $input;
    }

    private static $_progressStart;
    private static $_progressWidth;
    private static $_progressPrefix;

    /**
     * Starts display of a progress bar on screen.
     *
     * This bar will be updated by [[updateProgress()]] and my be ended by [[endProgress()]].
     *
     * The following example shows a simple usage of a progress bar:
     *
     * ```php
     * Console::startProgress(0, 1000);
     * for ($n = 1; $n <= 1000; $n++) {
     *     usleep(1000);
     *     Console::updateProgress($n, 1000);
     * }
     * Console::endProgress();
     * ```
     *
     * Git clone like progress (showing only status information):
     * ```php
     * Console::startProgress(0, 1000, 'Counting objects: ', false);
     * for ($n = 1; $n <= 1000; $n++) {
     *     usleep(1000);
     *     Console::updateProgress($n, 1000);
     * }
     * Console::endProgress("done." . PHP_EOL);
     * ```
     *
     * @param integer $done the number of items that are completed.
     * @param integer $total the total value of items that are to be done.
     * @param string $prefix an optional string to display before the progress bar.
     * Default to empty string which results in no prefix to be displayed.
     * @param integer|boolean $width optional width of the progressbar. This can be an integer representing
     * the number of characters to display for the progress bar or a float between 0 and 1 representing the
     * percentage of screen with the progress bar may take. It can also be set to false to disable the
     * bar and only show progress information like percent, number of items and ETA.
     * If not set, the bar will be as wide as the screen. Screen size will be detected using [[getScreenSize()]].
     * @see startProgress
     * @see updateProgress
     * @see endProgress
     */
    public static function start_progress($done, $total, $prefix = '', $width = null) {
        self::$_progressStart = time();
        self::$_progressWidth = $width;
        self::$_progressPrefix = $prefix;

        static::update_progress($done, $total);
    }

    /**
     * Updates a progress bar that has been started by [[startProgress()]].
     *
     * @param integer $done the number of items that are completed.
     * @param integer $total the total value of items that are to be done.
     * @param string $prefix an optional string to display before the progress bar.
     * Defaults to null meaning the prefix specified by [[startProgress()]] will be used.
     * If prefix is specified it will update the prefix that will be used by later calls.
     * @see startProgress
     * @see endProgress
     */
    public static function update_progress($done, $total, $prefix = null) {
        $width = self::$_progressWidth;
        if ($width === false) {
            $width = 0;
        } else {
            $screenSize = static::get_screen_size(true);
            if ($screenSize === false && $width < 1) {
                $width = 0;
            } elseif ($width === null) {
                $width = $screenSize[0];
            } elseif ($width > 0 && $width < 1) {
                $width = floor($screenSize[0] * $width);
            }
        }
        if ($prefix === null) {
            $prefix = self::$_progressPrefix;
        } else {
            self::$_progressPrefix = $prefix;
        }
        $width -= static::ansi_strlen($prefix);

        $percent = ($total == 0) ? 1 : $done / $total;
        $info = sprintf("%d%% (%d/%d)", $percent * 100, $done, $total);

        if ($done > $total || $done == 0) {
            $info .= ' ETA: n/a';
        } elseif ($done < $total) {
            $rate = (time() - self::$_progressStart) / $done;
            $info .= sprintf(' ETA: %d sec.', $rate * ($total - $done));
        }

        $width -= 3 + static::ansi_strlen($info);
        // skipping progress bar on very small display or if forced to skip
        if ($width < 5) {
            static::stdout("\r$prefix$info   ");
        } else {
            if ($percent < 0) {
                $percent = 0;
            } elseif ($percent > 1) {
                $percent = 1;
            }
            $bar = floor($percent * $width);
            $status = str_repeat("=", $bar);
            if ($bar < $width) {
                $status .= ">";
                $status .= str_repeat(" ", $width - $bar - 1);
            }
            static::stdout("\r$prefix" . "[$status] $info");
        }
        flush();
    }

    /**
     * Ends a progress bar that has been started by [[startProgress()]].
     *
     * @param string|boolean $remove This can be `false` to leave the progress bar on screen and just print a newline.
     * If set to `true`, the line of the progress bar will be cleared. This may also be a string to be displayed instead
     * of the progress bar.
     * @param boolean $keepPrefix whether to keep the prefix that has been specified for the progressbar when progressbar
     * gets removed. Defaults to true.
     * @see startProgress
     * @see updateProgress
     */
    public static function end_progress($remove = false, $keepPrefix = true) {
        if ($remove === false) {
            static::stdout(PHP_EOL);
        } else {
            if (static::stream_supports_ansi_colors(STDOUT)) {
                static::clear_line();
            }
            static::stdout("\r" . ($keepPrefix ? self::$_progressPrefix : '') . (is_string($remove) ? $remove : ''));
        }
        flush();

        self::$_progressStart = null;
        self::$_progressWidth = null;
        self::$_progressPrefix = '';
    }
}