Compiler   A
last analyzed

Complexity

Total Complexity 19

Size/Duplication

Total Lines 163
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 4
Bugs 0 Features 1
Metric Value
wmc 19
c 4
b 0
f 1
lcom 1
cbo 2
dl 0
loc 163
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
B compile() 0 60 4
A addFile() 0 16 4
B stripWhitespace() 0 26 6
A getStub() 0 20 1
A loadVersion() 0 21 4
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/rtheunissen')
58
            ->in($root.'/vendor/eljam')
59
            ->in($root.'/vendor/hogosha')
60
            ->in($root.'/vendor/webmozart')
61
            ->in($root.'/vendor/psr')
62
            ->in($root.'/vendor/guzzle')
63
            ->in($root.'/vendor/symfony')
64
        ;
65
66
        foreach ($finder as $file) {
67
            $this->addFile($phar, $file);
68
        }
69
70
        $this->addFile($phar, new \SplFileInfo($root.'/vendor/autoload.php'));
71
        $this->addFile($phar, new \SplFileInfo($root.'/vendor/composer/autoload_namespaces.php'));
72
        $this->addFile($phar, new \SplFileInfo($root.'/vendor/composer/autoload_psr4.php'));
73
        $this->addFile($phar, new \SplFileInfo($root.'/vendor/composer/autoload_classmap.php'));
74
        $this->addFile($phar, new \SplFileInfo($root.'/vendor/composer/autoload_files.php'));
75
        $this->addFile($phar, new \SplFileInfo($root.'/vendor/composer/autoload_real.php'));
76
77
        if (file_exists($root.'/vendor/composer/include_paths.php')) {
78
            $this->addFile($phar, new \SplFileInfo($root.'/vendor/composer/include_paths.php'));
79
        }
80
        $this->addFile($phar, new \SplFileInfo($root.'/vendor/composer/ClassLoader.php'));
81
82
        $binContent = file_get_contents($root.'/bin/monitor');
83
        $binContent = preg_replace('{^#!/usr/bin/env php\s*}', '', $binContent);
84
        $phar->addFromString('bin/monitor', $binContent);
85
86
        // Stubs
87
        $phar->setStub($this->getStub());
88
        $phar->stopBuffering();
89
        unset($phar);
90
    }
91
92
    protected function addFile(\Phar $phar, \SplFileInfo $file, $strip = true)
93
    {
94
        $path = str_replace(dirname(dirname(__DIR__)).DIRECTORY_SEPARATOR, '', $file->getRealPath());
95
        $content = file_get_contents($file);
96
        if ($strip) {
97
            $content = self::stripWhitespace($content);
98
        } elseif ('LICENSE' === basename($file)) {
99
            $content = "\n".$content."\n";
100
        }
101
102
        if ($path === 'src/Monitor.php') {
103
            $content = str_replace('@package_version@', $this->version, $content);
104
        }
105
106
        $phar->addFromString($path, $content);
107
    }
108
109
    /**
110
     * @param string $source A PHP string
111
     *
112
     * @return string The PHP string with the whitespace removed
113
     */
114
    public static function stripWhitespace($source)
115
    {
116
        if (!function_exists('token_get_all')) {
117
            return $source;
118
        }
119
        $output = '';
120
        foreach (token_get_all($source) as $token) {
121
            if (is_string($token)) {
122
                $output .= $token;
123
            } elseif (in_array($token[0], array(T_COMMENT, T_DOC_COMMENT))) {
124
                $output .= str_repeat("\n", substr_count($token[1], "\n"));
125
            } elseif (T_WHITESPACE === $token[0]) {
126
                // reduce wide spaces
127
                $whitespace = preg_replace('{[ \t]+}', ' ', $token[1]);
128
                // normalize newlines to \n
129
                $whitespace = preg_replace('{(?:\r\n|\r|\n)}', "\n", $whitespace);
130
                // trim leading spaces
131
                $whitespace = preg_replace('{\n +}', "\n", $whitespace);
132
                $output .= $whitespace;
133
            } else {
134
                $output .= $token[1];
135
            }
136
        }
137
138
        return $output;
139
    }
140
141
    protected function getStub()
142
    {
143
        return <<<'EOF'
144
#!/usr/bin/env php
145
<?php
146
/*
147
 * This file is part of the Visithor package.
148
 *
149
 * For the full copyright and license information, please view the LICENSE
150
 * file that was distributed with this source code.
151
 *
152
 * Feel free to edit as you please, and have fun.
153
 *
154
 */
155
Phar::mapPhar('monitor.phar');
156
157
require 'phar://monitor.phar/bin/monitor';
158
__HALT_COMPILER();
159
EOF;
160
    }
161
162
    /**
163
     * Load versions.
164
     */
165
    private function loadVersion()
166
    {
167
        $process = new Process('git log --pretty="%H" -n1 HEAD', __DIR__);
168
        if ($process->run() !== 0) {
169
            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.');
170
        }
171
        $this->version = trim($process->getOutput());
172
173
        $process = new Process('git log -n1 --pretty=%ci HEAD', __DIR__);
174
        if ($process->run() !== 0) {
175
            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.');
176
        }
177
        $date = new \DateTime(trim($process->getOutput()));
178
        $date->setTimezone(new \DateTimeZone('UTC'));
179
        $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...
180
181
        $process = new Process('git describe --tags HEAD');
182
        if ($process->run() === 0) {
183
            $this->version = trim($process->getOutput());
184
        }
185
    }
186
}
187