Completed
Push — master ( 004a61...1de1c7 )
by Guillaume
02:17
created

Compiler::compile()   B

Complexity

Conditions 4
Paths 8

Size

Total Lines 59
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 59
rs 8.9846
cc 4
eloc 43
nc 8
nop 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/*
4
 * This file is part of the hogosha-monitor package
5
 *
6
 * Copyright (c) 2016 Guillaume Cavana
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 *
11
 * Feel free to edit as you please, and have fun.
12
 *
13
 * @author Guillaume Cavana <[email protected]>
14
 */
15
16
namespace Hogosha\Monitor\Compiler;
17
18
use Symfony\Component\Finder\Finder;
19
use Symfony\Component\Process\Process;
20
21
/**
22
 * @author Guillaume Cavana <[email protected]>
23
 */
24
class Compiler
25
{
26
    protected $version;
27
28
    /**
29
     * Compile.
30
     */
31
    public function compile()
32
    {
33
        $pharFilePath = dirname(__FILE__).'/../../build/monitor.phar';
34
        if (file_exists($pharFilePath)) {
35
            unlink($pharFilePath);
36
        }
37
38
        $this->loadVersion();
39
40
        $phar = new \Phar($pharFilePath, 0, 'monitor.phar');
41
        $phar->setSignatureAlgorithm(\Phar::SHA1);
42
43
        $phar->startBuffering();
44
        $root = __DIR__.'/../..';
45
46
        $finder = new Finder();
47
        $finder->files()
48
            ->ignoreVCS(true)
49
            ->name('*.php')
50
            ->name('LICENSE')
51
            ->notName('Compiler.php')
52
            ->exclude('Tests')
53
            ->exclude('tests')
54
            ->exclude('docs')
55
            ->in($root.'/src')
56
            ->in($root.'/vendor/guzzlehttp')
57
            ->in($root.'/vendor/eljam')
58
            ->in($root.'/vendor/hogosha')
59
            ->in($root.'/vendor/webmozart')
60
            ->in($root.'/vendor/psr')
61
            ->in($root.'/vendor/guzzle')
62
            ->in($root.'/vendor/symfony')
63
        ;
64
65
        foreach ($finder as $file) {
66
            $this->addFile($phar, $file);
67
        }
68
69
        $this->addFile($phar, new \SplFileInfo($root.'/vendor/autoload.php'));
70
        $this->addFile($phar, new \SplFileInfo($root.'/vendor/composer/autoload_namespaces.php'));
71
        $this->addFile($phar, new \SplFileInfo($root.'/vendor/composer/autoload_psr4.php'));
72
        $this->addFile($phar, new \SplFileInfo($root.'/vendor/composer/autoload_classmap.php'));
73
        $this->addFile($phar, new \SplFileInfo($root.'/vendor/composer/autoload_files.php'));
74
        $this->addFile($phar, new \SplFileInfo($root.'/vendor/composer/autoload_real.php'));
75
76
        if (file_exists($root.'/vendor/composer/include_paths.php')) {
77
            $this->addFile($phar, new \SplFileInfo($root.'/vendor/composer/include_paths.php'));
78
        }
79
        $this->addFile($phar, new \SplFileInfo($root.'/vendor/composer/ClassLoader.php'));
80
81
        $binContent = file_get_contents($root.'/bin/monitor');
82
        $binContent = preg_replace('{^#!/usr/bin/env php\s*}', '', $binContent);
83
        $phar->addFromString('bin/monitor', $binContent);
84
85
        // Stubs
86
        $phar->setStub($this->getStub());
87
        $phar->stopBuffering();
88
        unset($phar);
89
    }
90
91
    protected function addFile(\Phar $phar, \SplFileInfo $file, $strip = true)
92
    {
93
        $path = str_replace(dirname(dirname(__DIR__)).DIRECTORY_SEPARATOR, '', $file->getRealPath());
94
        $content = file_get_contents($file);
95
        if ($strip) {
96
            $content = self::stripWhitespace($content);
97
        } elseif ('LICENSE' === basename($file)) {
98
            $content = "\n".$content."\n";
99
        }
100
101
        if ($path === 'src/Monitor.php') {
102
            $content = str_replace('@package_version@', $this->version, $content);
103
        }
104
105
        $phar->addFromString($path, $content);
106
    }
107
108
    /**
109
     * @param string $source A PHP string
110
     *
111
     * @return string The PHP string with the whitespace removed
112
     */
113
    public static function stripWhitespace($source)
114
    {
115
        if (!function_exists('token_get_all')) {
116
            return $source;
117
        }
118
        $output = '';
119
        foreach (token_get_all($source) as $token) {
120
            if (is_string($token)) {
121
                $output .= $token;
122
            } elseif (in_array($token[0], array(T_COMMENT, T_DOC_COMMENT))) {
123
                $output .= str_repeat("\n", substr_count($token[1], "\n"));
124
            } elseif (T_WHITESPACE === $token[0]) {
125
                // reduce wide spaces
126
                $whitespace = preg_replace('{[ \t]+}', ' ', $token[1]);
127
                // normalize newlines to \n
128
                $whitespace = preg_replace('{(?:\r\n|\r|\n)}', "\n", $whitespace);
129
                // trim leading spaces
130
                $whitespace = preg_replace('{\n +}', "\n", $whitespace);
131
                $output .= $whitespace;
132
            } else {
133
                $output .= $token[1];
134
            }
135
        }
136
137
        return $output;
138
    }
139
140
    protected function getStub()
141
    {
142
        return <<<'EOF'
143
#!/usr/bin/env php
144
<?php
145
/*
146
 * This file is part of the Visithor package.
147
 *
148
 * For the full copyright and license information, please view the LICENSE
149
 * file that was distributed with this source code.
150
 *
151
 * Feel free to edit as you please, and have fun.
152
 *
153
 */
154
Phar::mapPhar('monitor.phar');
155
156
require 'phar://monitor.phar/bin/monitor';
157
__HALT_COMPILER();
158
EOF;
159
    }
160
161
    /**
162
     * Load versions.
163
     */
164
    private function loadVersion()
165
    {
166
        $process = new Process('git log --pretty="%H" -n1 HEAD', __DIR__);
167
        if ($process->run() !== 0) {
168
            throw new \RuntimeException('Can\'t run git log. You must ensure to run compile from visithor git repository clone and that git binary is available.');
169
        }
170
        $this->version = trim($process->getOutput());
171
172
        $process = new Process('git log -n1 --pretty=%ci HEAD', __DIR__);
173
        if ($process->run() !== 0) {
174
            throw new \RuntimeException('Can\'t run git log. You must ensure to run compile from visithor git repository clone and that git binary is available.');
175
        }
176
        $date = new \DateTime(trim($process->getOutput()));
177
        $date->setTimezone(new \DateTimeZone('UTC'));
178
        $this->versionDate = $date->format('Y-m-d H:i:s');
0 ignored issues
show
Bug introduced by
The property versionDate does not seem to exist. Did you mean version?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
179
180
        $process = new Process('git describe --tags HEAD');
181
        if ($process->run() === 0) {
182
            $this->version = trim($process->getOutput());
183
        }
184
    }
185
}
186