Completed
Pull Request — master (#601)
by
unknown
02:29
created

DocumentGenerator::prefixWithSpaces()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 12
rs 9.4285
cc 3
eloc 6
nc 3
nop 1
1
<?php
2
3
/*
4
 * This file is part of the ONGR package.
5
 *
6
 * (c) NFQ Technologies UAB <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace ONGR\ElasticsearchBundle\Generator;
13
14
/**
15
 * Document Generator
16
 */
17
class DocumentGenerator
18
{
19
    /**
20
     * @var string
21
     */
22
    private $spaces = '    ';
23
24
    /**
25
     * @var string
26
     */
27
    private $getMethodTemplate =
0 ignored issues
show
Unused Code introduced by
The property $getMethodTemplate is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
28
        '/**
29
 * <description>
30
 *
31
 * @return string
32
 */
33
public function <methodName>()
34
{
35
<spaces>return $this-><fieldName>;
36
}';
37
38
    /**
39
     * @var string
40
     */
41
    private $setMethodTemplate =
0 ignored issues
show
Unused Code introduced by
The property $setMethodTemplate is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
42
        '/**
43
 * <description>
44
 *
45
 * @param string $<variableName>
46
 */
47
public function <methodName>($<variableName>)
48
{
49
<spaces>$this-><fieldName> = $<variableName>;
50
}';
51
52
    /**
53
     * @param array $metadata
54
     *
55
     * @return string
56
     */
57
    public function generateDocumentClass(array $metadata)
58
    {
59
        $lines[] = "<?php\n";
0 ignored issues
show
Coding Style Comprehensibility introduced by
$lines was never initialized. Although not strictly required by PHP, it is generally a good practice to add $lines = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
60
        $lines[] = sprintf('namespace %s;', substr($metadata['name'], 0, strrpos($metadata['name'], '\\'))) . "\n";
61
        $lines[] = "use ONGR\\ElasticsearchBundle\\Annotation as ES;\n";
62
        $lines[] = $this->generateDocumentDocBlock($metadata);
63
        $lines[] = 'class ' . $this->getClassName($metadata);
64
        $lines[] = "{";
65
        $lines[] = str_replace('<spaces>', $this->spaces, $this->generateDocumentBody($metadata));
66
        $lines[] = "}\n";
67
68
        return implode("\n", $lines);
69
    }
70
71
    /**
72
     * Generates document body
73
     *
74
     * @param array $metadata
75
     *
76
     * @return string
77
     */
78
    private function generateDocumentBody(array $metadata)
79
    {
80
        $lines = [];
81
82
        if ($properties = $this->generateDocumentProperties($metadata)) {
83
            $lines[] = $properties;
84
        }
85
86
        if ($methods = $this->generateDocumentMethods($metadata)) {
87
            $lines[] = $methods;
88
        }
89
90
        return rtrim(implode("\n", $lines));
91
    }
92
93
    /**
94
     * Generates document properties
95
     *
96
     * @param array $metadata
97
     *
98
     * @return string
99
     */
100 View Code Duplication
    private function generateDocumentProperties(array $metadata)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
101
    {
102
        $lines = [];
103
104
        foreach ($metadata['properties'] as $property) {
105
            $lines[] = $this->generatePropertyDocBlock($property);
106
            $lines[] = $this->spaces . 'private $' . $property['field_name'] . ";\n";
107
        }
108
109
        return implode("\n", $lines);
110
    }
111
112
    /**
113
     * Generates document methods
114
     *
115
     * @param array $metadata
116
     *
117
     * @return string
118
     */
119 View Code Duplication
    private function generateDocumentMethods(array $metadata)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
120
    {
121
        $lines = [];
122
123
        foreach ($metadata['properties'] as $property) {
124
            $lines[] = $this->generateDocumentMethod($property, 'set') . "\n";
125
            $lines[] = $this->generateDocumentMethod($property, 'get') . "\n";
126
        }
127
128
        return implode("\n", $lines);
129
    }
130
131
    /**
132
     * Generates document method
133
     *
134
     * @param array  $metadata
135
     * @param string $type
136
     *
137
     * @return string
138
     */
139
    private function generateDocumentMethod(array $metadata, $type)
140
    {
141
        $replacements = [
142
            '<description>' => ucfirst($type) . ' ' . $metadata['field_name'],
143
            '<variableName>'      => $metadata['field_name'],
144
            '<methodName>'        => $type . ucfirst($metadata['field_name']),
145
            '<fieldName>'         => $metadata['field_name'],
146
        ];
147
148
        return $this->prefixWithSpaces(
149
            str_replace(
150
                array_keys($replacements),
151
                array_values($replacements),
152
                $this->{$type . 'MethodTemplate'}
153
            )
154
        );
155
    }
156
157
    /**
158
     * Returns property doc block
159
     *
160
     * @param array $metadata
161
     *
162
     * @return string
163
     */
164
    private function generatePropertyDocBlock(array $metadata)
165
    {
166
        $lines[] = $this->spaces . '/**';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$lines was never initialized. Although not strictly required by PHP, it is generally a good practice to add $lines = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
167
        $lines[] = $this->spaces . ' * @var string';
168
        $lines[] = $this->spaces . ' *';
169
170
        $column = [];
171
        if (isset($metadata['property_name']) && $metadata['property_name'] != $metadata['field_name']) {
172
            $column[] = 'name="' . $metadata['property_name'] . '"';
173
        }
174
175
        if (isset($metadata['property_class'])) {
176
            $column[] = 'class="' . $metadata['property_class'] . '"';
177
        }
178
179
        if (isset($metadata['property_multiple']) && $metadata['property_multiple']) {
180
            $column[] = 'multiple=true';
181
        }
182
183
        if (isset($metadata['property_type']) && $metadata['annotation'] == 'Property') {
184
            $column[] = 'type="' . $metadata['property_type'] . '"';
185
        }
186
187
        if (isset($metadata['property_default'])) {
188
            $column[] = 'default="' . $metadata['property_default'] . '"';
189
        }
190
191
        if (isset($metadata['property_options'])  && $metadata['property_options']) {
192
            $column[] = 'options={' . $metadata['property_options'] . '}';
193
        }
194
195
        $lines[] = $this->spaces . ' * @ES\\' . $metadata['annotation'] . '('
196
            . implode(', ', $column) . ')';
197
198
        $lines[] = $this->spaces . ' */';
199
200
        return implode("\n", $lines);
201
    }
202
203
    /**
204
     * Generates document doc block
205
     *
206
     * @param array $metadata
207
     *
208
     * @return string
209
     */
210
    private function generateDocumentDocBlock(array $metadata)
211
    {
212
        $lines[] = '/**';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$lines was never initialized. Although not strictly required by PHP, it is generally a good practice to add $lines = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
213
        $lines[] = ' * ' . $this->getClassName($metadata);
214
215
        $lines[] = ' *';
216
217
        $lines[] = sprintf(
218
            ' * @ES\%s(%s)',
219
            $metadata['annotation'],
220
            $metadata['type'] != lcfirst($this->getClassName($metadata))
221
                ? sprintf('type="%s"', $metadata['type']) : ''
222
        );
223
224
        $lines[] = ' */';
225
226
        return implode("\n", $lines);
227
    }
228
229
    /**
230
     * @param string $code
231
     *
232
     * @return string
233
     */
234
    private function prefixWithSpaces($code)
235
    {
236
        $lines = explode("\n", $code);
237
238
        foreach ($lines as $key => $value) {
239
            if ($value) {
240
                $lines[$key] = $this->spaces . $lines[$key];
241
            }
242
        }
243
244
        return implode("\n", $lines);
245
    }
246
247
    /**
248
     * Returns class name
249
     *
250
     * @param array $metadata
251
     *
252
     * @return string
253
     */
254
    private function getClassName(array $metadata)
255
    {
256
        return ($pos = strrpos($metadata['name'], '\\'))
257
            ? substr($metadata['name'], $pos + 1, strlen($metadata['name'])) : $metadata['name'];
258
    }
259
}
260