component_library-1.0.x-dev/src/Asset.php

src/Asset.php
<?php

declare(strict_types=1);

namespace Drupal\component_library;

use Drupal\Core\Cache\Cache;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Asset\LibraryDiscoveryInterface;
use Drupal\component_library\Entity\ComponentLibraryAsset;

/**
 * Asset file handler service.
 */
class Asset {

  public function __construct(
    protected FileSystemInterface $fileSystem,
    protected LibraryDiscoveryInterface $libraryDiscovery,
    protected ConfigFactoryInterface $configFactory,
  ) {}

  /**
   * Generate library files.
   *
   * Writes the asset files to the public files dir.
   *
   * @param \Drupal\component_library\Entity\ComponentLibraryAsset $asset
   *   The asset that needs files generated.
   */
  public function generateLibraryFiles(ComponentLibraryAsset $asset) {
    foreach ($asset->getFiles(TRUE) as $file) {
      $directory = \dirname($file['path']);
      $this->fileSystem->prepareDirectory($directory, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS);
      $this->fileSystem->saveData(
        $file['code'],
        $file['path'],
        FileSystemInterface::EXISTS_REPLACE
      );
    }
    $this->libraryDiscovery->clearCachedDefinitions();
  }

  /**
   * Clear files.
   *
   * Deletes existing asset files with or without aggregation enabled.
   *
   * @param \Drupal\component_library\Entity\ComponentLibraryAsset $asset
   *   The component_library_asset to clean up files for.
   */
  public function clearFiles(ComponentLibraryAsset $asset): void {
    Cache::invalidateTags(['library_info']);
    foreach (['js', 'css'] as $asset_type) {
      $aggregation_enabled = $this->configFactory->get('system.performance')->get("$asset_type.preprocess");
      if ($aggregation_enabled) {
        $this->fileSystem->deleteRecursive('public://' . $asset_type . '/');
      }
    }
    $path = 'public://component_library_assets/' . $asset->id();
    $this->fileSystem->deleteRecursive($path);
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc