4cc901a9eaed6e0a53841d97610579a49a14dce3
[yaffs-website] / vendor / chi-teck / drupal-code-generator / templates / d8 / hook / file_url_alter.twig
1 /**
2  * Implements hook_file_url_alter().
3  */
4 function {{ machine_name }}_file_url_alter(&$uri) {
5   $user = \Drupal::currentUser();
6
7   // User 1 will always see the local file in this example.
8   if ($user->id() == 1) {
9     return;
10   }
11
12   $cdn1 = 'http://cdn1.example.com';
13   $cdn2 = 'http://cdn2.example.com';
14   $cdn_extensions = ['css', 'js', 'gif', 'jpg', 'jpeg', 'png'];
15
16   // Most CDNs don't support private file transfers without a lot of hassle,
17   // so don't support this in the common case.
18   $schemes = ['public'];
19
20   $scheme = file_uri_scheme($uri);
21
22   // Only serve shipped files and public created files from the CDN.
23   if (!$scheme || in_array($scheme, $schemes)) {
24     // Shipped files.
25     if (!$scheme) {
26       $path = $uri;
27     }
28     // Public created files.
29     else {
30       $wrapper = \Drupal::service('stream_wrapper_manager')->getViaScheme($scheme);
31       $path = $wrapper->getDirectoryPath() . '/' . file_uri_target($uri);
32     }
33
34     // Clean up Windows paths.
35     $path = str_replace('\\', '/', $path);
36
37     // Serve files with one of the CDN extensions from CDN 1, all others from
38     // CDN 2.
39     $pathinfo = pathinfo($path);
40     if (isset($pathinfo['extension']) && in_array($pathinfo['extension'], $cdn_extensions)) {
41       $uri = $cdn1 . '/' . $path;
42     }
43     else {
44       $uri = $cdn2 . '/' . $path;
45     }
46   }
47 }