h-roman
10/9/2017 - 12:46 PM

Шаблон консольного скрипт

Шаблон консольного скрипт

<?php
// Увеличиваем лимит на выполнение
ini_set('memory_limit', '1G');

// Make sure we're being called from the command line, not a web interface
if (array_key_exists('REQUEST_METHOD', $_SERVER)) die();

// Set flag that this is a parent file.
define('_JEXEC', 1);
define('DS', DIRECTORY_SEPARATOR);

error_reporting(E_ALL^E_STRICT);
ini_set('display_errors', 1);

// Load system defines
if (file_exists(dirname(dirname(__FILE__)) . '/defines.php'))
{
    require_once dirname(dirname(__FILE__)) . '/defines.php';
}

if (!defined('_JDEFINES'))
{
    define('JPATH_BASE', dirname(dirname(__FILE__)));
    require_once JPATH_BASE . '/includes/defines.php';
}

require_once JPATH_LIBRARIES . '/import.php';
require_once JPATH_LIBRARIES . '/cms.php';

// Force library to be in JError legacy mode
JError::$legacy = true;

// Load the configuration
require_once JPATH_CONFIGURATION . '/configuration.php';
require JPATH_BASE . '/plugins/system/kint/kint-master/Kint.class.php';
require_once(JPATH_BASE . '/language/ru-RU/ru-RU.localise.php');
jimport('joomla.database.table' );
jimport('joomla.application.component.helper');
jimport('joomla.environment.uri');
jimport('joomla.environment.request');

/**
 * This script will fetch the update information for all extensions and store
 * them in the database, speeding up your administrator.
 *
 * @package  Joomla.CLI
 * @since    2.5
 */
class BitShopImport extends JApplicationCli
{


    protected $params = array();

    public function __construct() {

        $this->getCliParams();

    }



    /**
     * Entry point for the script
     *
     * @return  void
     *
     * @since   2.5
     */
    public function doExecute()
    {



        $progress= $this->getProgress(10000, $rogresiv=true);

        for ($i = 1; $i <= 10000; $i++) {
            $progress->progress();
        }




        $this->beep();
        $this->out('');
    }






    /*=========================================*/
    /*==============  СИСТЕМНОЕ  ==============*/
    /*=========================================*/

    /**
     * Получаем модели
     * @param string $name
     * @param string $prefix
     * @return mixed
     */
    public function getModel($name = 'Category', $prefix = 'CategoriesModel') {
        JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_categories/models');
        JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_categories/tables');
        return JModelLegacy::getInstance($name, $prefix);
    }

    /**
     * Вывод текста в консоль
     * @param $str
     * @param bool $params
     */
    public function out($str, $params=false){

        if($this->getParam('silent', false)) return;


        $fontStyle['wight']['bold']='1';
        $fontStyle['wight']['underline']='4';
        $fontStyle['wight']['blank']='4';

        $fontStyle['color']['black']='30';
        $fontStyle['color']['red']='31';
        $fontStyle['color']['green']='32';
        $fontStyle['color']['yellow']='33';
        $fontStyle['color']['blue']='34';
        $fontStyle['color']['white']='37';

        $fontStyle['bgcolor']['black']='40';
        $fontStyle['bgcolor']['red']='41';
        $fontStyle['bgcolor']['green']='42';
        $fontStyle['bgcolor']['yellow']='43';
        $fontStyle['bgcolor']['blue']='44';
        $fontStyle['bgcolor']['white']='47';

        if($params && is_array($params)) {

            foreach ($params as $key => $value) {
                if (isset($fontStyle[$key]) && isset($fontStyle[$key][$value])) {
                    $strParams[] = $fontStyle[$key][$value];
                }
            }

            $str="\x1b[".implode(';',$strParams)."m$str\x1b[0m";


        }


        parent::out($str);
    }

    /**
     * Пикнуть в консоль
     */
    function beep() {
        echo "\x07";
    }

    /**
     * Красивый заголовок
     * @param $title
     */
    public function showTitle($title) {

        $length=mb_strlen($title);
        $tab=10;

        $header[]="╔".str_repeat('═',$tab).str_repeat('═',$length).str_repeat('═',$tab).'╗';
        $header[]="║".str_repeat(' ',$tab).$title.str_repeat(' ',$tab)."║";
        $header[]="╚".str_repeat('═',$tab).str_repeat('═',$length).str_repeat('═',$tab).'╝';

        $this->out(implode("\n",$header),array('color'=>'green'));

    }


    /**
     * Получаем параметры из строки кансоли
     */
    public function getCliParams() {
        $longopts[] = "silent::"; // Работа в тихом режиме;

        $params = getopt("", $longopts);
        $this->params = array();
        $this->params['silent'] = isset($params['silent']) ?: false;



        return $this->params;
    }

    /**
     * Получить значение параметра из строки
     * @param $name
     * @param bool $default
     * @return bool|mixed
     */
    public function getParam($name,$default=false) {
        return isset($this->params[$name]) ? $this->params[$name] : $default;
    }


    function getProgress($count,$progresiv=false) {
        return new SlCliProgress($count, $progresiv, $this->getParam('silent'));
    }

}


class SlCliProgress extends JApplicationCli {
    var $index=0;
    var $count;
    var $silent;
    var $progresiv=false;

    public function __construct($count, $progresiv=false, $silent) {
        $this->count=$count;
        $this->silent=$silent;
        $this->progresiv=$progresiv;

    }

    public function progress() {
        $this->index++;

        if($this->silent) return;

        if($this->index==1) {
            $this->showProgress();
        }
        elseif($this->count>=500) {
            if($this->index % 100 == 0 || $this->count<=$this->index) $this->showProgress($this->index,$this->count);
        }
        elseif (($this->count<=500 && $this->count>=50) || $this->count<=$this->index) {
            if($this->index % 50 == 0 || $this->count<=$this->index) $this->showProgress($this->index,$this->count);
        }
        else {
            $this->showshowProgress();
        }
    }

    public function showProgress() {


        $procent=round(($this->index / ($this->count / 100)), 0);
        $string[]="[".date('Y-m-d h:i:s')."] ";
        $string[]="(".$procent."%)";
        $string[]="[";
        $string[]=str_repeat("\x1b[32m■\x1b[0m",$procent);
        $string[]=str_repeat("\x1b[33m■\x1b[0m",100-$procent);
        $string[]="]";
        $string[]=' '.$this->index.'/'.$this->count;

        parent::out("\r",false);
        parent::out(implode('',$string),false);

    }

}



JApplicationCli::getInstance('BitShopImport')->execute();