1+ <?php
2+
3+ namespace TimeHunter \LaravelJsonToClassGenerator \Services ;
4+
5+
6+ use Illuminate \Support \Facades \File ;
7+ use Nette \PhpGenerator \PhpFile ;
8+
9+ /**
10+ * Class JsonToClassGenerator
11+ * @package TimeHunter\LaravelJsonToClassGenerator\Services
12+ */
13+ abstract class AbstractClassGenerator
14+ {
15+ /**
16+ * @return array
17+ */
18+ abstract protected function getData (): array ;
19+
20+ /**
21+ * Generate classes
22+ */
23+ public function generate ()
24+ {
25+ $ this ->recursiveCreateFile ($ this ->getData (), config ('jsontoclassgenerator.namespace ' ));
26+ }
27+
28+ /**
29+ * @param $sample
30+ * @param $namespaceString
31+ */
32+ private function recursiveCreateFile ($ sample , $ namespaceString )
33+ {
34+ foreach ($ sample as $ key => $ data ) {
35+ $ className = $ this ->convertClassName ($ key );
36+ $ phpFile = new PhpFile ();
37+ $ namespace = $ phpFile ->addNamespace ($ namespaceString );
38+ $ class = $ namespace ->addClass ($ className );
39+
40+ $ toArray = "return [ \n" ;
41+ foreach ($ data as $ itemKey => $ item ) {
42+ $ camelCase = $ this ->convert ($ itemKey );
43+ $ class ->addProperty ($ camelCase );
44+ if (is_array ($ item )) {
45+
46+ $ subClassName = $ this ->convertClassName ($ itemKey );
47+
48+ $ toArray .= " ' $ itemKey' => " . 'collect($this-> ' . $ camelCase . ')->map(function ( ' . "$ subClassName " . ' $data){
49+ return $data->toArray();
50+ })->toArray() ' . ', ' . "\n" ;
51+ $ this ->recursiveCreateFile ([$ itemKey => $ item ], $ namespaceString );
52+ } else {
53+ $ toArray .= " ' $ itemKey' => " . '$this-> ' . $ camelCase . ', ' . "\n" ;
54+ }
55+ }
56+ $ toArray .= "]; " ;
57+ $ class ->addMethod ('toArray ' )->setReturnType ('array ' )->setBody ($ toArray ); // method return type;
58+
59+ $ file = $ className . '.php ' ;
60+
61+ $ location = config ('jsontoclassgenerator.file_location ' ) . '/ ' . $ file ;
62+ File::put ($ location , $ phpFile );
63+ }
64+ }
65+
66+ /**
67+ * @param $string
68+ * @return string
69+ */
70+ private function convert ($ string )
71+ {
72+ $ str = str_replace (' ' , '' , ucwords (str_replace ('_ ' , ' ' , $ string )));
73+
74+ return lcfirst ($ str );
75+ }
76+
77+ /**
78+ * @param $string
79+ * @return mixed
80+ */
81+ private function convertClassName ($ string )
82+ {
83+ $ str = str_replace (' ' , '' , ucwords (str_replace ('_ ' , ' ' , $ string )));
84+
85+ return $ str ;
86+ }
87+ }
0 commit comments