ValidateCommand.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Composer\Command;
  12. use Symfony\Component\Console\Input\InputInterface;
  13. use Symfony\Component\Console\Input\InputArgument;
  14. use Symfony\Component\Console\Output\OutputInterface;
  15. use Composer\Json\JsonFile;
  16. use Composer\Json\JsonValidationException;
  17. /**
  18. * @author Robert Schönthal <seroscho@googlemail.com>
  19. * @author Jordi Boggiano <j.boggiano@seld.be>
  20. */
  21. class ValidateCommand extends Command
  22. {
  23. protected function configure()
  24. {
  25. $this
  26. ->setName('validate')
  27. ->setDescription('Validates a composer.json')
  28. ->setDefinition(array(
  29. new InputArgument('file', InputArgument::OPTIONAL, 'path to composer.json file', './composer.json')
  30. ))
  31. ->setHelp(<<<EOT
  32. The validate command validates a given composer.json
  33. EOT
  34. )
  35. ;
  36. }
  37. protected function execute(InputInterface $input, OutputInterface $output)
  38. {
  39. $file = $input->getArgument('file');
  40. if (!file_exists($file)) {
  41. $output->writeln('<error>'.$file.' not found.</error>');
  42. return 1;
  43. }
  44. if (!is_readable($file)) {
  45. $output->writeln('<error>'.$file.' is not readable.</error>');
  46. return 1;
  47. }
  48. $laxValid = false;
  49. try {
  50. $json = new JsonFile($file);
  51. $json->read();
  52. $json->validateSchema(JsonFile::LAX_SCHEMA);
  53. $laxValid = true;
  54. $json->validateSchema();
  55. } catch (JsonValidationException $e) {
  56. if ($laxValid) {
  57. $output->writeln('<info>'.$file.' is valid for simple usage with composer but has</info>');
  58. $output->writeln('<info>strict errors that make it unable to be published as a package:</info>');
  59. } else {
  60. $output->writeln('<error>'.$file.' is invalid, the following errors were found:</error>');
  61. }
  62. foreach ($e->getErrors() as $message) {
  63. $output->writeln('<error>'.$message.'</error>');
  64. }
  65. return 1;
  66. } catch (\Exception $e) {
  67. $output->writeln('<error>'.$file.' contains a JSON Syntax Error:</error>');
  68. $output->writeln('<error>'.$e->getMessage().'</error>');
  69. return 1;
  70. }
  71. $output->writeln('<info>'.$file.' is valid</info>');
  72. }
  73. }