PharCompiler::getStub()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.8333
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Storeman;
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
    /**
25
     * Compiles the phar into the given target file path and the given file mode.
26
     *
27
     * @param string $targetFilePath
28
     * @param int $mode
29
     */
30
    public function compile(string $targetFilePath, int $mode = 0755): void
31
    {
32
        if (file_exists($targetFilePath))
33
        {
34
            $this->filesystem->remove($targetFilePath);
35
        }
36
37
38
        $phar = new \Phar($targetFilePath, 0, 'storeman.phar');
39
        $phar->setSignatureAlgorithm(\Phar::SHA256);
40
41
        $phar->startBuffering();
42
43
        $this->addSourceFiles($phar);
44
        $this->addDependencyFiles($phar);
45
46
        $this->addFile($phar, new \SplFileInfo(__DIR__ . '/../bootstrap.php'));
47
        $this->addFile($phar, new \SplFileInfo(__DIR__ . '/../bin/storeman'));
48
49
        $phar->setStub($this->getStub());
50
        $phar->compressFiles(\Phar::GZ);
51
52
        $phar->stopBuffering();
53
54
        $this->filesystem->chmod($targetFilePath, $mode);
55
    }
56
57
    protected function addSourceFiles(\Phar $phar): void
58
    {
59
        $finder = new Finder();
60
        $finder->files()
61
            ->ignoreVCS(true)
62
            ->name('*.php')
63
            ->in(__DIR__)
64
        ;
65
        foreach ($finder as $file)
66
        {
67
            $this->addFile($phar, $file);
68
        }
69
    }
70
71
    protected function addDependencyFiles(\Phar $phar): void
72
    {
73
        $finder = new Finder();
74
        $finder->files()
75
            ->ignoreVCS(true)
76
            ->name('*.php')
77
            ->name('LICENSE')
78
            ->exclude('docs')
79
            ->exclude('examples')
80
            ->exclude('Tests')
81
            ->exclude('tests')
82
            ->in(__DIR__ . '/../vendor/')
83
        ;
84
        foreach ($finder as $file)
85
        {
86
            $this->addFile($phar, $file);
87
        }
88
    }
89
90
    protected function addFile(\Phar $phar, \SplFileInfo $file): void
91
    {
92
        $relativePath = $this->getRelativeFilePath($file);
93
        $content = $this->stripWhitespace(file_get_contents($file->getPathname()));
94
95
        $phar->addFromString($relativePath, $content);
96
    }
97
98
    protected function getRelativeFilePath(\SplFileInfo $file): string
99
    {
100
        $realPath = $file->getRealPath();
101
        $pathPrefix = dirname(__DIR__) . '/';
102
103
        $pos = strpos($realPath, $pathPrefix);
104
        $relativePath = ($pos !== false) ? substr_replace($realPath, '', $pos, strlen($pathPrefix)) : $realPath;
105
106
        return strtr($relativePath, '\\', '/');
107
    }
108
109
    /**
110
     * Reduces file size while preserving line numbers.
111
     *
112
     * @param string $source
113
     * @return string
114
     */
115
    protected function stripWhitespace(string $source): string
116
    {
117
        $output = '';
118
119
        foreach (token_get_all($source) as $token)
120
        {
121
            if (is_string($token))
122
            {
123
                $output .= $token;
124
            }
125
            elseif (in_array($token[0], [T_COMMENT, T_DOC_COMMENT]))
126
            {
127
                $output .= str_repeat("\n", substr_count($token[1], "\n"));
128
            }
129
            elseif (T_WHITESPACE === $token[0])
130
            {
131
                // reduce wide spaces
132
                $whitespace = preg_replace('{[ \t]+}', ' ', $token[1]);
133
134
                // normalize newlines to \n
135
                $whitespace = preg_replace('{(?:\r\n|\r|\n)}', "\n", $whitespace);
136
137
                // trim leading spaces
138
                $whitespace = preg_replace('{\n +}', "\n", $whitespace);
139
140
                $output .= $whitespace;
141
            }
142
            else
143
            {
144
                $output .= $token[1];
145
            }
146
        }
147
148
        return $output;
149
    }
150
151
    protected function getStub(): string
152
    {
153
        return <<<EOF
154
#!/usr/bin/env php
155
<?php
156
157
Phar::mapPhar('storeman.phar');
158
159
require 'phar://storeman.phar/bin/storeman';
160
161
__HALT_COMPILER();
162
EOF;
163
    }
164
}
165