Passed
Push — master ( ffd0eb...cd99fb )
by Shahrad
22:25
created

EnvironmentsTrait::guessEnvPath()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 8
c 0
b 0
f 0
dl 0
loc 15
rs 10
cc 3
nc 3
nop 0
1
<?php
2
declare(strict_types=1);
3
4
namespace TelegramBot\Traits;
5
6
use Symfony\Component\Dotenv\Dotenv;
7
8
/**
9
 * EnvironmentsTrait class
10
 *
11
 * @link    https://github.com/telegram-bot-php/core
12
 * @author  Shahrad Elahi (https://github.com/shahradelahi)
13
 * @license https://github.com/telegram-bot-php/core/blob/master/LICENSE (MIT License)
14
 */
15
trait EnvironmentsTrait
16
{
17
18
    /**
19
     * Admin chat id
20
     *
21
     * @var int
22
     */
23
    protected static int $adminId = -1;
24
25
    /**
26
     * Guesses a possible path to env file
27
     *
28
     * @return string|null
29
     */
30
  protected static function guessEnvPath(): string|null
31
    {
32
        $defaultEnvPaths = [
33
            getcwd() . '/.env',
34
            getcwd() . '/../.env',
35
            $_SERVER['DOCUMENT_ROOT'] . '/.env',
36
        ];
37
38
        foreach ($defaultEnvPaths as $path) {
39
            if (file_exists($path)) {
40
                return $path;
41
            }
42
        }
43
44
        return null;
45
    }
46
47
    protected static function tryAutoloadEnv(): void {
48
      $envPath = static::guessEnvPath();
49
      if ($envPath !== null) {
50
        (new Dotenv())->load($envPath);
51
      }
52
    }
53
54
    /**
55
     * Set the admin chat id
56
     *
57
     * @return int
58
     */
59
    public static function getAdminId(): int
60
    {
61
        return static::$adminId;
62
    }
63
64
    /**
65
     * Set the admin chat id
66
     *
67
     * @param int $adminId
68
     */
69
    public static function setAdminId(int $adminId): void
70
    {
71
        static::$adminId = $adminId;
72
    }
73
74
    /**
75
     * Get token from env file.
76
     *
77
     * @param string $file
78
     * @return string|null
79
     */
80
    protected function getEnvToken(string $file): string|null
81
    {
82
        if (!file_exists($file)) return null;
83
        return $_ENV['TELEGRAM_BOT_TOKEN'] ?? null;
84
    }
85
86
}
87