Completed
Push — 1.x ( f4f2df...fa8652 )
by Akihito
11s
created

AppMeta   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Test Coverage

Coverage 89.29%

Importance

Changes 8
Bugs 1 Features 0
Metric Value
wmc 16
lcom 0
cbo 3
dl 0
loc 52
ccs 25
cts 28
cp 0.8929
rs 10
c 8
b 1
f 0

2 Methods

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