CommentLineAppender::insertComment()   B
last analyzed

Complexity

Conditions 6
Paths 9

Size

Total Lines 34
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 34
rs 8.439
cc 6
eloc 25
nc 9
nop 3
1
<?php
2
namespace DicDoc;
3
4
/**
5
 * Class CommentLineAppender
6
 *
7
 * @package DicDoc
8
 */
9
class CommentLineAppender implements Interfaces\TextFileManipulator
10
{
11
12
    /**
13
     * @param $filePath
14
     * @param $text
15
     * @param $position
16
     *
17
     * @return bool
18
     */
19
    public function insertComment($filePath, $text, $position)
20
    {
21
        $reading = @fopen($filePath, 'r');
22
        if (!$reading) {
23
            return false;
24
        }
25
        $tempFilePath = tempnam(sys_get_temp_dir(), 'DIC');
26
        $writing = fopen($tempFilePath, 'w');
27
        $replaced = false;
28
        $i = 1;
29
        while (!feof($reading)) {
30
            $line = fgets($reading);
31
            if ($position == $i++) {
32
                $ident = "";
33
                if (preg_match('/^(\s*|\t*)/', $line, $matches)) {
34
                    $ident = $matches[1];
35
                }
36
                fputs($writing, $ident.$text."\n");
37
                $line = preg_replace('/^(.*)?dd\((.*)\)(.*)?/', "$1$2$3", $line);
38
                $replaced = true;
39
            }
40
            fputs($writing, $line);
41
        }
42
        fclose($reading);
43
        fclose($writing);
44
45
        if ($replaced) {
46
            return rename($tempFilePath, $filePath);
47
        } else {
48
            unlink($tempFilePath);
49
50
            return false;
51
        }
52
    }
53
54
}