Team Ai
Apppublic

errorcode418/php

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
Converter.php98 linesDownload Raw Back to Util
1<?php2/**3 * ua-parser4 *5 * Copyright (c) 2011-2012 Dave Olsen, http://dmolsen.com6 *7 * Released under the MIT license8 */9namespace UAParser\Util;10 11use Symfony\Component\Filesystem\Filesystem;12use Symfony\Component\Yaml\Yaml;13use UAParser\Exception\FileNotFoundException;14 15class Converter16{17    /** @var string */18    private $destination;19 20    /** @var Filesystem */21    private $fs;22 23    /**24     * @param string $destination25     * @param Filesystem $fs26     */27    public function __construct($destination, Filesystem $fs = null)28    {29        $this->destination = $destination;30        $this->fs = $fs ? $fs : new Filesystem();31    }32 33    /**34     * @param string $yamlFile35     * @param bool $backupBeforeOverride36     * @throws FileNotFoundException37     */38    public function convertFile($yamlFile, $backupBeforeOverride = true)39    {40        if (!$this->fs->exists($yamlFile)) {41            throw FileNotFoundException::fileNotFound($yamlFile);42        }43 44        $this->doConvert(Yaml::parse(file_get_contents($yamlFile)), $backupBeforeOverride);45    }46 47    /**48     * @param string $yamlString49     * @param bool $backupBeforeOverride50     */51    public function convertString($yamlString, $backupBeforeOverride = true)52    {53        $this->doConvert(Yaml::parse($yamlString), $backupBeforeOverride);54    }55 56    /**57     * @param array $regexes58     * @param bool $backupBeforeOverride59     */60    protected function doConvert(array $regexes, $backupBeforeOverride = true)61    {62        $regexes = $this->sanitizeRegexes($regexes);63        $data = "<?php\nreturn " . preg_replace('/\s+$/m', '', var_export($regexes, true)) . ';';64 65        $regexesFile = $this->destination . '/regexes.php';66        if ($backupBeforeOverride && $this->fs->exists($regexesFile)) {67 68            $currentHash = hash('sha512', file_get_contents($regexesFile));69            $futureHash = hash('sha512', $data);70 71            if ($futureHash === $currentHash) {72                return;73            }74 75            $backupFile = $this->destination . '/regexes-' . $currentHash . '.php';76            $this->fs->copy($regexesFile, $backupFile);77        }78 79        $this->fs->dumpFile($regexesFile, $data);80    }81 82    private function sanitizeRegexes(array $regexes)83    {84        foreach ($regexes as $groupName => $group) {85            $regexes[$groupName] = array_map(array($this, 'sanitizeRegex'), $group);86        }87 88        return $regexes;89    }90 91    private function sanitizeRegex(array $regex)92    {93        $regex['regex'] = str_replace('@', '\@', $regex['regex']);94 95        return $regex;96    }97}98