You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1.8 KiB

  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Console\VerifyJSON;
  4. use Illuminate\Console\Command;
  5. use Symfony\Component\Console\Command\Command as CommandAlias;
  6. class ValidateJsonFiles extends Command
  7. {
  8. use VerifyJSON;
  9. /**
  10. * The name and signature of the console command.
  11. *
  12. * @var string
  13. */
  14. protected $signature = 'import:validate-json-directory {directory : The directory with JSON files to validate}';
  15. /**
  16. * The console command description.
  17. *
  18. * @var string
  19. */
  20. protected $description = 'Recursively validate all JSON files in a directory. Stops after 100 files.';
  21. /**
  22. * Execute the console command.
  23. */
  24. public function handle(): int
  25. {
  26. $directory = (string)$this->argument('directory');
  27. if (!is_dir($directory) || !is_readable($directory)) {
  28. $this->error(sprintf('Cannot read directory %s.', $directory));
  29. return CommandAlias::FAILURE;
  30. }
  31. // check each file in the directory and see if it needs action.
  32. // collect recursively:
  33. $it = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($directory, \RecursiveDirectoryIterator::SKIP_DOTS));
  34. $Regex = new \RegexIterator($it, '/^.+\.json$/i', \RecursiveRegexIterator::GET_MATCH);
  35. $fullPaths = [];
  36. foreach ($Regex as $item) {
  37. $path = $item[0];
  38. $fullPaths[] = $path;
  39. }
  40. foreach ($fullPaths as $file) {
  41. $result = $this->verifyJSON($file);
  42. if (false === $result) {
  43. $this->error(sprintf('File "%s" is not valid JSON.', $file));
  44. return CommandAlias::FAILURE;
  45. }
  46. $this->info(sprintf('File "%s" is valid JSON.', $file));
  47. }
  48. return CommandAlias::SUCCESS;
  49. }
  50. }