InfoParser.php 1.87 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Contains Drupal\Core\Extension\InfoParser.
 */

namespace Drupal\Core\Extension;

10 11
use Drupal\Component\Serialization\Yaml;
use Drupal\Component\Serialization\Exception\InvalidDataTypeException;
12 13 14
use Drupal\Component\Utility\String;

/**
15
 * Parses extension .info.yml files.
16 17 18 19 20 21 22 23
 */
class InfoParser implements InfoParserInterface {

  /**
   * Array of all info keyed by filename.
   *
   * @var array
   */
24
  protected static $parsedInfos = array();
25 26 27 28 29

  /**
   * {@inheritdoc}
   */
  public function parse($filename) {
30
    if (!isset(static::$parsedInfos[$filename])) {
31
      if (!file_exists($filename)) {
32
        static::$parsedInfos[$filename] = array();
33 34 35
      }
      else {
        try {
36
          static::$parsedInfos[$filename] = Yaml::decode(file_get_contents($filename));
37
        }
38 39 40
        catch (InvalidDataTypeException $e) {
          $message = String::format("Unable to parse !file: !error", array('!file' => $filename, '!error' => $e->getMessage()));
          throw new InfoParserException($message);
41
        }
42
        $missing_keys = array_diff($this->getRequiredKeys(), array_keys(static::$parsedInfos[$filename]));
43
        if (!empty($missing_keys)) {
44
          $message = String::format('Missing required keys (!missing_keys) in !file.', array('!missing_keys' => implode(', ', $missing_keys), '!file' => $filename));
45
          throw new InfoParserException($message);
46
        }
47 48
        if (isset(static::$parsedInfos[$filename]['version']) && static::$parsedInfos[$filename]['version'] === 'VERSION') {
          static::$parsedInfos[$filename]['version'] = \Drupal::VERSION;
49 50 51
        }
      }
    }
52
    return static::$parsedInfos[$filename];
53 54 55 56 57 58 59 60 61
  }

  /**
   * Returns an array of keys required to exist in .info.yml file.
   *
   * @return array
   *   An array of required keys.
   */
  protected function getRequiredKeys() {
62
    return array('type', 'core', 'name');
63 64 65
  }

}