<commit_before><?php

namespace Oro\Bundle\TranslationBundle\Provider;

use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;

use Symfony\Component\Finder\Finder;

class TranslationServiceProvider
{
    const FILE_NAME_SUFFIX      = '.zip';
    const DEFAULT_SOURCE_LOCALE = 'en';

    /** @var AbstractAPIAdapter */
    protected $adapter;

    /** @var JsTranslationDumper */
    protected $jsTranslationDumper;

    /** @var NullLogger */
    protected $logger;

    /** @var string */
    protected $rootDir;

    /**
     * @param AbstractAPIAdapter  $adapter
     * @param JsTranslationDumper $jsTranslationDumper
     * @param string              $rootDir
     */
    public function __construct(
        AbstractAPIAdapter $adapter,
        JsTranslationDumper $jsTranslationDumper,
        $rootDir
    ) {
        $this->adapter             = $adapter;
        $this->jsTranslationDumper = $jsTranslationDumper;
        $this->rootDir             = $rootDir;

        $this->setLogger(new NullLogger());
    }

    /**
     * Loop through the generated files in $dir and merge them with downloaded in $targetDir
     * merge generated files over downloaded and upload result back to remote
     *
     * @param string $dir
     *
     * @return mixed
     */
    public function update($dir)
    {
        $targetDir  = $this->getTmpDir('oro-trans');
        $pathToSave = $targetDir . DIRECTORY_SEPARATOR . 'update';
        $targetDir  = $targetDir . DIRECTORY_SEPARATOR . self::DEFAULT_SOURCE_LOCALE . DIRECTORY_SEPARATOR;

        $isDownloaded = $this->download($pathToSave, [], self::DEFAULT_SOURCE_LOCALE, false);
        if (!$isDownloaded) {
            return false;
        }

        $finder = Finder::create()->files()->name('*.yml')->in($dir);
        foreach ($finder->files() as $fileInfo) {
            $localContents = file($fileInfo);
            $remoteFile    = $targetDir . $fileInfo->getRelativePathname();

            if (file_exists($remoteFile)) {
                $remoteContents = file($remoteFile);
                array_shift($remoteContents); // remove dashes from the beginning of file
            } else {
                $remoteContents = [];
            }

            $content = array_unique(array_merge($remoteContents, $localContents));
            $content = implode('', $content);

            $remoteDir = dirname($remoteFile);
            if (!is_dir($remoteDir)) {
                mkdir($remoteDir, 0777, true);
            }
            file_put_contents($remoteFile, $content);
        }

        $result = $this->upload($targetDir, 'update');
        $this->cleanup($targetDir);

        return $result;
    }

    /**
     * Upload translations
     *
     * @param string $dir
     * @param string $mode
     *
     * @return mixed
     */
    public function upload($dir, $mode = 'add')
    {
        $finder = Finder::create()->files()->name('*.yml')->in($dir);

        /** $file \SplFileInfo */
        $files = array();
        foreach ($finder->files() as $file) {
            // crowdin understand only "/" as directory separator :)
            $apiPath         = str_replace(array($dir, DIRECTORY_SEPARATOR), array('', '/'), (string)$file);
            $files[$apiPath] = (string)$file;
        }

        return $this->adapter->upload($files, $mode);
    }

    /**
     * @param string      $pathToSave path to save translations
     * @param array       $projects   project names
     * @param null|string $locale
     * @param bool        $toApply    whether apply download packs or not
     *
     * @throws \RuntimeException
     * @return bool
     */
    public function download($pathToSave, array $projects, $locale = null, $toApply = true)
    {
        $pathToSave = $pathToSave . self::FILE_NAME_SUFFIX;
        $targetDir  = dirname($pathToSave);
        $this->cleanup($targetDir);

        $isDownloaded = $this->adapter->download($pathToSave, $projects, $locale);
        try {
            $isExtracted = $this->unzip(
                $pathToSave,
                is_null($locale) ? $targetDir : rtrim($targetDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $locale
            );
        } catch (\RuntimeException $e) {
            // try to check possible error messages in file
            if ($e->getCode() === \ZipArchive::ER_NOZIP) {
                $this->adapter->parseResponse(file_get_contents($pathToSave));
            }

            throw $e;
        }

        // TODO: consider move this in crowdin adapter or remove
        if ($locale == 'en') {
            // check and fix exported file names, replace $locale_XX locale in file names to $locale
            $this->renameFiles('.en_US.', '.en.', $targetDir);
        }

        if ($isExtracted) {
            unlink($pathToSave);
        }

        if ($toApply && $isExtracted) {
            //$applyDir = $this->getTmpDir('trans_');
            $appliedLocales = $this->apply(
                $this->rootDir . DIRECTORY_SEPARATOR . 'Resources' . DIRECTORY_SEPARATOR,
                //$applyDir,
                $targetDir
            );

            //$this->dumpToDb($applyDir);
            if ($appliedLocales) {
                $this->cleanup($targetDir);
                $this->jsTranslationDumper->dumpTranslations($appliedLocales);
            }
        }
<commit_msg>BAP-2735: Proxymanager    - code style fixes<commit_after><?php

namespace Oro\Bundle\TranslationBundle\Provider;

use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;

use Symfony\Component\Finder\Finder;

class TranslationServiceProvider
{
    const FILE_NAME_SUFFIX      = '.zip';
    const DEFAULT_SOURCE_LOCALE = 'en';

    /** @var AbstractAPIAdapter */
    protected $adapter;

    /** @var JsTranslationDumper */
    protected $jsTranslationDumper;

    /** @var NullLogger */
    protected $logger;

    /** @var string */
    protected $rootDir;

    /**
     * @param AbstractAPIAdapter  $adapter
     * @param JsTranslationDumper $jsTranslationDumper
     * @param string              $rootDir
     */
    public function __construct(
        AbstractAPIAdapter $adapter,
        JsTranslationDumper $jsTranslationDumper,
        $rootDir
    ) {
        $this->adapter             = $adapter;
        $this->jsTranslationDumper = $jsTranslationDumper;
        $this->rootDir             = $rootDir;

        $this->setLogger(new NullLogger());
    }

    /**
     * Loop through the generated files in $dir and merge them with downloaded in $targetDir
     * merge generated files over downloaded and upload result back to remote
     *
     * @param string $dir
     *
     * @return mixed
     */
    public function update($dir)
    {
        $targetDir  = $this->getTmpDir('oro-trans');
        $pathToSave = $targetDir . DIRECTORY_SEPARATOR . 'update';
        $targetDir  = $targetDir . DIRECTORY_SEPARATOR . self::DEFAULT_SOURCE_LOCALE . DIRECTORY_SEPARATOR;

        $isDownloaded = $this->download($pathToSave, [], self::DEFAULT_SOURCE_LOCALE, false);
        if (!$isDownloaded) {
            return false;
        }

        $finder = Finder::create()->files()->name('*.yml')->in($dir);
        foreach ($finder->files() as $fileInfo) {
            $localContents = file($fileInfo);
            $remoteFile    = $targetDir . $fileInfo->getRelativePathname();

            if (file_exists($remoteFile)) {
                $remoteContents = file($remoteFile);
                array_shift($remoteContents); // remove dashes from the beginning of file
            } else {
                $remoteContents = [];
            }

            $content = array_unique(array_merge($remoteContents, $localContents));
            $content = implode('', $content);

            $remoteDir = dirname($remoteFile);
            if (!is_dir($remoteDir)) {
                mkdir($remoteDir, 0777, true);
            }
            file_put_contents($remoteFile, $content);
        }

        $result = $this->upload($targetDir, 'update');
        $this->cleanup($targetDir);

        return $result;
    }

    /**
     * Upload translations
     *
     * @param string $dir
     * @param string $mode
     *
     * @return mixed
     */
    public function upload($dir, $mode = 'add')
    {
        $finder = Finder::create()->files()->name('*.yml')->in($dir);

        /** $file \SplFileInfo */
        $files = array();
        foreach ($finder->files() as $file) {
            // crowdin understand only "/" as directory separator :)
            $apiPath         = str_replace(array($dir, DIRECTORY_SEPARATOR), array('', '/'), (string)$file);
            $files[$apiPath] = (string)$file;
        }

        return $this->adapter->upload($files, $mode);
    }

    /**
     * @param string      $pathToSave path to save translations
     * @param array       $projects   project names
     * @param null|string $locale
     * @param bool        $toApply    whether apply download packs or not
     *
     * @throws \RuntimeException
     * @return bool
     */
    public function download($pathToSave, array $projects, $locale = null, $toApply = true)
    {
        $pathToSave = $pathToSave . self::FILE_NAME_SUFFIX;
        $targetDir  = dirname($pathToSave);
        $this->cleanup($targetDir);

        $isDownloaded = $this->adapter->download($pathToSave, $projects, $locale);
        try {
            $isExtracted = $this->unzip(
                $pathToSave,
                is_null($locale) ? $targetDir : rtrim($targetDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $locale
            );
        } catch (\RuntimeException $e) {
            // try to check possible error messages in file
            if ($e->getCode() === \ZipArchive::ER_NOZIP) {
                $this->adapter->parseResponse(file_get_contents($pathToSave));
            }

            throw $e;
        }

        // TODO: consider move this in crowdin adapter or remove
        if ($locale == 'en') {
            // check and fix exported file names, replace $locale_XX locale in file names to $locale
            $this->renameFiles('.en_US.', '.en.', $targetDir);
        }

        if ($isExtracted) {
            unlink($pathToSave);
        }

        if ($toApply && $isExtracted) {
            $appliedLocales = $this->apply(
                $this->rootDir . DIRECTORY_SEPARATOR . 'Resources' . DIRECTORY_SEPARATOR,
                $targetDir
            );

            if ($appliedLocales) {
                $this->cleanup($targetDir);
                $this->jsTranslationDumper->dumpTranslations($appliedLocales);
            }
        }

{'fraction_non_alphanumeric': 0.12887963663890992, 'fraction_numerical': 0.0011355034065102195, 'mean_word_length': 2.0353245261344055, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 69, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 18, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7061226', 'n_tokens_mistral': 3019, 'n_tokens_neox': 2890, 'n_words': 642}