Esempio n. 1
0
/**
 * 2016-03-09
 * Портировал из РСМ.
 * @param int|string|null|bool|StoreInterface $store [optional]
 * @return string|null
 */
function df_domain($store = null)
{
    return dfcf(function ($store = null) {
        /** @var string $result */
        $store = df_store($store);
        /** @var string|null $baseUrl */
        // Может вернуть null, если в БД отсутствует значение соответствующей опции.
        $baseUrl = $store->getBaseUrl();
        if ($baseUrl) {
            try {
                $result = df_zuri($baseUrl)->getHost();
                df_assert_string_not_empty($result);
            } catch (Exception $e) {
            }
        }
        if (!$result) {
            /** @var \Zend_View_Helper_ServerUrl $helper */
            $helper = new \Zend_View_Helper_ServerUrl();
            /** @var string|null $result */
            // Может вернуть null, если Magento запущена с командной строки (
            // например, планировщиком задач)
            $result = $helper->getHost();
        }
        return $result;
    }, func_get_args());
}
Esempio n. 2
0
 /**
  * 2016-08-27
  * @param Method $method
  * @return array(string, array(string => mixed))
  */
 public static final function p(Method $method)
 {
     /** @var self $i */
     $i = df_create(df_con($method, 'Charge'), [self::$P__METHOD => $method]);
     /**
      * 2016-08-29
      * Метод @uses \Df\Payment\R\ICharge::requestIdKey(),
      * но мы вызываем его нестатично (чтобы он был вызван для нужного класса, а не бля базового),
      * и это успешно работает безо всяких предупреждений интерпретатора:
      * https://3v4l.org/N2VD2
      * http://stackoverflow.com/a/32746909
      * http://stackoverflow.com/a/15756165
      * Некоторые утверждают, что якобы на старых версиях PHP
      * это может выдавать предупреждение уровня E_STRICT:
      * http://stackoverflow.com/a/12874405
      * Однако это неправда, я проверил: https://3v4l.org/1JY8i
      */
     /** @var string $id */
     $id = $i->requestId();
     df_assert_string_not_empty($id);
     /** @var array(string => mixed) $p */
     $p = [$i->requestIdKey() => $id] + $i->params();
     return [$id, $p + [$i->signatureKey() => Signer::signRequest($i, $p)]];
 }
Esempio n. 3
0
/**
 * 2016-07-04
 * «How to programmatically get the base currency's ISO code for a store?» https://mage2.pro/t/1841
 * @param null|string|int|ScopeA|Store|ConfigData|IConfigData|O|Q $scope [optional]
 * @return Currency
 */
function df_currency_base($scope = null)
{
    if ($scope instanceof O || $scope instanceof Q) {
        $scope = $scope->getStore();
    }
    /** @var string $code */
    $code = df_cfg(Currency::XML_PATH_CURRENCY_BASE, $scope);
    df_assert_string_not_empty($code);
    return df_currency($code);
}
Esempio n. 4
0
/**
 * Возвращает неиспользуемое имя файла в заданной папке $directory по заданному шаблону $template.
 * Результатом всегда является непустая строка.
 * @param string $directory
 * @param string $template
 * @param string $ds [optional]
 * @return string
 */
function df_file_name($directory, $template, $ds = '-')
{
    // 2016-11-09
    // Отныне $template может содержать файловый путь:
    // в этом случае этот файловый путь убираем из $template и добавляем к $directory.
    $directory = df_path_n($directory);
    $template = df_path_n($template);
    if (df_contains($template, '/')) {
        /** @var string $templateA */
        $templateA = explode('/', $template);
        $template = array_pop($templateA);
        $directory = df_cc_path($directory, $templateA);
    }
    /** @var string $result */
    /** @var int $counter */
    $counter = 1;
    /** @var bool $hasOrderingPosition */
    $hasOrderingPosition = df_contains($template, '{ordering}');
    /** @var \Zend_Date $now */
    $now = \Zend_Date::now()->setTimezone('Europe/Moscow');
    /** @var array(string => string) */
    $vars = df_map_k(function ($k, $v) use($ds, $now) {
        return df_dts($now, implode($ds, $v));
    }, ['date' => ['y', 'MM', 'dd'], 'time' => ['HH', 'mm'], 'time-full' => ['HH', 'mm', 'ss']]);
    /**
    * 2016-11-09
    * @see \Zend_Date неправильно работает с миллисекундами:
    * всегда возвращает 0 вместо реального количества миллисекунд.
    * Так происходит из-за дефекта в методах
    * @see \Zend_Date::addMilliSecond()
    * @see \Zend_Date::setMilliSecond()
    * Там такой код:
    			list($milli, $time) = explode(" ", microtime());
    			$milli = intval($milli);
    * https://github.com/OpenMage/magento-mirror/blob/1.9.3.0/lib/Zend/Date.php#L4490-L4491
    * Этот код ошибочен, потому что после первой операции
    * $milli содержит дробное значение меньше 1, например: 0.653...
    * А вторая операция тупо делает из этого значения 0.
    */
    $vars['time-full-ms'] = implode($ds, [$vars['time-full'], sprintf('%02d', round(100 * df_first(explode(' ', microtime()))))]);
    while (true) {
        /** @var string $fileName */
        $fileName = df_var($template, ['ordering' => sprintf('%03d', $counter)] + $vars);
        /** @var string $fileFullPath */
        $fileFullPath = $directory . DS . $fileName;
        if (!file_exists($fileFullPath)) {
            /**
             * Раньше здесь стояло file_put_contents,
             * и иногда почему-то возникал сбой:
             * failed to open stream: No such file or directory.
             * Может быть, такой сбой возникает, если папка не существует?
             */
            $result = $fileFullPath;
            break;
        } else {
            if ($counter > 999) {
                df_error("Счётчик достиг предела ({$counter}).");
            } else {
                $counter++;
                /**
                 * Если в шаблоне имени файла
                 * нет переменной «{ordering}» — значит, надо добавить её,
                 * чтобы в следующей интерации имя файла стало уникальным.
                 * Вставляем «{ordering}» непосредственно перед расширением файла.
                 * Например, rm.shipping.log преобразуем в rm.shipping-{ordering}.log
                 */
                if (!$hasOrderingPosition && 2 === $counter) {
                    /** @var string[] $fileNameTemplateExploded */
                    $fileNameTemplateExploded = explode('.', $template);
                    /** @var int $secondFromLastPartIndex*/
                    $secondFromLastPartIndex = max(0, count($fileNameTemplateExploded) - 2);
                    /** @var string $secondFromLastPart */
                    $secondFromLastPart = dfa($fileNameTemplateExploded, $secondFromLastPartIndex);
                    df_assert_string_not_empty($secondFromLastPart);
                    $fileNameTemplateExploded[$secondFromLastPartIndex] = implode('--', [$secondFromLastPart, '{ordering}']);
                    /** @var string $newFileNameTemplate */
                    $newFileNameTemplate = implode('.', $fileNameTemplateExploded);
                    df_assert_ne($template, $newFileNameTemplate);
                    $template = $newFileNameTemplate;
                }
            }
        }
    }
    return df_path_n($result);
}