Completed
Push — 57-formatter-per-extension ( 73b3c8 )
by Nicolas
40:17 queued 36:16
created

Hydrator::setFormatterProvider()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 6
rs 9.4286
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
3
namespace Karma;
4
5
use Gaufrette\Filesystem;
6
use Psr\Log\NullLogger;
7
use Karma\FormatterProviders\NullProvider;
8
9
class Hydrator
10
{
11
    use \Karma\Logging\LoggerAware;
12
13
    const
14
        VARIABLE_REGEX = '~<%(?P<variableName>[A-Za-z0-9_\.]+)%>~';
15
    
16
    private
17
        $sources,
0 ignored issues
show
Coding Style introduced by
It is generally advisable to only define one property per statement.

Only declaring a single property per statement allows you to later on add doc comments more easily.

It is also recommended by PSR2, so it is a common style that many people expect.

Loading history...
18
        $suffix,
19
        $reader,
20
        $dryRun,
21
        $enableBackup,
22
        $finder,
23
        $formatterProvider,
24
        $currentFormatterName;
25
    
26
    public function __construct(Filesystem $sources, Configuration $reader, Finder $finder, FormatterProvider $formatterProvider = null)
27
    {
28
        $this->logger = new NullLogger();
29
        
30
        $this->sources = $sources;
31
        $this->reader = $reader;
32
        $this->finder = $finder;
33
        
34
        $this->suffix = Application::DEFAULT_DISTFILE_SUFFIX;
35
        $this->dryRun = false;
36
        $this->enableBackup = false;
37
        
38
        $this->formatterProvider = $formatterProvider;
39
        if($this->formatterProvider === null)
40
        {
41
            $this->formatterProvider = new NullProvider();
42
        }
43
        
44
        $this->currentFormatterName = null;
45
    }
46
47
    public function setSuffix($suffix)
48
    {
49
        $this->suffix = $suffix;
50
    
51
        return $this;
52
    }    
53
    
54
    public function setDryRun($value = true)
55
    {
56
        $this->dryRun = (bool) $value;
57
        
58
        return $this;
59
    }
60
    
61
    public function enableBackup($value = true)
62
    {
63
        $this->enableBackup = (bool) $value;
64
        
65
        return $this;
66
    }
67
    
68
    public function setFormatterProvider(FormatterProvider $formatterProvider)
69
    {
70
        $this->formatterProvider = $formatterProvider;
71
        
72
        return $this;
73
    }
74
    
75
    public function hydrate($environment)
76
    {
77
        $distFiles = $this->collectDistFiles();
78
        
79
        foreach($distFiles as $file)
80
        {
81
            $this->hydrateFile($file, $environment);
82
        }
83
        
84
        $this->info(sprintf(
85
           '%d files generated',
86
            count($distFiles)
87
        ));
88
    }
89
    
90
    private function collectDistFiles()
91
    {
92
        return $this->finder->findFiles("~$this->suffix$~");
93
    }
94
    
95
    private function hydrateFile($file, $environment)
96
    {
97
        $content = $this->sources->read($file);
98
        $content = $this->parseFileDirectives($file, $content);
99
        
100
        $targetContent = $this->injectValues($file, $content, $environment);
101
        
102
        $targetFile = substr($file, 0, strlen($this->suffix) * -1);
103
        $this->debug("Write $targetFile");
104
105
        if($this->dryRun === false)
106
        {
107
            $this->backupFile($targetFile);
108
            $this->sources->write($targetFile, $targetContent, true);
109
        }
110
    }
111
    
112
    private function parseFileDirectives($file, $fileContent)
113
    {
114
        $this->currentFormatterName = null;
115
        
116
        if($count = preg_match_all('~(<%\s*karma:formatter\s*=\s*(?P<formatterName>[^%]+)%>)~', $fileContent, $matches))
117
        {
118
            if($count !== 1)
119
            {
120
                throw new \RuntimeException(sprintf(
121
                    'Syntax error in %s : only one formatter directive is allowed (%d found)',
122
                    $file,
123
                    $count
124
                ));
125
            }
126
            
127
            $this->currentFormatterName = strtolower(trim($matches['formatterName'][0]));
128
        }   
129
130
        return $this->removeFileDirectives($fileContent);
131
    }
132
    
133
    private function removeFileDirectives($fileContent)
134
    {
135
        return preg_replace('~(<%\s*karma:[^%]*%>\s*)~', '', $fileContent);
136
    }
137
    
138
    private function injectValues($sourceFile, $content, $environment)
139
    {
140
        $replacementCounter = 0;
141
        
142
        $replacementCounter += $this->injectScalarValues($content, $environment);
143
        $replacementCounter += $this->injectListValues($content, $environment);
144
        
145
        if($replacementCounter === 0)
146
        {
147
            $this->warning("No variable found in $sourceFile");
148
        }
149
        
150
        return $content;
151
    }
152
    
153
    private function injectScalarValues(& $content, $environment)
154
    {
155
        $fileExtension = null; // FIXME
0 ignored issues
show
Coding Style introduced by
Comment refers to a FIXME task
Loading history...
156
        $formatter = $this->formatterProvider->getFormatter($fileExtension, $this->currentFormatterName);
157
        
158
        $content = preg_replace_callback(self::VARIABLE_REGEX, function(array $matches) use($environment, $formatter)
159
        {
160
            $value = $this->reader->read($matches['variableName'], $environment);
161
        
162
            if(is_array($value))
163
            {
164
                // don't replace lists at this time
165
                return $matches[0];
166
            }
167
        
168
            return $formatter->format($value);
169
        
170
        }, $content, -1, $count);
171
172
        return $count;
173
    }
174
    
175
    private function injectListValues(& $content, $environment)
176
    {
177
        $fileExtension = null; // FIXME
0 ignored issues
show
Coding Style introduced by
Comment refers to a FIXME task
Loading history...
178
        $formatter = $this->formatterProvider->getFormatter($fileExtension, $this->currentFormatterName);
179
        $replacementCounter = 0;
180
        
181
        $eol = $this->detectEol($content);
182
        
183
        while(preg_match(self::VARIABLE_REGEX, $content))
184
        {
185
            $lines = explode($eol, $content);
186
            $result = array();
187
            
188
            foreach($lines as $line)
189
            {
190
                if(preg_match(self::VARIABLE_REGEX, $line, $matches))
191
                {
192
                    $values = $this->reader->read($matches['variableName'], $environment);
193
                    
194
                    $replacementCounter++; 
195
                    foreach($values as $value)
196
                    {
197
                        $result[] = preg_replace(self::VARIABLE_REGEX, $formatter->format($value), $line, 1);
198
                    }
199
200
                    continue;
201
                }
202
203
                $result[] = $line;
204
            }
205
            
206
            $content = implode($eol, $result); 
207
        }
208
        
209
        return $replacementCounter; 
210
    }
211
    
212
    private function detectEol($content)
213
    {
214
        $types = array("\r\n", "\r", "\n");
215
        
216
        foreach($types as $type)
217
        {
218
            if(strpos($content, $type) !== false)
219
            {
220
                return $type;
221
            }
222
        }
223
        
224
        return "\n";
225
    }
226
    
227
    private function backupFile($targetFile)
228
    {
229 View Code Duplication
        if($this->enableBackup === true)
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...
230
        {
231
            if($this->sources->has($targetFile))
232
            {
233
                $backupFile = $targetFile . Application::BACKUP_SUFFIX;
234
                $this->sources->write($backupFile, $this->sources->read($targetFile), true);
0 ignored issues
show
Bug introduced by
It seems like $this->sources->read($targetFile) targeting Gaufrette\Filesystem::read() can also be of type boolean; however, Gaufrette\Filesystem::write() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
235
            }
236
        }
237
    }
238
    
239
    public function rollback()
240
    {
241
        $distFiles = $this->collectDistFiles();
242
    
243
        foreach($distFiles as $file)
244
        {
245
            $this->rollbackFile($file);
246
        }
247
    }
248
    
249
    private function rollbackFile($file)
250
    {
251
        $this->debug("- $file");
252
    
253
        $targetFile = substr($file, 0, strlen($this->suffix) * -1);
254
        $backupFile = $targetFile . Application::BACKUP_SUFFIX;
255
    
256 View Code Duplication
        if($this->sources->has($backupFile))
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...
257
        {
258
            $this->info("  Writing $targetFile");
259
    
260
            if($this->dryRun === false)
261
            {
262
                $backupContent = $this->sources->read($backupFile);
263
                $this->sources->write($targetFile, $backupContent, true);
0 ignored issues
show
Bug introduced by
It seems like $backupContent defined by $this->sources->read($backupFile) on line 262 can also be of type boolean; however, Gaufrette\Filesystem::write() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
264
            }
265
        }
266
    }
267
}