1<?php
2
3// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
4// See the LICENCE file in the repository root for full licence text.
5
6namespace App\Console\Commands;
7
8use App\Libraries\RouteScopesHelper;
9use Illuminate\Console\Command;
10
11class RouteConvert extends Command
12{
13 const FILE_OPTIONS = ['from-csv', 'from-json', 'to-csv', 'to-json'];
14
15 /**
16 * The name and signature of the console command.
17 *
18 * @var string
19 */
20 protected $signature = 'route:convert {--from-csv=} {--from-json=} {--to-csv=} {--to-json=}';
21
22 /**
23 * The console command description.
24 *
25 * @var string
26 */
27 protected $description = 'Dump existing api routes or convert route dump file.';
28
29 protected $options = [];
30
31 protected $routeScopesHelper;
32
33 /**
34 * Execute the console command.
35 *
36 * @return mixed
37 */
38 public function handle()
39 {
40 $this->readOptions();
41
42 $this->routeScopesHelper = new RouteScopesHelper();
43
44 $this->read();
45 $this->write();
46 }
47
48 protected function read()
49 {
50 if ($filename = $this->options['from-csv']) {
51 $this->routeScopesHelper->fromCsv($filename);
52 } elseif ($filename = $this->options['from-json']) {
53 $this->routeScopesHelper->fromJson($filename);
54 } else {
55 $this->routeScopesHelper->loadRoutes();
56 }
57 }
58
59 protected function readOptions()
60 {
61 foreach (static::FILE_OPTIONS as $name) {
62 $this->options[$name] = presence($this->option($name));
63 }
64 }
65
66 protected function write()
67 {
68 $written = false;
69
70 if ($filename = $this->options['to-csv']) {
71 $this->routeScopesHelper->toCsv($filename);
72 $written = true;
73 }
74
75 if ($filename = $this->options['to-json']) {
76 $this->routeScopesHelper->toJson($filename);
77 $written = true;
78 }
79
80 if (!$written) {
81 $this->line(json_encode($this->routeScopesHelper->toArray(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
82 }
83 }
84}