File::getPath()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
  declare(strict_types=1);
4
5
  namespace Funivan\PhpTokenizer;
6
7
  use Funivan\PhpTokenizer\Query\Query;
8
9
  /**
10
   * @author Ivan Shcherbak <[email protected]>
11
   */
12
  class File {
13
14
    /**
15
     * @var string
16
     */
17
    protected $path;
18
19
    /**
20
     * @var Collection
21
     */
22
    protected $collection;
23
24
25
    /**
26
     *
27
     * ```
28
     * $file = File::open('test.php');
29
     * $tokens = $file->getCollection();
30
     * if ($tokens[0]=='<?php'){
31
     *  $tokens[0] = '<?php';
32
     *  $file->save();
33
     * }
34
     * ```
35
     *
36
     * @param string $path
37
     * @return File
38
     */
39 3
    public static function open(string $path) : File {
40 3
      return new File($path);
41
    }
42
43
44
    /**
45
     * @param string $path
46
     */
47 36
    public function __construct(string $path) {
48 36
      $this->path = $path;
49 36
      $code = file_get_contents($path);
50 36
      $this->collection = Collection::createFromString($code);
51 36
    }
52
53
54
    /**
55
     * @return Collection
56
     */
57 30
    public function getCollection() : Collection {
58 30
      return $this->collection;
59
    }
60
61
62
    /**
63
     * Save tokens to
64
     *
65
     * @return bool|int
66
     */
67 6
    public function save() {
68 6
      if (!$this->isChanged()) {
69 3
        return true;
70
      }
71 3
      $newCode = $this->collection->assemble();
72 3
      return file_put_contents($this->path, $newCode);
73
    }
74
75
76
    /**
77
     * Parse current tokens
78
     *
79
     * @return self
80
     */
81 3
    public function refresh() : self {
82 3
      $newCode = $this->collection->assemble();
83 3
      $tokens = Helper::getTokensFromString($newCode);
84
85 3
      $this->collection->setItems($tokens);
86 3
      return $this;
87
    }
88
89
90
    /**
91
     * @return string
92
     */
93 36
    public function getPath() : string {
94 36
      return $this->path;
95
    }
96
97
98
    /**
99
     * @return bool
100
     */
101 9
    public function isChanged() : bool {
102 9
      return $this->collection->isChanged();
103
    }
104
105
106
    /**
107
     * Alias for Collection::find
108
     *
109
     * @param Query $query
110
     * @return Collection
111
     */
112 3
    public function find(Query $query) : Collection {
113 3
      return $this->getCollection()->find($query);
114
    }
115
116
  }
117
118
119
120
121