Completed
Push — master ( fa0d52...fef7a6 )
by Arne
01:59
created

PharCompiler::compile()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 24
rs 8.9713
c 0
b 0
f 0
cc 2
eloc 13
nc 2
nop 1
1
<?php
2
3
namespace Archivr;
4
5
use Symfony\Component\Filesystem\Filesystem;
6
use Symfony\Component\Finder\Finder;
7
8
/**
9
 * Compiles the application into a standalone phar which is suitable for distribution.
10
 * Based on the composer counterpart: https://github.com/composer/composer/blob/master/src/Composer/Compiler.php
11
 */
12
class PharCompiler
13
{
14
    /**
15
     * @var Filesystem
16
     */
17
    protected $filesystem;
18
19
    public function __construct()
20
    {
21
        $this->filesystem = new Filesystem();
22
    }
23
24
    public function compile(string $targetFileName): void
25
    {
26
        if (file_exists($targetFileName))
27
        {
28
            $this->filesystem->remove($targetFileName);
29
        }
30
31
32
        $phar = new \Phar($targetFileName, 0, 'archivr.phar');
33
        $phar->setSignatureAlgorithm(\Phar::SHA256);
34
35
        $phar->startBuffering();
36
37
        $this->addSourceFiles($phar);
38
        $this->addDependencyFiles($phar);
39
40
        $this->addFile($phar, new \SplFileInfo(__DIR__ . '/../bootstrap.php'));
41
        $this->addFile($phar, new \SplFileInfo(__DIR__ . '/../bin/archivr'));
42
43
        $phar->setStub($this->getStub());
44
        $phar->compressFiles(\Phar::GZ);
45
46
        $phar->stopBuffering();
47
    }
48
49
    protected function addSourceFiles(\Phar $phar): void
50
    {
51
        $finder = new Finder();
52
        $finder->files()
53
            ->ignoreVCS(true)
54
            ->name('*.php')
55
            ->in(__DIR__)
56
        ;
57
        foreach ($finder as $file)
58
        {
59
            $this->addFile($phar, $file);
60
        }
61
    }
62
63
    protected function addDependencyFiles(\Phar $phar): void
64
    {
65
        $finder = new Finder();
66
        $finder->files()
67
            ->ignoreVCS(true)
68
            ->name('*.php')
69
            ->name('LICENSE')
70
            ->exclude('docs')
71
            ->exclude('examples')
72
            ->exclude('Tests')
73
            ->exclude('tests')
74
            ->in(__DIR__ . '/../vendor/')
75
        ;
76
        foreach ($finder as $file)
77
        {
78
            $this->addFile($phar, $file);
79
        }
80
    }
81
82
    protected function addFile(\Phar $phar, \SplFileInfo $file): void
83
    {
84
        $relativePath = $this->getRelativeFilePath($file);
85
        $content = $this->stripWhitespace(file_get_contents($file->getPathname()));
86
87
        $phar->addFromString($relativePath, $content);
88
    }
89
90
    protected function getRelativeFilePath(\SplFileInfo $file): string
91
    {
92
        $realPath = $file->getRealPath();
93
        $pathPrefix = dirname(__DIR__) . DIRECTORY_SEPARATOR;
94
95
        $pos = strpos($realPath, $pathPrefix);
96
        $relativePath = ($pos !== false) ? substr_replace($realPath, '', $pos, strlen($pathPrefix)) : $realPath;
97
98
        return strtr($relativePath, '\\', '/');
99
    }
100
101
    /**
102
     * Reduces file size while preserving line numbers.
103
     *
104
     * @param string $source
105
     * @return string
106
     */
107
    protected function stripWhitespace(string $source): string
108
    {
109
        $output = '';
110
111
        foreach (token_get_all($source) as $token)
112
        {
113
            if (is_string($token))
114
            {
115
                $output .= $token;
116
            }
117
            elseif (in_array($token[0], [T_COMMENT, T_DOC_COMMENT]))
118
            {
119
                $output .= str_repeat("\n", substr_count($token[1], "\n"));
120
            }
121
            elseif (T_WHITESPACE === $token[0])
122
            {
123
                // reduce wide spaces
124
                $whitespace = preg_replace('{[ \t]+}', ' ', $token[1]);
125
126
                // normalize newlines to \n
127
                $whitespace = preg_replace('{(?:\r\n|\r|\n)}', "\n", $whitespace);
128
129
                // trim leading spaces
130
                $whitespace = preg_replace('{\n +}', "\n", $whitespace);
131
132
                $output .= $whitespace;
133
            }
134
            else
135
            {
136
                $output .= $token[1];
137
            }
138
        }
139
140
        return $output;
141
    }
142
143
    protected function getStub(): string
144
    {
145
        return <<<EOF
146
#!/usr/bin/env php
147
<?php
148
149
Phar::mapPhar('archivr.phar');
150
151
require 'phar://archivr.phar/bin/archivr';
152
153
__HALT_COMPILER();
154
EOF;
155
    }
156
}
157