Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
85.71% covered (warning)
85.71%
12 / 14
80.00% covered (warning)
80.00%
4 / 5
CRAP
0.00% covered (danger)
0.00%
0 / 1
ConsoleCliStorage
85.71% covered (warning)
85.71%
12 / 14
80.00% covered (warning)
80.00%
4 / 5
15.66
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getHomePath
n/a
0 / 0
n/a
0 / 0
6
 getRootPath
71.43% covered (warning)
71.43%
5 / 7
0.00% covered (danger)
0.00%
0 / 1
4.37
 store
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 restore
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 remove
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3namespace Apie\Console;
4
5use Apie\Core\Other\FileReaderInterface;
6use Apie\Core\Other\FileWriterInterface;
7
8final class ConsoleCliStorage
9{
10    private ?string $rootPath = null;
11
12    private ?string $homePath = null;
13
14    public function __construct(
15        private readonly FileWriterInterface&FileReaderInterface $fileWriter
16    ) {
17    }
18
19    /**
20     * @codeCoverageIgnore
21     */
22    private function getHomePath(): string
23    {
24        if ($this->homePath) {
25            return $this->homePath;
26        }
27        $home = getenv('HOME');
28        if (empty($home)) {
29            if (!empty($_SERVER['HOMEDRIVE']) && !empty($_SERVER['HOMEPATH'])) {
30                // home on windows
31                $home = $_SERVER['HOMEDRIVE'] . $_SERVER['HOMEPATH'];
32            }
33        }
34        return $this->homePath = empty($home) ? $this->getRootPath() : $home;
35    }
36
37    private function getRootPath(): string
38    {
39        if ($this->rootPath) {
40            return $this->rootPath;
41        }
42        $bt = debug_backtrace();
43        if (isset($bt[0]['file'])) {
44            return $this->rootPath = $bt[0]['file'];
45        }
46        // fallback
47        $files = get_included_files();
48        return $this->rootPath = reset($files) ? : __FILE__;
49    }
50    public function store(string $key, string $value): void
51    {
52        $filePath = $this->getHomePath() . '/.apie-' . md5($this->getRootPath() . '...' . $key) . '-cli';
53        $this->fileWriter->writeFile($filePath, $value);
54    }
55
56    public function restore(string $key): ?string
57    {
58        $filePath = $this->getHomePath() . '/.apie-' . md5($this->getRootPath() . '...' . $key) . '-cli';
59        return $this->fileWriter->fileExists($filePath) ? $this->fileWriter->readContents($filePath) : null;
60    }
61
62    public function remove(string $key): void
63    {
64        $filePath = $this->getHomePath() . '/.apie-' . md5($this->getRootPath() . '...' . $key) . '-cli';
65        $this->fileWriter->clearPath($filePath);
66    }
67}