Example #1
0
/**
 * Переводит дату из одного строкового формата в другой
 * @param string $dateInSourceFormat
 * @param string $sourceFormat
 * @param string $resultFormat
 * @param bool $canBeEmpty [optional]
 * @return string
 */
function df_dtss($dateInSourceFormat, $sourceFormat, $resultFormat, $canBeEmpty = false)
{
    /** @var string $result */
    $result = '';
    if (!$dateInSourceFormat) {
        df_assert($canBeEmpty, 'Пустая дата недопустима.');
    } else {
        $result = df_dts(new ZD($dateInSourceFormat, $sourceFormat), $resultFormat);
    }
    return $result;
}
Example #2
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);
}