optimize example


    }

    // Allow modules and themes to alter the CSS assets.     $this->moduleHandler->alter('css', $css$assets$language);
    $this->themeManager->alter('css', $css$assets$language);

    // Sort CSS items, so that they appear in the correct order.     uasort($css[static::class, 'sort']);

    if ($optimize) {
      $css = \Drupal::service('asset.css.collection_optimizer')->optimize($css$libraries_to_load$language);
    }
    $this->cache->set($cid$css, CacheBackendInterface::CACHE_PERMANENT, ['library_info']);

    return $css;
  }

  /** * Returns the JavaScript settings assets for this response's libraries. * * Gathers all drupalSettings from all libraries in the attached assets * collection and merges them. * * @param \Drupal\Core\Asset\AttachedAssetsInterface $assets * The assets attached to the current response. * * @return array * A (possibly optimized) collection of JavaScript assets. */
->willReturnCallback(function D$css) {
        $this->dumperData = $css;
      });
    $mock_state = $this->createMock(StateInterface::class);
    $mock_file_system = $this->createMock(FileSystemInterface::class);
    $this->optimizer = new CssCollectionOptimizer($mock_grouper$mock_optimizer$mock_dumper$mock_state$mock_file_system);
    $gpl_license = [
      'name' => 'GNU-GPL-2.0-or-later',
      'url' => 'https://www.drupal.org/licensing/faq',
      'gpl-compatible' => TRUE,
    ];
    $this->optimizer->optimize([
      'core/modules/system/tests/modules/common_test/common_test_css_import.css' => [
        'type' => 'file',
        'data' => 'core/modules/system/tests/modules/common_test/common_test_css_import.css',
        'preprocess' => TRUE,
        'license' => $gpl_license,
      ],
      'core/modules/system/tests/modules/common_test/common_test_css_import_not_preprocessed.css' => [
        'type' => 'file',
        'data' => 'core/modules/system/tests/modules/common_test/common_test_css_import.css',
        'preprocess' => TRUE,
        'license' => $gpl_license,
      ],
$progressBar->advance();
                    continue;
                }

                $progressBar->setMessage($item['path'], 'filename');

                if ($output->getVerbosity() === OutputInterface::VERBOSITY_VERBOSE) {
                    $output->writeln(' - ' . $item['path']);
                }

                try {
                    $optimizerService->optimize($item['path']);
                } catch (FileNotFoundException $exception) {
                    $output->writeln(' => ' . $exception->getMessage());
                } catch (OptimizerNotFoundException $exception) {
                    // Empty catch intended since no optimizer is available                 } catch (FileExistsException $exception) {
                    $output->writeln(' => ' . $exception->getMessage());
                }

                $progressBar->advance();
            }
        }
    }
public function __construct(OptimizerServiceInterface $optimizerService)
    {
        $this->optimizerService = $optimizerService;
    }

    /** * {@inheritdoc} */
    public function optimize($filepath)
    {
        $this->optimizerService->optimize($filepath);
    }

    /** * {@inheritdoc} */
    public function getOptimizers()
    {
        return $this->optimizerService->getOptimizers();
    }

    /** * {@inheritdoc} */
public function optimizeGroup(array $group): string {
    // Optimize each asset within the group.     $data = '';
    $current_license = FALSE;
    foreach ($group['items'] as $css_asset) {
      // Ensure license information is available as a comment after       // optimization.       if ($css_asset['license'] !== $current_license) {
        $data .= "/* @license " . $css_asset['license']['name'] . " " . $css_asset['license']['url'] . " */\n";
      }
      $current_license = $css_asset['license'];
      $data .= $this->optimizer->optimize($css_asset);
    }
    // Per the W3C specification at     // http://www.w3.org/TR/REC-CSS2/cascade.html#at-import, @import rules must     // precede any other style, so we move those to the top. The regular     // expression is expressed in NOWDOC since it is detecting backslashes as     // well as single and double quotes. It is difficult to read when     // represented as a quoted string.     $regexp = <<<'REGEXP' /@import\s*(?:'(?:\\'|.)*'|"(?:\\"|.)*"|url\(\s*(?:\\[\)\'\"]|[^'")])*\s*\)|url\(\s*'(?:\'|.)*'\s*\)|url\(\s*"(?:\"|.)*"\s*\)).*;/iU REGEXP;
    preg_match_all($regexp$data$matches);
    
// Ensure license information is available as a comment after                 // optimization.                 if ($js_asset['license'] !== $current_license) {
                  $data .= "/* @license " . $js_asset['license']['name'] . " " . $js_asset['license']['url'] . " */\n";
                }
                $current_license = $js_asset['license'];
                // Optimize this JS file, but only if it's not yet minified.                 if (isset($js_asset['minified']) && $js_asset['minified']) {
                  $data .= file_get_contents($js_asset['data']);
                }
                else {
                  $data .= $this->optimizer->optimize($js_asset);
                }
                // Append a ';' and a newline after each JS file to prevent them                 // from running together.                 $data .= ";\n";
              }
              // Remove unwanted JS code that cause issues.               $data = $this->optimizer->clean($data);
              // Dump the optimized JS for this group into an aggregate file.               $uri = $this->dumper->dump($data, 'js');
              // Set the URI for this group's aggregate file.               $js_assets[$order]['data'] = $uri;
              

        ob_end_clean();

        $this->mediaService->write($destination$content);
    }

    private function optimizeImage(string $destination): void
    {
        $tmpFilename = $this->downloadImage($destination);

        try {
            $this->optimizerService->optimize($tmpFilename);
            $this->uploadImage($destination$tmpFilename);
        } catch (OptimizerNotFoundException $exception) {
            // empty catch intended since no optimizer is available         } finally {
            unlink($tmpFilename);
        }
    }

    private function downloadImage(string $destination): string
    {
        $tmpFilename = tempnam(sys_get_temp_dir(), 'optimize_image');
        
$this->mediaService = $mediaService;
        $this->filesystem = $filesystem ? $filesystem : new Filesystem(new Local(sys_get_temp_dir()));
    }

    /** * {@inheritdoc} */
    public function optimize($filepath)
    {
        // If the file is on the local filesystem we can optimize it directly         if ($this->mediaService->getAdapterType() === 'local') {
            $this->optimizerService->optimize($filepath);

            return;
        }

        // Generate unique temporary file name         $tempFileName = uniqid('CdnOptimizerTemp-', true);

        $mediaServiceAdapter = $this->mediaService->getFilesystem();

        try {
            // Load file from remote filesystem, optimize it and upload it back again.
        file_get_contents($path . 'syntax_error.js'),
      ],
    ];
  }

  /** * Tests cleaning of a JS asset group containing 'type' => 'file'. * * @dataProvider providerTestOptimize */
  public function testOptimize($js_asset$expected) {
    $this->assertEquals($expected$this->optimizer->optimize($js_asset));
  }

}
// Ensure license information is available as a comment after       // optimization.       if ($js_asset['license'] !== $current_license) {
        $data .= "/* @license " . $js_asset['license']['name'] . " " . $js_asset['license']['url'] . " */\n";
      }
      $current_license = $js_asset['license'];
      // Optimize this JS file, but only if it's not yet minified.       if (isset($js_asset['minified']) && $js_asset['minified']) {
        $data .= file_get_contents($js_asset['data']);
      }
      else {
        $data .= $this->optimizer->optimize($js_asset);
      }
      // Append a ';' and a newline after each JS file to prevent them from       // running together.       $data .= ";\n";
    }
    // Remove unwanted JS code that causes issues.     return $this->optimizer->clean($data);
  }

}
if (empty($uri) || !file_exists($uri)) {
              // Optimize each asset within the group.               $data = '';
              $current_license = FALSE;
              foreach ($css_group['items'] as $css_asset) {
                // Ensure license information is available as a comment after                 // optimization.                 if ($css_asset['license'] !== $current_license) {
                  $data .= "/* @license " . $css_asset['license']['name'] . " " . $css_asset['license']['url'] . " */\n";
                }
                $current_license = $css_asset['license'];
                $data .= $this->optimizer->optimize($css_asset);
              }
              // Per the W3C specification at               // http://www.w3.org/TR/REC-CSS2/cascade.html#at-import, @import               // rules must precede any other style, so we move those to the               // top. The regular expression is expressed in NOWDOC since it is               // detecting backslashes as well as single and double quotes. It               // is difficult to read when represented as a quoted string.               $regexp = <<<'REGEXP' /@import\s*(?:'(?:\\'|.)*'|"(?:\\"|.)*"|url\(\s*(?:\\[\)\'\"]|[^'")])*\s*\)|url\(\s*'(?:\'|.)*'\s*\)|url\(\s*"(?:\"|.)*"\s*\)).*;/iU REGEXP;
              preg_match_all($regexp$data$matches);
              

  public function testOptimize($css_asset$expected) {
    global $base_path;
    $original_base_path = $base_path;
    $base_path = '/';

    // \Drupal\Core\Asset\CssOptimizer::loadFile() relies on the current working     // directory being the one that is used when index.php is the entry point.     // Note: PHPUnit automatically restores the original working directory.     chdir(realpath(__DIR__ . '/../../../../../../'));

    $this->assertEquals($expected$this->optimizer->optimize($css_asset), 'Group of file CSS assets optimized correctly.');

    $base_path = $original_base_path;
  }

  /** * Tests a file CSS asset with preprocessing disabled. */
  public function testTypeFilePreprocessingDisabled() {
    $this->expectException('Exception');
    $this->expectExceptionMessage('Only file CSS assets with preprocessing enabled can be optimized.');

    
Home | Imprint | This part of the site doesn't use cookies.