YamlLinter.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. $errors = $errors + static::lintBlueprints();
  20. return $errors;
  21. }
  22. public static function lintPages()
  23. {
  24. return static::recurseFolder('page://');
  25. }
  26. public static function lintConfig()
  27. {
  28. return static::recurseFolder('config://');
  29. }
  30. public static function lintBlueprints()
  31. {
  32. /** @var UniformResourceLocator $locator */
  33. $locator = Grav::instance()['locator'];
  34. $current_theme = Grav::instance()['config']->get('system.pages.theme');
  35. $theme_path = 'themes://' . $current_theme . '/blueprints';
  36. $locator->addPath('blueprints', '', [$theme_path]);
  37. return static::recurseFolder('blueprints://');
  38. }
  39. public static function recurseFolder($path, $extensions = 'md|yaml')
  40. {
  41. $lint_errors = [];
  42. /** @var UniformResourceLocator $locator */
  43. $locator = Grav::instance()['locator'];
  44. $flags = \RecursiveDirectoryIterator::SKIP_DOTS;
  45. if ($locator->isStream($path)) {
  46. $directory = $locator->getRecursiveIterator($path, $flags);
  47. } else {
  48. $directory = new \RecursiveDirectoryIterator($path, $flags);
  49. }
  50. $recursive = new \RecursiveIteratorIterator($directory, \RecursiveIteratorIterator::SELF_FIRST);
  51. $iterator = new \RegexIterator($recursive, '/^.+\.'.$extensions.'$/i');
  52. /** @var \RecursiveDirectoryIterator $file */
  53. foreach ($iterator as $filepath => $file) {
  54. try {
  55. Yaml::parse(static::extractYaml($filepath));
  56. } catch (\Exception $e) {
  57. $lint_errors[str_replace(GRAV_ROOT, '', $filepath)] = $e->getMessage();
  58. }
  59. }
  60. return $lint_errors;
  61. }
  62. protected static function extractYaml($path)
  63. {
  64. $extension = pathinfo($path, PATHINFO_EXTENSION);
  65. if ($extension === 'md') {
  66. $file = MarkdownFile::instance($path);
  67. $contents = $file->frontmatter();
  68. } else {
  69. $contents = file_get_contents($path);
  70. }
  71. return $contents;
  72. }
  73. }