Completed
Push — 8.x-1.x ( aafe99...a92205 )
by Philipp
07:57 queued 04:05
created

Loader::listComponents()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
nc 5
nop 1
dl 0
loc 16
rs 9.4222
c 0
b 0
f 0
1
<?php
2
3
namespace Drupal\graphql_twig\Template\Loader;
4
5
use Drupal\Core\Cache\CacheBackendInterface;
6
use Drupal\Core\Theme\ThemeManagerInterface;
7
8
/**
9
 * Filesystem loader that will search for fractal component shortnames.
10
 */
11
class Loader extends \Twig_Loader_Filesystem {
12
13
  /**
14
   * @var \Drupal\Core\Theme\ThemeManagerInterface
15
   */
16
  protected $themeManager;
17
18
  /**
19
   * Static component lookup cache.
20
   *
21
   * @var array
22
   */
23
  protected $components = null;
24
25
  /**
26
   * @var \Drupal\Core\Cache\CacheBackendInterface
27
   */
28
  protected $cacheBackend;
29
30
  /**
31
   * @var array
32
   */
33
  protected $twigConfig;
34
35
  public function __construct(
36
    ThemeManagerInterface $themeManager,
37
    array $twigConfig,
38
    CacheBackendInterface $cacheBackend,
39
    $paths = [],
40
    ?string $rootPath = NULL
41
  ) {
42
    parent::__construct($paths, $rootPath);
43
    $this->cacheBackend = $cacheBackend;
44
    $this->twigConfig = $twigConfig;
45
    $this->themeManager = $themeManager;
46
  }
47
48
  /**
49
   * List all components found within a specific path.
50
   *
51
   * @param string $path
52
   *   The directory to scan for
53
   *
54
   * @return string[]
55
   *   Map of component filenames keyed by component handle.
56
   */
57
  protected function listComponents($path) {
58
    if ($this->twigConfig['cache'] && $cache = $this->cacheBackend->get($path)) {
59
      return $cache->data;
60
    }
61
62
    foreach (file_scan_directory($path, '/.*\.twig/') as $file) {
63
      $this->components[$file->name] = $file->uri;
64
    }
65
66
    if ($this->twigConfig['cache']) {
67
      $this->cacheBackend->set($path, $this->components);
68
    }
69
70
    return $this->components;
71
72
  }
73
74
  /**
75
   * {@inheritdoc}
76
   */
77
  protected function findTemplate($name) {
78
    if (is_null($this->components)) {
79
      // Scan the directory for any twig files and register them.
80
      // TODO: inherit components from base theme
81
      // TODO: configurable components directory
82
      $this->components = $this->listComponents($this->themeManager->getActiveTheme()->getPath() . '/components');
83
    }
84
85
    if ($name[0] === '#') {
86
      $component = substr($name, 1);
87
      if (array_key_exists($component, $this->components)) {
88
        return $this->components[$component];
89
      }
90
    }
91
92
    return FALSE;
93
  }
94
95
}
96