YamlLinter.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. /**
  3. * @package Grav\Common\Helpers
  4. *
  5. * @copyright Copyright (C) 2015 - 2019 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Common\Helpers;
  9. use Grav\Common\Grav;
  10. use RocketTheme\Toolbox\File\MarkdownFile;
  11. use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
  12. use Symfony\Component\Yaml\Yaml;
  13. class YamlLinter
  14. {
  15. public static function lint()
  16. {
  17. $errors = static::lintConfig();
  18. $errors = $errors + static::lintPages();
  19. return $errors;
  20. }
  21. public static function lintPages()
  22. {
  23. return static::recurseFolder('page://');
  24. }
  25. public static function lintConfig()
  26. {
  27. return static::recurseFolder('config://');
  28. }
  29. public static function recurseFolder($path, $extensions = 'md|yaml')
  30. {
  31. $lint_errors = [];
  32. /** @var UniformResourceLocator $locator */
  33. $locator = Grav::instance()['locator'];
  34. $flags = \RecursiveDirectoryIterator::SKIP_DOTS;
  35. if ($locator->isStream($path)) {
  36. $directory = $locator->getRecursiveIterator($path, $flags);
  37. } else {
  38. $directory = new \RecursiveDirectoryIterator($path, $flags);
  39. }
  40. $recursive = new \RecursiveIteratorIterator($directory, \RecursiveIteratorIterator::SELF_FIRST);
  41. $iterator = new \RegexIterator($recursive, '/^.+\.'.$extensions.'$/i');
  42. /** @var \RecursiveDirectoryIterator $file */
  43. foreach ($iterator as $filepath => $file) {
  44. try {
  45. Yaml::parse(static::extractYaml($filepath));
  46. } catch (\Exception $e) {
  47. $lint_errors[str_replace(GRAV_ROOT, '', $filepath)] = $e->getMessage();
  48. }
  49. }
  50. return $lint_errors;
  51. }
  52. protected static function extractYaml($path)
  53. {
  54. $extension = pathinfo($path, PATHINFO_EXTENSION);
  55. if ($extension === 'md') {
  56. $file = MarkdownFile::instance($path);
  57. $contents = $file->frontmatter();
  58. } else {
  59. $contents = file_get_contents($path);
  60. }
  61. return $contents;
  62. }
  63. }