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

AppMeta::getResourceListGenerator()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 9.4285
cc 1
eloc 4
nc 1
nop 0
crap 1
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