Filesystem.php 12.9 KB
Newer Older
Ketan's avatar
Ketan committed
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
<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Magento\Deploy\Model;

use Symfony\Component\Console\Output\OutputInterface;
use Magento\Framework\App\State;
use Magento\Framework\App\DeploymentConfig\Writer;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Validator\Locale;
use Magento\User\Model\ResourceModel\User\Collection as UserCollection;

/**
 * Generate static files, compile
 *
 * Сlear generated/code, generated/metadata/, var/view_preprocessed and pub/static directories
 *
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class Filesystem
{
    /**
     * File access permissions
     *
     * @deprecated As magento2 doesn't control indirectly the access permissions to the files anymore.
     * Access permissions to the files are set during deploy Magento 2, directly after
     * uploading code of Magento. Also it is possible to specify the value
     * of inverse mask for setting access permissions to files generated by Magento.
     * @link https://devdocs.magento.com/guides/v2.0/install-gde/install/post-install-umask.html
     * @link https://devdocs.magento.com/guides/v2.0/install-gde/prereq/file-system-perms.html
     */
    const PERMISSIONS_FILE = 0640;

    /**
     * Directory access permissions
     *
     * @deprecated As magento2 doesn't control indirectly the access permissions to the directories anymore.
     * Access permissions to the directories are set during deploy Magento 2, directly after
     * uploading code of Magento. Also it is possible to specify the value
     * of inverse mask for setting access permissions to directories generated by Magento.
     * @link https://devdocs.magento.com/guides/v2.0/install-gde/install/post-install-umask.html
     * @link https://devdocs.magento.com/guides/v2.0/install-gde/prereq/file-system-perms.html
     */
    const PERMISSIONS_DIR = 0750;

    /**
     * Default theme when no theme is stored in configuration
     */
    const DEFAULT_THEME = 'Magento/blank';

    /**
     * @var \Magento\Framework\App\DeploymentConfig\Writer
     */
    private $writer;

    /**
     * @var \Magento\Framework\App\DeploymentConfig\Reader
     */
    private $reader;

    /**
     * @var \Magento\Framework\ObjectManagerInterface
     */
    private $objectManager;

    /**
     * @var \Magento\Framework\Filesystem
     */
    private $filesystem;

    /**
     * @var \Magento\Framework\App\Filesystem\DirectoryList
     */
    private $directoryList;

    /**
     * @var \Magento\Framework\Filesystem\Driver\File
     */
    private $driverFile;

    /**
     * @var \Magento\Store\Model\Config\StoreView
     */
    private $storeView;

    /**
     * @var \Magento\Framework\ShellInterface
     */
    private $shell;

    /**
     * @var string
     */
    private $functionCallPath;

    /**
     * @var UserCollection
     */
    private $userCollection;

    /**
     * @var Locale
     */
    private $locale;

    /**
     * @param \Magento\Framework\App\DeploymentConfig\Writer $writer
     * @param \Magento\Framework\App\DeploymentConfig\Reader $reader
     * @param \Magento\Framework\ObjectManagerInterface $objectManager
     * @param \Magento\Framework\Filesystem $filesystem
     * @param \Magento\Framework\App\Filesystem\DirectoryList $directoryList
     * @param \Magento\Framework\Filesystem\Driver\File $driverFile
     * @param \Magento\Store\Model\Config\StoreView $storeView
     * @param \Magento\Framework\ShellInterface $shell
     * @param UserCollection|null $userCollection
     * @param Locale|null $locale
     * @SuppressWarnings(PHPMD.ExcessiveParameterList)
     */
    public function __construct(
        \Magento\Framework\App\DeploymentConfig\Writer $writer,
        \Magento\Framework\App\DeploymentConfig\Reader $reader,
        \Magento\Framework\ObjectManagerInterface $objectManager,
        \Magento\Framework\Filesystem $filesystem,
        \Magento\Framework\App\Filesystem\DirectoryList $directoryList,
        \Magento\Framework\Filesystem\Driver\File $driverFile,
        \Magento\Store\Model\Config\StoreView $storeView,
        \Magento\Framework\ShellInterface $shell,
        UserCollection $userCollection = null,
        Locale $locale = null
    ) {
        $this->writer = $writer;
        $this->reader = $reader;
        $this->objectManager = $objectManager;
        $this->filesystem = $filesystem;
        $this->directoryList = $directoryList;
        $this->driverFile = $driverFile;
        $this->storeView = $storeView;
        $this->shell = $shell;
        $this->userCollection = $userCollection ?: $this->objectManager->get(UserCollection::class);
        $this->locale = $locale ?: $this->objectManager->get(Locale::class);
        $this->functionCallPath =
            PHP_BINARY . ' -f ' . BP . DIRECTORY_SEPARATOR . 'bin' . DIRECTORY_SEPARATOR . 'magento ';
    }

    /**
     * Regenerate static
     *
     * @param OutputInterface $output
     * @return void
     * @throws LocalizedException
     * @throws \Exception
     */
    public function regenerateStatic(
        OutputInterface $output
    ) {
        // Сlear generated/code, generated/metadata/, var/view_preprocessed and pub/static directories
        $this->cleanupFilesystem(
            [
                DirectoryList::CACHE,
                DirectoryList::GENERATED_CODE,
                DirectoryList::GENERATED_METADATA,
                DirectoryList::TMP_MATERIALIZATION_DIR,
                DirectoryList::STATIC_VIEW
            ]
        );

        $this->reinitCacheDirectories();
        // Trigger code generation
        $this->compile($output);

        $this->reinitCacheDirectories();
        // Trigger static assets compilation and deployment
        $this->deployStaticContent($output);
    }

    /**
     * Deploy static content
     *
     * @param OutputInterface $output
     * @return void
     * @throws \Exception
     */
    protected function deployStaticContent(
        OutputInterface $output
    ) {
        $output->writeln('Starting deployment of static content');
        $cmd = $this->functionCallPath . 'setup:static-content:deploy -f '
            . implode(' ', $this->getUsedLocales());

        /**
         * @todo eliminate exec
         */
        try {
            $execOutput = $this->shell->execute($cmd);
        } catch (LocalizedException $e) {
            $output->writeln('Something went wrong while deploying static content. See the error log for details.');
            throw $e;
        }
        $output->writeln($execOutput);
        $output->writeln('Deployment of static content complete');
    }

    /**
     * Get admin user locales
     *
     * @return array
     */
    private function getAdminUserInterfaceLocales()
    {
        $locales = [];
        foreach ($this->userCollection as $user) {
            $locales[] = $user->getInterfaceLocale();
        }
        return $locales;
    }

    /**
     * Get used store and admin user locales.
     *
     * @return array
     * @throws \InvalidArgumentException if unknown locale is provided by the store configuration
     * @throws \Magento\Framework\Exception\FileSystemException
     */
    private function getUsedLocales()
    {
        $usedLocales = array_merge(
            $this->storeView->retrieveLocales(),
            $this->getAdminUserInterfaceLocales()
        );

        return array_map(
            function ($locale) {
                if (!$this->locale->isValid($locale)) {
                    throw new \InvalidArgumentException(
                        $locale . ' argument has invalid value, run info:language:list for list of available locales'
                    );
                }

                return $locale;
            },
            array_unique($usedLocales)
        );
    }

    /**
     * Runs compiler
     *
     * @param OutputInterface $output
     * @return void
     * @throws LocalizedException
     */
    protected function compile(OutputInterface $output)
    {
        $output->writeln('Starting compilation');
        $cmd = $this->functionCallPath . 'setup:di:compile';

        /**
         * exec command is necessary for now to isolate the autoloaders in the compiler from the memory state
         * of this process, which would prevent some classes from being generated
         *
         * @todo eliminate exec
         */
        try {
            $execOutput = $this->shell->execute($cmd);
        } catch (LocalizedException $e) {
            $output->writeln('Something went wrong while compiling generated code. See the error log for details.');
            throw $e;
        }
        $output->writeln($execOutput);
        $output->writeln('Compilation complete');
    }

    /**
     * Deletes specified directories by code
     *
     * @param array $directoryCodeList
     * @return void
     * @throws \Magento\Framework\Exception\FileSystemException
     */
    public function cleanupFilesystem($directoryCodeList)
    {
        $excludePatterns = ['#.htaccess#', '#deployed_version.txt#'];
        foreach ($directoryCodeList as $code) {
            if ($code == DirectoryList::STATIC_VIEW) {
                $directoryPath = $this->directoryList->getPath(DirectoryList::STATIC_VIEW);
                if ($this->driverFile->isExists($directoryPath)) {
                    $files = $this->driverFile->readDirectory($directoryPath);
                    foreach ($files as $file) {
                        foreach ($excludePatterns as $pattern) {
                            if (preg_match($pattern, $file)) {
                                continue 2;
                            }
                        }
                        if ($this->driverFile->isFile($file)) {
                            $this->driverFile->deleteFile($file);
                        } else {
                            $this->driverFile->deleteDirectory($file);
                        }
                    }
                }
            } else {
                $this->filesystem->getDirectoryWrite($code)
                    ->delete();
            }
        }
    }

    /**
     * Changes permissions for directories by their code.
     *
     * @param array $directoryCodeList
     * @param int $dirPermissions
     * @param int $filePermissions
     * @return void
     * @deprecated 100.0.6 As magento2 doesn't control indirectly
     * the access permissions to the files and directories anymore.
     * Access permissions to the files and directories are set during deploy Magento 2, directly after
     * uploading code of Magento. Also it is possible to specify the value
     * of inverse mask for setting access permissions to files and directories generated by Magento.
     * @link https://devdocs.magento.com/guides/v2.0/install-gde/install/post-install-umask.html
     * @link https://devdocs.magento.com/guides/v2.0/install-gde/prereq/file-system-perms.html
     * @throws \Magento\Framework\Exception\FileSystemException
     */
    protected function changePermissions($directoryCodeList, $dirPermissions, $filePermissions)
    {
        foreach ($directoryCodeList as $code) {
            $directoryPath = $this->directoryList->getPath($code);
            if ($this->driverFile->isExists($directoryPath)) {
                $this->filesystem->getDirectoryWrite($code)
                    ->changePermissionsRecursively('', $dirPermissions, $filePermissions);
            } else {
                $this->driverFile->createDirectory($directoryPath, $dirPermissions);
            }
        }
    }

    /**
     * Change permissions on static resources
     *
     * @return void
     * @deprecated 100.0.6 As magento2 doesn't control indirectly the access permissions to the files
     * and directories anymore.
     * Access permissions to the files and directories are set during deploy Magento 2, directly after
     * uploading code of Magento. Also it is possible to specify the value
     * of inverse mask for setting access permissions to files and directories generated by Magento.
     * @link https://devdocs.magento.com/guides/v2.0/install-gde/install/post-install-umask.html
     * @link https://devdocs.magento.com/guides/v2.0/install-gde/prereq/file-system-perms.html
     * @throws \Magento\Framework\Exception\FileSystemException
     */
    public function lockStaticResources()
    {
        // Lock /generated/code, /generated/metadata/ and /var/view_preprocessed directories
        $this->changePermissions(
            [
                DirectoryList::GENERATED_CODE,
                DirectoryList::GENERATED_METADATA,
                DirectoryList::TMP_MATERIALIZATION_DIR,
            ],
            self::PERMISSIONS_DIR,
            self::PERMISSIONS_FILE
        );
    }

    /**
     * Flush cache and restore the basic cache directories.
     *
     * @throws LocalizedException
     */
    private function reinitCacheDirectories()
    {
        $command = $this->functionCallPath . 'cache:flush';
        $this->shell->execute($command);
    }
}