AppService.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace App;
  3. use YdbPlatform\Ydb\Ydb;
  4. use Monolog\Logger;
  5. use Monolog\Handler\StreamHandler;
  6. class AppService
  7. {
  8. const DEFAULT_ENDPOINT = 'ydb.serverless.yandexcloud.net:2135';
  9. /**
  10. * @var array
  11. */
  12. protected $config = [
  13. 'db' => [
  14. 'database' => null,
  15. 'endpoint' => null,
  16. 'discovery' => false,
  17. 'iam_config' => [
  18. 'use_metadata' => false,
  19. 'key_id' => null,
  20. 'service_account_id' => null,
  21. 'private_key_file' => null,
  22. 'service_file' => null,
  23. 'oauth_token' => null,
  24. 'root_cert_file' => null,
  25. 'temp_dir' => null,
  26. ],
  27. ],
  28. 'use_logger' => false,
  29. ];
  30. public function __construct()
  31. {
  32. $this->config['db']['database'] = $this->getEnv('DB_DATABASE', null);
  33. $this->config['db']['endpoint'] = $this->getEnv('DB_ENDPOINT', static::DEFAULT_ENDPOINT);
  34. $this->config['db']['discovery'] = $this->getEnv('DB_DISCOVERY', false);
  35. $this->config['db']['iam_config'] = [
  36. // 'use_metadata' => $this->getEnv('USE_METADATA', false),
  37. 'key_id' => $this->getEnv('SA_ACCESS_KEY_ID', null),
  38. 'service_account_id' => $this->getEnv('SA_ID', null),
  39. 'private_key_file' => $this->getEnv('SA_PRIVATE_KEY_FILE', null),
  40. 'service_file' => $this->getEnv('SA_SERVICE_FILE', null),
  41. 'oauth_token' => $this->getEnv('DB_OAUTH_TOKEN', null),
  42. 'root_cert_file' => $this->getEnv('YDB_SSL_ROOT_CERTIFICATES_FILE', null),
  43. 'anonymous' => $this->getEnv('YDB_ANONYMOUS', false),
  44. 'insecure' => $this->getEnv('YDB_INSECURE', false),
  45. 'temp_dir' => '/tmp',
  46. ];
  47. $this->config['use_logger'] = $this->getEnv('USE_LOGGER', false);
  48. // print_r($_ENV);
  49. // print("\n\nconfig:\n");
  50. // print_r($this->config);
  51. }
  52. /**
  53. * @param string $key
  54. * @return mixed|null
  55. */
  56. public function config($key)
  57. {
  58. return $this->config[$key] ?? null;
  59. }
  60. /**
  61. * @return Logger|null
  62. */
  63. public function getLogger()
  64. {
  65. if ($this->config('use_logger'))
  66. {
  67. $logger = new Logger('ydb');
  68. $logger->pushHandler(new StreamHandler('./logs/ydb-' . date('Y-m-d') . '.log'));
  69. return $logger;
  70. }
  71. return null;
  72. }
  73. public function initYdb()
  74. {
  75. return new Ydb($this->config('db'), $this->getLogger());
  76. }
  77. protected function getEnv($var, $default = null)
  78. {
  79. return $_ENV[$var] ?? getenv($var) ?? $default;
  80. }
  81. }