Completed
Pull Request — 1.x (#19)
by Akihito
01:13
created

AppMeta   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Test Coverage

Coverage 96.3%

Importance

Changes 0
Metric Value
wmc 16
lcom 0
cbo 3
dl 0
loc 51
ccs 26
cts 27
cp 0.963
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
C __construct() 0 25 13
A clearTmpDirectory() 0 10 3
1
<?php
2
3
declare(strict_types=1);
4
/**
5
 * This file is part of the BEAR.AppMeta package.
6
 *
7
 * @license http://opensource.org/licenses/MIT MIT
8
 */
9
namespace BEAR\AppMeta;
10
11
use BEAR\AppMeta\Exception\AppNameException;
12
use BEAR\AppMeta\Exception\NotWritableException;
13
14
class AppMeta extends AbstractAppMeta
15
{
16
    /**
17
     * ClearDir flags not to delete multiple times in single request, Such as unit testing
18
     *
19
     * @var string[]
20
     */
21
    private static $cleanUpFlg = [];
22
23
    /**
24
     * @param string $name    application name      (Vendor\Project)
25
     * @param string $context application context   (prod-hal-app)
26
     * @param string $appDir  application directory
27
     */
28 6
    public function __construct(string $name, string $context = 'app', string $appDir = '')
29
    {
30 6
        $appModule = $name . '\Module\AppModule';
31 6
        if (! class_exists($appModule)) {
32 1
            throw new AppNameException($name);
33
        }
34 6
        $this->name = $name;
35 6
        $this->appDir = $appDir ?: dirname((new \ReflectionClass($appModule))->getFileName(), 3);
36 6
        $this->tmpDir = $this->appDir . '/var/tmp/' . $context;
37 6
        if (! file_exists($this->tmpDir) && ! @mkdir($this->tmpDir, 0777, true) && ! is_dir($this->tmpDir)) {
38 1
            throw new NotWritableException($this->tmpDir);
39
        }
40 6
        $this->logDir = $this->appDir . '/var/log/' . $context;
41 6
        if (! file_exists($this->logDir) && ! @mkdir($this->logDir, 0777, true) && ! is_dir($this->logDir)) {
42
            throw new NotWritableException($this->logDir);
43
        }
44 6
        $isClearable = strpos($context, 'prod-') === false
45 6
            && strpos($context, 'stage-') === false
46 6
            && ! in_array($this->tmpDir, self::$cleanUpFlg, true)
47 6
            && ! file_exists($this->tmpDir . '/.do_not_clear');
48 6
        if ($isClearable) {
49 1
            $this->clearTmpDirectory($this->tmpDir);
50 1
            self::$cleanUpFlg[] = $this->tmpDir;
51
        }
52 6
    }
53
54
    private function clearTmpDirectory(string $dir)
55
    {
56 1
        $unlink = function ($path) use (&$unlink) {
57 1
            foreach (glob(rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . '*') as $file) {
58 1
                is_dir($file) ? $unlink($file) : unlink($file);
59 1
                @rmdir($file);
60
            }
61 1
        };
62 1
        $unlink($dir);
63 1
    }
64
}
65