BucketFactory::__invoke()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 1
dl 0
loc 10
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace PhpCache\Storage;
4
5
/**
6
 * Description of BucketFactory.
7
 *
8
 * @author dude920228
9
 */
10
class BucketFactory
11
{
12
    public function __invoke(\Psr\Container\ContainerInterface $container)
13
    {
14
        $config = $container->getConfig();
15
        $backupDir = $config['backupDir'];
16
        $bucket = new Bucket($backupDir);
17
        if (!file_exists($backupDir)) {
18
            return $bucket;
19
        }
20
21
        return $this->restoreFromBackup($bucket, $backupDir);
22
    }
23
24
    private function restoreFromBackup($bucket, $backupDir)
25
    {
26
        foreach (new \DirectoryIterator($backupDir) as $file) {
27
            if (!$file->isDot() && $file->isFile()) {
28
                $keyParts = explode('.', $file->getFilename());
29
                $key = $keyParts[0];
30
                $handle = $file->openFile('r');
31
                $contents = '';
32
                while (!$handle->eof()) {
33
                    $contents .= $handle->fread(128);
34
                }
35
                if ($contents != '') {
36
                    $unserialized = unserialize($contents);
37
                    $unserialized['content'] = gzuncompress($unserialized['content']);
38
                    $bucket->store($key, $unserialized['content'], $unserialized['created_time']);
39
                }
40
                unlink($file->getPathname());
41
            }
42
        }
43
44
        return $bucket;
45
    }
46
}
47