Passed
Pull Request — main (#81)
by Tan
03:36 queued 47s
created

ChangeOwnerConfigJson::getDefaultUserGroup()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 2
b 0
f 0
nc 2
nop 0
dl 0
loc 10
rs 10
1
<?php
2
3
namespace CSlant\LaravelTelegramGitNotifier\Commands;
4
5
use Illuminate\Console\Command;
6
7
class ChangeOwnerConfigJson extends Command
8
{
9
    /**
10
     * The name and signature of the console command.
11
     *
12
     * @var string
13
     */
14
    protected $signature = 'config-json:change-owner 
15
                {user? : The user to change owner}
16
                {group? : The group to change owner}';
17
18
    /**
19
     * The console command description.
20
     *
21
     * @var string
22
     */
23
    protected $description = 'config-json';
24
25
    /**
26
     * Execute the console command.
27
     *
28
     * @return void
29
     */
30
    public function handle(): void
31
    {
32
        if (PHP_OS_FAMILY !== 'Linux') {
33
            $this->error('This command only works on Linux');
34
35
            return;
36
        }
37
38
        $user = $this->argument('user') ?: $this->getDefaultUserGroup();
39
        $group = $this->argument('group') ?: $this->getDefaultUserGroup();
40
41
        if (empty($user) || empty($group)) {
42
            $user = $group = $this->getDefaultUserGroup();
43
        }
44
45
        $this->changeOwner($user, $group);
46
    }
47
48
    /**
49
     * @param  string  $user
50
     * @param  string  $group
51
     * @return void
52
     */
53
    private function changeOwner(string $user, string $group): void
54
    {
55
        $jsonsPath = config('telegram-git-notifier.data_file.storage_folder');
56
        if (is_string($jsonsPath) && file_exists($jsonsPath)) {
57
            shell_exec('chown -R '.escapeshellarg($user).':'.escapeshellarg($group).' '.escapeshellarg($jsonsPath));
58
        } else {
59
            $this->error('The path to the jsons folder is not valid');
60
        }
61
    }
62
63
    /**
64
     * Get the default user and group for the chown command.
65
     *
66
     * @return string
67
     */
68
    private function getDefaultUserGroup(): string
69
    {
70
        $defaultUserGroup = exec('ps aux | egrep "(apache|httpd|nginx)" | grep -v "root" | head -n1 | cut -d\  -f1');
71
        if ($defaultUserGroup === false) {
72
            $this->error('Failed to retrieve default user and group');
73
74
            return '';
75
        }
76
77
        return $defaultUserGroup;
78
    }
79
}
80