EnvHelper::getRootPath()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 5
eloc 8
c 2
b 0
f 0
nc 5
nop 0
dl 0
loc 17
rs 9.6111
1
<?php
2
3
namespace Silviooosilva\CacheerPhp\Helpers;
4
5
use Composer\InstalledVersions;
6
7
/**
8
 * Class EnvHelper
9
 * @author Sílvio Silva <https://github.com/silviooosilva>
10
 * @package Silviooosilva\CacheerPhp
11
 */
12
class EnvHelper {
13
14
    /**
15
     * @return string
16
     */
17
    public static function getRootPath()
18
    {
19
        // Tenta obter a raiz do projeto via Composer, se disponível
20
        if (class_exists(InstalledVersions::class)) {
21
            $rootPackage = InstalledVersions::getRootPackage();
22
            if (!empty($rootPackage['install_path'])) {
23
                return rtrim($rootPackage['install_path'], DIRECTORY_SEPARATOR);
24
            }
25
        }
26
27
        // Fallback: sobe os diretórios a partir do __DIR__ procurando o .env.example
28
        $baseDir = __DIR__;
29
        while (!file_exists($baseDir . DIRECTORY_SEPARATOR . '.env.example') && $baseDir !== dirname($baseDir)) {
30
            $baseDir = dirname($baseDir);
31
        }
32
33
        return rtrim($baseDir, DIRECTORY_SEPARATOR);
34
    }
35
36
    /**
37
    * @return void
38
    */
39
    public static function copyEnv()
40
    {
41
        $rootDir = self::getRootPath();
42
        $envFile = $rootDir . '/.env';
43
        $envExampleFile = $rootDir . '/.env.example';
44
45
        if (!file_exists($envFile) && file_exists($envExampleFile)) {
46
            if (copy($envExampleFile, $envFile)) {
47
                echo ".env file created successfully from .env.example.\n";
48
            } else {
49
                echo "Failed to create .env file from .env.example.\n";
50
            }
51
        }
52
    }
53
54
}
55