YamlDiscovery.php 2.14 KB
Newer Older
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
<?php

/**
 * @file
 * Contains \Drupal\Component\Discovery\YamlDiscovery.
 */

namespace Drupal\Component\Discovery;

use Symfony\Component\Yaml\Parser;

/**
 * Provides discovery for YAML files within a given set of directories.
 */
class YamlDiscovery implements DiscoverableInterface {

  /**
   * The base filename to look for in each directory.
   *
   * @var string
   */
  protected $name;

  /**
   * An array of directories to scan.
   *
   * @var array
   */
  protected $directories = array();

  /**
   * The symfony YAML parser.
   *
   * @var \Symfony\Component\Yaml\Parser
   */
  protected $parser;

  /**
   * Constructs a YamlDiscovery object.
   *
   * @param string $name
   *   The
   * @param array $directories
   *   An array of directories to scan. If an associative array is provided the
   *   return array will use these keys.
   */
  public function __construct($name, array $directories) {
    $this->name = $name;
    $this->directories = $directories;
  }

  /**
   * {@inheritdoc}
   */
  public function findAll() {
    $all = array();
    $parser = $this->parser();

    foreach ($this->findFiles() as $key => $file) {
      $all[$key] = $parser->parse(file_get_contents($file));
    }

    return $all;
  }

  /**
   * Returns the YAML parse.
   *
   * @return \Symfony\Component\Yaml\Parser
   *   The symfony YAML parser.
   */
  protected function parser() {
    if (!isset($this->parser)) {
      $this->parser = new Parser();
    }
    return $this->parser;
  }

  /**
   * Returns an array of file paths.
   *
   * @return array
   */
  protected function findFiles() {
    $files = array();
    foreach ($this->directories as $key => $directory) {
      $file = $directory . '/' . $this->fileBaseName($directory) . '.yml';
      if (file_exists($file)) {
        $files[$key] = $file;
      }
    }
    return $files;
  }

  /**
   * Returns the base filename for the current directory.
   *
   * @param string $directory
   *   The current directory path.
   *
   * @return string
   *   The file name, without the .yml extension.
   */
  protected function fileBaseName($directory) {
    return basename($directory) . '.' . $this->name;
  }

}