DateControl.php 16.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
<?php

/**
 * @package   yii2-datecontrol
 * @author    Kartik Visweswaran <kartikv2@gmail.com>
 * @copyright Copyright &copy; Kartik Visweswaran, Krajee.com, 2014 - 2015
 * @version   1.9.4
 */

namespace kartik\datecontrol;

use DateTime;
use DateTimeZone;
use Yii;
use yii\helpers\Html;
use yii\helpers\Url;
use yii\helpers\Json;
use yii\helpers\ArrayHelper;
use yii\helpers\FormatConverter;
use yii\base\InvalidConfigException;
use yii\web\View;
use yii\web\JsExpression;
use kartik\base\Config;

/**
 * DateControl widget enables you to control the formatting of date/time separately in View (display) and Model (save).
 *
 * @author Kartik Visweswaran <kartikv2@gmail.com>
 * @since 1.0
 */
class DateControl extends \kartik\base\InputWidget
{
    const FORMAT_DATE = 'date';
    const FORMAT_TIME = 'time';
    const FORMAT_DATETIME = 'datetime';

    /**
     * @inherit doc
     */
    protected $_pluginName = 'datecontrol';

    /**
     * @var string data type to use for the displayed date control. One of the FORMAT constants.
     */
    public $type = self::FORMAT_DATE;

    /**
     * @var boolean whether to use ajaxConversion to process date format for the widget.
     */
    public $ajaxConversion;

    /**
     * @var string the format string for displaying the date. If not set, will automatically use the settings
     * from the Module based on the `type` setting.
     */
    public $displayFormat;

    /**
     * @var string the default format string to be save the date as. If not set, will automatically use the settings
     * from the Module.
     */
    public $saveFormat;

    /**
     * @var string the timezone for the displayed date. If not set, no timezone
     * setting will be applied for formatting.
     * @see http://php.net/manual/en/timezones.php
     */
    public $displayTimezone;

    /**
     * @var string the timezone for the saved date. If not set, no timezone
     * setting will be applied for formatting.
     * @see http://php.net/manual/en/timezones.php
     */
    public $saveTimezone;

    /**
     * @var bool whether to automatically use \kartik\widgets based on `$type`. Will use these widgets:
     * - \kartik\date\DatePicker for FORMAT_DATE
     * - \kartik\time\TimePicker for FORMAT_TIME
     * - \kartik\datetime\DateTimePicker for FORMAT_DATETIME
     * If not set, this will default to `true.`
     */
    public $autoWidget;

    /**
     * @var string any custom widget class to use. Will only be used if autoWidget is set to `false`.
     */
    public $widgetClass;

    /**
     * @var array the HTML attributes for the display input. If a widget is used based on `autoWidget` or `widgetClass`,
     * this will be considered as the widget options.
     */
    public $options = [];

    /**
     * @var array the HTML attributes for the base model input that will be saved typically to database.
     * The following special options are recognized:
     * - 'type': string, whether to generate a 'hidden' or 'text' input. Defaults to 'hidden'.
     * - 'label': string, any label to be placed before the input. Will be only displayed if 'type' is 'text'.
     */
    public $saveOptions = [];

    /**
     * @var boolean whether to fire an asynchronous ajax request. Defaults to `true`.
     * You can set this to `false` for cases, where you need this to be fired synchronously.
     * For example when using this widget as a filter in \kartik\grid\GridView.
     */
    public $asyncRequest = true;

    /**
     * @var string display attribute name
     */
    protected $_displayAttribName;

    /**
     * @var \kartik\datecontrol\Module the `datecontrol` module instance
     */
    protected $_module;

    /**
     * @var array the parsed widget settings from the module
     */
    protected $_widgetSettings = [];

    /**
     * @var boolean whether translation is needed
     */
    private $_doTranslate = false;

    /**
     * @var array the english date settings
     */
    private static $_enSettings = [
        'days' => ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
        'daysShort' => ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
        'months' => [
            'January', 'February', 'March', 'April', 'May', 'June', 'July',
            'August', 'September', 'October', 'November', 'December'
        ],
        'monthsShort' => ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
        'meridiem' => ['AM', 'PM']
    ];

    /**
     * Initializes widget
     *
     * @throws \yii\base\InvalidConfigException
     */
    public function init()
    {
        $this->initConfig();
        if (!isset($this->ajaxConversion)) {
            $this->ajaxConversion = $this->_module->ajaxConversion;
        }
        if (!$this->ajaxConversion && ($this->displayTimezone != null || $this->saveTimezone != null)) {
            throw new InvalidConfigException("You must set 'ajaxConversion' to 'true' when using time-zones for display or save.");
        }
        parent::init();
        $this->initLanguage();
        $this->setDataVar($this->_pluginName);
        $this->_displayAttribName = (($this->hasModel()) ? $this->attribute : $this->name) . '-' . $this->options['id'];
        $this->saveOptions['id'] = $this->options['id'];
        $this->options['id'] = $this->options['id'] . '-disp';
        $this->_doTranslate = isset($this->language) && $this->language != 'en';
        if ($this->_doTranslate && $this->autoWidget) {
            $this->_widgetSettings[$this->type]['options']['language'] = $this->language;
        }
        $this->setLocale();
    }

    /**
     * Initializes widget based on module settings
     *
     * @throws \yii\base\InvalidConfigException
     */
    protected function initConfig()
    {
        $this->_module = Config::initModule(Module::classname());
        if (!isset($this->autoWidget)) {
            $this->autoWidget = $this->_module->autoWidget;
        }
        if (!$this->autoWidget && !empty($this->widgetClass) && !class_exists($this->widgetClass)) {
            throw new InvalidConfigException("The widgetClass '{$this->widgetClass}' entered is invalid.");
        }
        if ($this->autoWidget === null) {
            $this->autoWidget = true;
        }
        $this->_widgetSettings = $this->_module->widgetSettings;
        if (empty($this->displayFormat)) {
            $this->displayFormat = $this->_module->getDisplayFormat($this->type);
        } else {
            $this->displayFormat = Module::parseFormat($this->displayFormat, $this->type);
        }
        if (empty($this->saveFormat)) {
            $this->saveFormat = $this->_module->getSaveFormat($this->type);
        } else {
            $this->saveFormat = Module::parseFormat($this->saveFormat, $this->type);
        }
        if (empty($this->displayTimezone)) {
            $this->displayTimezone = $this->_module->getDisplayTimezone();
        }
        if (empty($this->saveTimezone)) {
            $this->saveTimezone = $this->_module->getSaveTimezone();
        }
        if ($this->autoWidget) {
            $this->_widgetSettings = [
                self::FORMAT_DATE => ['class' => '\kartik\date\DatePicker'],
                self::FORMAT_DATETIME => ['class' => '\kartik\datetime\DateTimePicker'],
                self::FORMAT_TIME => ['class' => '\kartik\time\TimePicker'],
            ];
            Config::validateInputWidget($this->_widgetSettings[$this->type]['class'],
                "for DateControl '{$this->type}' format");
            foreach ($this->_widgetSettings as $type => $setting) {
                $this->_widgetSettings[$type]['options'] = $this->_module->autoWidgetSettings[$type];
                $this->_widgetSettings[$type]['disabled'] = $this->disabled;
                $this->_widgetSettings[$type]['readonly'] = $this->readonly;
            }
        }
        if (empty($this->widgetClass) && !empty($this->_widgetSettings[$this->type]['class'])) {
            $this->widgetClass = $this->_widgetSettings[$this->type]['class'];
        }
    }

    /**
     * Runs widget
     *
     * @return string|void
     */
    public function run()
    {
        $this->registerAssets();
        echo $this->getDisplayInput() . $this->getSaveInput();
        parent::run();
    }

    /**
     * Whether a widget is used to render the display
     *
     * @return bool
     */
    protected function isWidget()
    {
        return ($this->autoWidget || !empty($this->widgetClass));
    }

    /**
     * Generates the display input
     *
     * @return string
     */
    protected function getDisplayInput()
    {
        $value = empty($this->value) ? '' : $this->getDisplayValue($this->value);
        if (!$this->isWidget()) {
            if (empty($this->options['class'])) {
                $this->options['class'] = 'form-control';
            }
            return Html::textInput($this->_displayAttribName, $value, $this->options);
        }
        if (!empty($this->displayFormat) && $this->autoWidget) {
            $this->options = ArrayHelper::merge(Module::defaultWidgetOptions($this->type, $this->displayFormat),
                $this->options);
        }
        if (!empty($this->_widgetSettings[$this->type]['options'])) {
            $this->options = ArrayHelper::merge($this->_widgetSettings[$this->type]['options'], $this->options);
        }
        unset($this->options['model'], $this->options['attribute']);
        $this->options['name'] = $this->_displayAttribName;
        $this->options['value'] = $value;
        $class = $this->widgetClass;
        if (!property_exists($class, 'disabled')) {
            unset($this->options['disabled']);
        }
        if (!property_exists($class, 'readonly')) {
            unset($this->options['readonly']);
        }
        return $class::widget($this->options);
    }

    /**
     * Generates the save input
     *
     * @return string
     */
    protected function getSaveInput()
    {
        $type = ArrayHelper::remove($this->saveOptions, 'type', 'hidden');
        $label = ArrayHelper::remove($this->saveOptions, 'label', '');

        if ($type === 'text') {
            $this->saveOptions['tabindex'] = 10000;
            return $label . ($this->hasModel() ?
                Html::activeTextInput($this->model, $this->attribute, $this->saveOptions) :
                Html::textInput($this->name, $this->value, $this->saveOptions));
        }
        return $this->hasModel() ?
            Html::activeHiddenInput($this->model, $this->attribute, $this->saveOptions) :
            Html::hiddenInput($this->name, $this->value, $this->saveOptions);
    }

    /**
     * Gets the formatted display date value
     *
     * @param string $data the input date data
     *
     * @return string
     */
    protected function getDisplayValue($data)
    {
        /**
         * Fix to prevent DateTime defaulting the time
         * part to current time, for FORMAT_DATE
         */
        $saveDate = $data;
        $saveFormat = $this->saveFormat;
        $settings = $this->_doTranslate ? ArrayHelper::getValue($this->pluginOptions, 'dateSettings', []) : [];
        $date = static::getTimestamp($saveDate, $saveFormat, $this->saveTimezone, $settings);
        if ($date && $date instanceof DateTime) {
            if ($this->displayTimezone != null) {
                $date->setTimezone(new DateTimeZone($this->displayTimezone));
            }
            $value = $date->format($this->displayFormat);
            if ($this->_doTranslate) {
                $value = $this->translateDate($value, $this->displayFormat);
            }
            return $value;
        }
        return null;
    }

    /**
     * Translate the date string
     *
     * @param string $data the input date data
     * @param string $format the input date format
     *
     * @return string the translated date
     */
    protected function translateDate($data, $format)
    {
        $out = $data;
        foreach (self::$_enSettings as $key => $value) {
            if (static::checkFormatKey($format, $key)) {
                $out = $this->translate($out, $key);
            }
        }
        return $out;
    }

    /**
     * Translate a date pattern based on type
     *
     * @param string $string input date string
     * @param string $type the type of date pattern as set in [[$_enSettings]]
     *
     * @return string the translated string
     */
    protected function translate($string, $type)
    {
        if (empty($this->pluginOptions['dateSettings'][$type])) {
            return $string;
        }
        return str_ireplace(self::$_enSettings[$type], $this->pluginOptions['dateSettings'][$type], $string);
    }

    /**
     * Sets the locale using the locales configuration settings
     */
    protected function setLocale()
    {
        if (!$this->_doTranslate || !empty($this->pluginOptions['dateSettings'])) {
            return;
        }
        $file = static::getLocaleFile($this->language);
        if (file_exists($file)) {
            $this->pluginOptions['dateSettings'] = require($file);
        }
    }

    /**
     * Fetches the locale settings file
     * @param string $lang the locale/language ISO code
     * @return string the locale file name
     */
    protected static function getLocaleFile($lang)
    {
        $s = DIRECTORY_SEPARATOR;
        $file = __DIR__ . "{$s}locales{$s}{$lang}{$s}dateSettings.php";
        if (!file_exists($file)) {
            $langShort = Config::getLang($lang);
            $file = __DIR__ . "{$s}locales{$s}{$langShort}{$s}dateSettings.php";
        }
        return $file;
    }
    
    /**
     * Parses locale data and returns an english format
     * @param string $source the date source pattern
     * @param string $format the date format
     * @param string $settings the locale/language date settings
     * @return the converted date source to english
     */
    protected static function parseLocale($source, $format, $settings = [])
    {
        if (empty($settings)) {
            return $source;
        }
        foreach (self::$_enSettings as $key => $value) {
            if (!empty($settings[$key]) && static::checkFormatKey($format, $key)) {
                $source = str_ireplace($settings[$key], $value, $source);
            }
        }
        return $source;
    }
    
    /**
     * Checks if the format string contains the relevant date format 
     * pattern based on the passed key.
     * @param string $format the date format string
     * @param string $key the key to check
     * @return boolean
     */
    protected static function checkFormatKey($format, $key)
    {
        switch ($key) {
            case 'months':
                return strpos($format, 'F') !== false;
            case 'monthsShort':
                return strpos($format, 'M') !== false;
            case 'days':
                return strpos($format, 'l') !== false;
            case 'daysShort':
                return strpos($format, 'D') !== false;
            case 'meridiem':
                return stripos($format, 'A') !== false;
            default:
                return false;
        }
    }
    
    /**
     * Parses and normalizes a date source and converts it to a DateTime object
     * by parsing it based on specified format.
     * @param string $source the date source pattern
     * @param string $format the date format
     * @param string $timezone the date timezone
     * @param string $settings the locale/language date settings
     * @return DateTime object
     */
    public static function getTimestamp($source, $format, $timezone = null, $settings = [])
    {
        if (empty($source)) {
            return null;
        }
        $source = static::parseLocale($source, $format, $settings);
        if (substr($format, 0, 1) !== '!') {
            $format = '!' . $format;
        }
        if ($timezone != null) {
            $timestamp = DateTime::createFromFormat($format, $source, new DateTimeZone($timezone));
        } else {
            $timestamp = DateTime::createFromFormat($format, $source);
        }
        return $timestamp;
    }
    
    /**
     * Registers assets
     */
    protected function registerAssets()
    {
        $view = $this->getView();
        DateFormatterAsset::register($view);
        DateControlAsset::register($view);
        $pluginOptions = empty($this->pluginOptions) ? [] : $this->pluginOptions;
        $this->pluginOptions = ArrayHelper::merge([
            'idSave' => $this->saveOptions['id'],
            'url' => $this->ajaxConversion ? Url::to([$this->_module->convertAction]) : '',
            'type' => $this->type,
            'saveFormat' => $this->saveFormat,
            'dispFormat' => $this->displayFormat,
            'saveTimezone' => $this->saveTimezone,
            'dispTimezone' => $this->displayTimezone,
            'asyncRequest' => $this->asyncRequest
        ], $pluginOptions);
        $this->registerPlugin($this->_pluginName);
        if ($this->isWidget() && !empty($this->options[$this->_dataVar])) {
            $this->options['options'][$this->_dataVar] = $this->options[$this->_dataVar];
            unset($this->options[$this->_dataVar]);
        }
    }
}