Completed
Pull Request — master (#79)
by Julien
05:33 queued 02:16
created

gitignoreContainsComposerLock()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 2
eloc 2
nc 2
nop 1
1
<?php
2
namespace Modules\Core\Console\Installers\Scripts;
3
4
use Illuminate\Console\Command;
5
use Modules\Core\Console\Installers\SetupScript;
6
7
class UnignoreComposerLock implements SetupScript
8
{
9
    const COMPOSER_LOCK = "composer.lock";
10
11
    /**
12
     * Fire the install script
13
     *
14
     * @param  Command $command
15
     * @return mixed
16
     */
17
    public function fire(Command $command)
18
    {
19
        $gitignorePath = base_path('.gitignore');
20
21
        if (!$this->gitignoreContainsComposerLock($gitignorePath)) {
22
            return;
23
        }
24
25
        $removeComposerLock = $command->confirm('Do you want to remove composer.lock from .gitignore ?', true);
26
        if ($removeComposerLock) {
27
            $out = $this->getGitignoreLinesButComposerLock($gitignorePath);
28
            $this->writeNewGitignore($gitignorePath, $out);
29
        }
30
    }
31
32
    /**
33
     * @param $gitignorePath
34
     * @return bool
35
     */
36
    private function gitignoreContainsComposerLock($gitignorePath)
37
    {
38
        return file_exists($gitignorePath) && strpos(file_get_contents($gitignorePath), self::COMPOSER_LOCK) !== false;
39
    }
40
41
    /**
42
     * @param $gitignorePath
43
     * @return array
44
     */
45
    private function getGitignoreLinesButComposerLock($gitignorePath)
46
    {
47
        $data = file($gitignorePath);
48
        $out = [];
49
        foreach ($data as $line) {
50
            if (trim($line) !== self::COMPOSER_LOCK) {
51
                $out[] = $line;
52
            }
53
        }
54
55
        return $out;
56
    }
57
58
    /**
59
     * @param $gitignorePath
60
     * @param $out
61
     */
62
    private function writeNewGitignore($gitignorePath, $out)
63
    {
64
        $fp = fopen($gitignorePath, "w+");
65
        flock($fp, LOCK_EX);
66
        foreach ($out as $line) {
67
            fwrite($fp, $line);
68
        }
69
        flock($fp, LOCK_UN);
70
        fclose($fp);
71
    }
72
}
73