Passed
Pull Request — main (#81)
by Tan
03:33
created

ChangeOwnerConfigJson::changeOwner()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 5
c 0
b 0
f 0
nc 2
nop 2
dl 0
loc 7
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 = (string) ($this->argument('user') ?? $this->getDefaultUserGroup());
39
        $group = (string) ($this->argument('group') ?? $user);
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
     *
52
     * @return void
53
     */
54
    private function changeOwner(string $user, string $group): void
55
    {
56
        $jsonsPath = config('telegram-git-notifier.data_file.storage_folder');
57
        if (is_string($jsonsPath) && file_exists($jsonsPath)) {
58
            shell_exec('chown -R '.escapeshellarg($user).':'.escapeshellarg($group).' '.escapeshellarg($jsonsPath));
59
        } else {
60
            $this->error('The path to the jsons folder is not valid');
61
        }
62
    }
63
64
    /**
65
     * Get the default user and group for the chown command.
66
     *
67
     * @return string
68
     */
69
    private function getDefaultUserGroup(): string
70
    {
71
        $defaultUserGroup = exec('ps aux | egrep "(apache|httpd|nginx)" | grep -v "root" | head -n1 | cut -d\  -f1');
72
        if ($defaultUserGroup === false) {
73
            $this->error('Failed to retrieve default user and group');
74
75
            return '';
76
        }
77
78
        return $defaultUserGroup;
79
    }
80
}
81