File: Freezer.php

package info (click to toggle)
dojo 1.10.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 97,980 kB
  • ctags: 10,348
  • sloc: php: 10,616; xml: 3,429; java: 3,098; sql: 928; sh: 484; pascal: 205; perl: 182; makefile: 77; python: 45; sed: 37; ruby: 10
file content (63 lines) | stat: -rw-r--r-- 1,634 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<?php

final class Freezer
{
  protected $key_delimeter = '%%%';

  private $length = 99999;
  private $nodes_location = '';
  private $nodes = array();

  public static function clean($directory, $suffix) {
    $loc = $directory . '/' . $suffix;
    file_exists($loc) && unlink($loc);
  }

  public function __construct($directory, $suffix) {
    $this->nodes_location = $directory . '/' . $suffix;
    touch($this->nodes_location);
    $nodes_file = fopen($this->nodes_location, 'r');
    $this->_readFromFile($nodes_file);
    fclose($nodes_file);
  }

  public function __destruct() {
    $this->flush();
  }

  private function _readFromFile($nodes_file) {
    while (!feof($nodes_file)) {
      $line = stream_get_line($nodes_file, $this->length, "\n");
      list($key, $value) = explode($this->key_delimeter, $line);
      
      if (trim($key)) {
        $this->nodes[$key] = $value;
      }
    } 
  }

  public function ids($flush = TRUE) {
    return array_keys($this->nodes);
  }

  public function open($key, $default) {
    if(array_key_exists($key, $this->nodes)){
        return unserialize(str_replace("\\n", "\n", $this->nodes[$key]));
    }
    return $default;
  }

  public function save($key, $content) {
    $this->nodes[$key] =  str_replace("\n", "\\n", serialize($content));
  }

  private function flush() {
    $tmp = fopen($this->nodes_location . '_tmp', 'w');
    foreach ($this->nodes as $key => $value) {
      fwrite($tmp, $key . $this->key_delimeter . $value . "\n");
    }
    fclose($tmp);
    unlink($this->nodes_location);
    rename($this->nodes_location . '_tmp', $this->nodes_location);
  }
}