GenericWriter::__construct()   B
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 27
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 27
rs 8.439
c 0
b 0
f 0
cc 5
eloc 15
nc 5
nop 5
1
<?php
2
//[PHPCOMPRESSOR(remove,start)]
3
/**
4
 * Created by Vitaly Iegorov <[email protected]>.
5
 * on 25.03.16 at 12:04
6
 */
7
namespace samsoncms\api\generator;
8
9
use samsonframework\orm\DatabaseInterface;
10
use samsonphp\generator\Generator;
11
12
/**
13
 * Generator classes file writer.
14
 *
15
 * @package samsoncms\api\generator
16
 */
17
class GenericWriter
18
{
19
    /** @var \samsoncms\api\generator\analyzer\GenericAnalyzer[string] Collection of entity analyzers */
20
    protected $analyzers = [];
21
22
    /** @var \samsoncms\api\generator\Generic[string] Collection of entity generators */
23
    protected $generators = [];
24
25
    /** @var array Analyzers metadata */
26
    protected $metadata = [];
27
28
    /** @var Generator Code generator */
29
    protected $codeGenerator;
30
31
    /** @var string Path to generated entities */
32
    protected $path;
33
34
    /**
35
     * Writer constructor.
36
     *
37
     * @param DatabaseInterface $db
38
     * @param Generator         $codeGenerator
39
     * @param string            $namespace
40
     * @param array             $analyzers Collection of analyzer class names
41
     * @param string            $path Path to generated entities
42
     *
43
     * @throws \Exception
44
     */
45
    public function __construct(DatabaseInterface $db, Generator $codeGenerator, $namespace, array $analyzers, $path)
46
    {
47
        $this->codeGenerator = $codeGenerator;
48
        $this->path = $path;
49
        $this->namespace = $namespace;
0 ignored issues
show
Bug introduced by
The property namespace does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
50
51
        // Create analyzer instances
52
        foreach ($analyzers as $analyzerClass => $generators) {
53
            if (class_exists($analyzerClass)) {
54
                $this->analyzers[$analyzerClass] = new $analyzerClass($db);
55
56
                // Analyze to get metadata
57
                $this->metadata[$analyzerClass] = $this->analyzers[$analyzerClass]->analyze();
58
59
                // Validate generator classes
60
                foreach ($generators as $generator) {
61
                    if (class_exists($generator)) {
62
                        $this->generators[$analyzerClass][] = $generator;
63
                    } else {
64
                        throw new \Exception('Entity generator class[' . $generator . '] not found');
65
                    }
66
                }
67
            } else {
68
                throw new \Exception('Entity analyzer class['.$analyzerClass.'] not found');
69
            }
70
        }
71
    }
72
73
    /**
74
     * Analyze, generate and write class files.
75
     */
76
    public function write()
77
    {
78
        // Create module cache folder if not exists
79
        if (!file_exists($this->path)) {
80
            @mkdir($this->path, 0777, true);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
81
        }
82
83 View Code Duplication
        foreach ($this->analyzers as $analyzerClass => $analyzer) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
84
            // Analyze database structure and get entities metadata
85
            foreach ($this->metadata[$analyzerClass] as $metadata) {
86
                // Iterate all generators for analyzer
87
                foreach ($this->generators[$analyzerClass] as $generator) {
88
                    // TODO: Optimize generators creation by searching for existing files
89
                    /** @var Generic $generator Create class generator */
90
                    $generator = new $generator($this->codeGenerator->defNamespace($this->namespace), $metadata);
91
92
                    // Create entity generated class names
93
                    $file = $this->path . $generator->className . '.php';
94
95
                    // Do not generate file if its already there
96
                    //if (!file_exists($file)) {
97
                        // Create entity query class files
98
                        file_put_contents($file, '<?php' . $generator->generate());
99
                    //}
100
101
                    // Require files
102
                    require($file);
103
                }
104
            }
105
        }
106
    }
107
}
108
//[PHPCOMPRESSOR(remove,end)]
109