Passed
Pull Request — main (#81)
by Tan
02:50
created

ChangeOwnerConfigJson::getDefaultUserGroup()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 8
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');
39
        $group = $this->argument('group') ?? $user;
40
41
        if (!is_string($user) || !is_string($group)) {
42
            $user = $group = $this->getDefaultUserGroup();
43
        }
44
45
        $jsonsPath = config('telegram-git-notifier.data_file.storage_folder');
46
        if (is_string($jsonsPath) && file_exists($jsonsPath)) {
47
            shell_exec("chown -R ".escapeshellarg($user).":".escapeshellarg($group)." ".escapeshellarg($jsonsPath));
48
        } else {
49
            $this->error('The path to the jsons folder is not valid');
50
        }
51
    }
52
53
    /**
54
     * Get the default user and group for the chown command.
55
     *
56
     * @return string
57
     */
58
    private function getDefaultUserGroup(): string
59
    {
60
        $defaultUserGroup = exec('ps aux | egrep "(apache|httpd|nginx)" | grep -v "root" | head -n1 | cut -d\  -f1');
61
        if ($defaultUserGroup === false) {
62
            $this->error('Failed to retrieve default user and group');
63
            return '';
64
        }
65
        return $defaultUserGroup;
66
    }
67
}
68