1+ <?php
2+
3+ declare (strict_types=1 );
4+
5+ namespace PhpKafka \AvscJsonConverter \Command ;
6+
7+ use PhpKafka \AvscJsonConverter \Avro \Avro ;
8+ use PhpKafka \AvscJsonConverter \Converter \ConverterInterface ;
9+ use Symfony \Component \Console \Command \Command ;
10+ use Symfony \Component \Console \Input \InputArgument ;
11+ use Symfony \Component \Console \Input \InputInterface ;
12+ use Symfony \Component \Console \Input \InputOption ;
13+ use Symfony \Component \Console \Output \OutputInterface ;
14+
15+ class ConvertSingleAvscToJsonCommand extends Command
16+ {
17+ private ConverterInterface $ converter ;
18+
19+ public function __construct (ConverterInterface $ converter , string $ name = null )
20+ {
21+ $ this ->converter = $ converter ;
22+ parent ::__construct ($ name );
23+ }
24+
25+ protected function configure (): void
26+ {
27+ $ this
28+ ->setName ('convert:single-avsc-to-json ' )
29+ ->setDescription ('Convert avsc schema to json schema ' )
30+ ->addArgument ('avscSchema ' , InputArgument::REQUIRED , 'Avsc schema file path ' )
31+ ->addArgument ('jsonSchema ' , InputArgument::REQUIRED , 'Json schema file path ' )
32+ ->addOption ('noDefaultAsRequired ' , null , InputOption::VALUE_NONE , 'Instead of all fields, only fields with no default are required ' )
33+ ;
34+ }
35+
36+ public function execute (InputInterface $ input , OutputInterface $ output ): ?int
37+ {
38+ /** @var string $avscSchema */
39+ $ avscSchema = $ input ->getArgument ('avscSchema ' );
40+
41+ /** @var string $jsonSchema */
42+ $ jsonSchema = $ input ->getArgument ('jsonSchema ' );
43+ $ outputDirectory = dirname ($ jsonSchema );
44+
45+ $ noDefaultAsRequired = (bool ) $ input ->getOption ('noDefaultAsRequired ' );
46+
47+ if (Avro::FILE_EXTENSION !== pathinfo ($ avscSchema , PATHINFO_EXTENSION )) {
48+ $ output ->writeln ('<error>Input schema is not of type avsc</error> ' );
49+ return -1 ;
50+ }
51+
52+ $ avsc = file_get_contents ($ avscSchema );
53+ $ json = $ this ->converter ->convert ($ avsc , ['markNoDefaultAsRequired ' => $ noDefaultAsRequired ]);
54+
55+ if (false === file_exists ($ outputDirectory )) {
56+ mkdir ($ outputDirectory );
57+ }
58+
59+ $ fname = $ outputDirectory . DIRECTORY_SEPARATOR . $ jsonSchema ;
60+ file_put_contents ($ fname , $ json );
61+
62+ $ output ->writeln ('Successfully converted avsc schema ' );
63+
64+ return 0 ;
65+ }
66+ }
0 commit comments