Example #1
0
 protected function getEnv()
 {
     try {
         $loader = new Loader('.env');
         $loader->parse()->putenv(true);
     } catch (\InvalidArgumentException $e) {
         //ignore
     }
     return ["GLOBAL_CLIENT_ID" => getenv('GLOBAL_CLIENT_ID'), "GLOBAL_CLIENT_SECRET" => getenv('GLOBAL_CLIENT_SECRET'), "APP_CLIENT_ID" => getenv('APP_CLIENT_ID'), "APP_CLIENT_SECRET" => getenv('APP_CLIENT_SECRET'), "DOMAIN" => getenv('DOMAIN')];
 }
Example #2
0
function loadDotEnv($dir = __DIR__)
{
    /**
     * alternatively, Dotenv::load(dirname(__DIR__) . DIRECTORY_SEPARATOR . '.env');
     */
    Dotenv::load(['filepath' => dirname($dir) . DIRECTORY_SEPARATOR . '.env', 'toEnv' => true]);
}
 /**
  * Creates and returns a new Options instance
  *
  * @param array $getopt Options data
  * @param array $validators Validators to validate the options
  * @param array $defaults Default values for the options
  * @return Options
  */
 public function newInstance(array $getopt = [], array $validators = [], array $defaults = [])
 {
     $this->error = null;
     // Extend the base config
     if (isset($this->config['getopt'])) {
         $getopt = array_merge($this->config['getopt'], $getopt);
     }
     if (isset($this->config['validators'])) {
         $validators = array_merge($this->config['validators'], $validators);
     }
     if (isset($this->config['defaults'])) {
         $defaults = array_merge($this->config['defaults'], $defaults);
     }
     // Read command line
     $cli = $this->context->getopt($getopt);
     $data = new OptionTransformer($cli->get());
     // Create the options container instance
     $options = new Options($validators, $defaults);
     $options->loadOptionData($data->getArrayCopy());
     // initial load so we can access the config option
     // Read config file
     $configLoader = new DotenvLoader((string) new TildeExpander($options->config));
     try {
         $configData = $configLoader->parse()->toArray();
         $options->loadOptionData($configData, false);
         // don't overwrite CLI data
     } catch (\InvalidArgumentException $e) {
         $this->error = $e;
     }
     return $options;
 }
Example #4
0
 /**
  * Initialize testing environment
  *
  * @return void
  */
 public static function init()
 {
     if (is_file(__DIR__ . '/config/.env')) {
         Dotenv::load(['filepath' => __DIR__ . '/config/.env', 'toEnv' => true]);
     }
     // Define application environment
     if (!isset($_ENV['WELLCART_APPLICATION_ENV'])) {
         $_ENV['WELLCART_APPLICATION_ENV'] = getenv('WELLCART_APPLICATION_ENV') ?: 'testing';
     }
     // Load the user-defined test configuration file, if it exists; otherwise, load
     if (is_readable(__DIR__ . '/config/application.config.php')) {
         $testConfig = __DIR__ . '/config/application.config.php';
     } else {
         $testConfig = __DIR__ . '/config/application.config.php.dist';
     }
     static::initAutoloader();
     defined('WELLCART_ROOT') || define('WELLCART_ROOT', getenv('WELLCART_ROOT') ? getenv('WELLCART_ROOT') : str_replace('\\', '/', __DIR__) . '/');
     defined('WELLCART_BIN_PATH') || define('WELLCART_BIN_PATH', getenv('WELLCART_BIN_PATH') ? getenv('WELLCART_BIN_PATH') : static::findParentPath('bin'));
     defined('WELLCART_PUBLIC_PATH') || define('WELLCART_PUBLIC_PATH', static::findParentPath('public'));
     // Define application context
     if (!is_file(WELLCART_ROOT . 'config/autoload/installed.php')) {
         $_ENV['WELLCART_APPLICATION_CONTEXT'] = Application::CONTEXT_SETUP;
     } elseif (empty($_ENV['WELLCART_APPLICATION_CONTEXT'])) {
         $_ENV['WELLCART_APPLICATION_CONTEXT'] = Application::CONTEXT_GLOBAL;
     }
     /**
      * Setup initial PHP environment
      */
     PHPEnvironment::initialize();
     $app = Application::init(Config::application(include $testConfig));
     application($app);
 }
Example #5
0
 /**
  * {@inheritdoc}
  */
 protected function configure()
 {
     $dotEnvPath = dirname(dirname(__DIR__)) . '/.env';
     if (file_exists($dotEnvPath) && is_readable($dotEnvPath)) {
         Dotenv::load(['filepath' => $dotEnvPath, 'toEnv' => true]);
     }
     $this->install(new PackageModule());
     $this->bind(ClientInterface::class)->to(Client::class);
     $this->bind(GlobeApiClientInterface::class)->to(GlobeApiClient::class);
 }
Example #6
0
 /**
  * {@inheritdoc}
  */
 protected function configure()
 {
     Dotenv::load(['filepath' => dirname(dirname(__DIR__)) . '/.env', 'expect' => ['DB_DSN', 'DB_USER', 'DB_PASS'], 'toEnv' => true]);
     $this->install(new PackageModule());
     $this->install(new DbAppPackage($_ENV['DB_DSN'], $_ENV['DB_USER'], $_ENV['DB_PASS'], $_ENV['DB_READ']));
     $this->bind('Doctrine\\ORM\\EntityManager')->annotatedWith("manager")->toProvider('InakaPhper\\Lunchlog\\Module\\Provider\\DoctrineORMProvider');
     // Entity
     $this->bind('InakaPhper\\Lunchlog\\Entity\\Shop')->annotatedWith("shop")->toInstance(new Shop());
     $this->bind('InakaPhper\\Lunchlog\\Entity\\Menu')->annotatedWith("menu")->toInstance(new Menu());
 }
Example #7
0
 /**
  * {@inheritdoc}
  */
 protected function configure()
 {
     $dotEnvPath = dirname(dirname(__DIR__)) . '/.env';
     if (file_exists($dotEnvPath) && is_readable($dotEnvPath)) {
         Dotenv::load(['filepath' => $dotEnvPath, 'toEnv' => true]);
     }
     $this->install(new PackageModule());
     $this->bind(ClientInterface::class)->to(Client::class);
     $this->bind(ChatWorkApiClientInterface::class)->to(ChatWorkApiClient::class);
     $this->bind(SchemeCollectionInterface::class)->toProvider(SchemeCollectionProvider::class);
     $this->bind(ResourceInterface::class)->to(Resource::class);
 }
<?php

namespace App;

use App\Command\HelloWorldCommand;
use Choccybiccy\Telegram\ApiClient;
use Choccybiccy\Telegram\CommandHandler;
use Choccybiccy\Telegram\Entity\Message;
use Choccybiccy\Telegram\Entity\Update;
use josegonzalez\Dotenv\Loader;
use Slim\Slim;
require_once "../vendor/autoload.php";
// Load the .env file if it exists.
if (file_exists(__DIR__ . "/../.env")) {
    $loader = new Loader("../.env");
    $loader->parse()->define();
}
/**
 * Create and inject the ApiClient into the Slim app.
 */
$app = new Slim();
$app->telegram = function () {
    return new ApiClient(TELEGRAM_BOT_AUTH_TOKEN);
};
/**
 * Here's the endpoint where Telegram will send it's updates to. Register your
 * commands in the CommandHandler in here.
 */
$app->post("/webhook", function () use($app) {
    /** @var Update $update */
    $update = $app->telegram->entityFromBody($app->request->getBody(), new Update());
Example #9
0
<?php

use josegonzalez\Dotenv\Loader as Dotenv;
Dotenv::load(['filepath' => dirname(dirname(__DIR__)) . '/.env', 'toEnv' => true]);
$pdo = new PDO($_ENV['DB_DSN'], $_ENV['DB_USER'], $_ENV['DB_PASS']);
preg_match("/dbname=(\\w+)/i", $_ENV['DB_DSN'], $parts);
$name = $parts[1];
return ["paths" => ["migrations" => __DIR__], "environments" => ["default_migration_table" => "phinxlog", "default_database" => "default", "default" => ["name" => $name, "connection" => $pdo], "test" => ["name" => $name . '_test', "connection" => $pdo]]];
Example #10
0
 public function loadEnvironment()
 {
     $env = new Loader(getcwd() . '/../.env');
     return $env->parse()->prefix('APP_')->define();
 }
Example #11
0
<?php

/**
 * Created by PhpStorm.
 * User: yogasukma
 * Date: 12/22/15
 * Time: 2:39 PM
 */
use josegonzalez\Dotenv\Loader;
$env = new Loader(__DIR__ . "/../.env");
$env->parse()->putenv(TRUE);
Example #12
0
File: env.php Project: themogwi/app
<?php

use Cake\Utility\Hash;
use josegonzalez\Dotenv\Loader;
$config = [];
if (!env('APP_NAME')) {
    $dotenv = new Loader([__DIR__ . DS . '.env', __DIR__ . DS . '.env.default']);
    $dotenv->setFilters(['josegonzalez\\Dotenv\\Filter\\LowercaseKeyFilter', 'josegonzalez\\Dotenv\\Filter\\UppercaseFirstKeyFilter', 'josegonzalez\\Dotenv\\Filter\\UnderscoreArrayFilter', function ($data) {
        $keys = ['Debug' => 'debug', 'Emailtransport' => 'EmailTransport', 'Database' => 'Datasources.default', 'Test.database' => 'Datasources.test', 'Test' => null, 'Cache.duration' => null, 'Cache.cakemodel' => 'Cache._cake_model_', 'Cache.cakecore' => 'Cache._cake_core_'];
        foreach ($keys as $key => $newKey) {
            if ($newKey === null) {
                $data = Hash::remove($data, $key);
                continue;
            }
            $value = Hash::get($data, $key);
            $data = Hash::remove($data, $key);
            $data = Hash::insert($data, $newKey, $value);
        }
        return $data;
    }]);
    $dotenv->parse();
    $dotenv->filter();
    $config = $dotenv->toArray();
}
return $config;
Example #13
0
<?php

use Cake\Utility\Hash;
use josegonzalez\Dotenv\Loader;
$config = [];
if (!env('APP_NAME')) {
    $dotenv = new Loader([__DIR__ . DS . '.env', __DIR__ . DS . '.env.default']);
    $dotenv->setFilters(['josegonzalez\\Dotenv\\Filter\\LowercaseKeyFilter', 'josegonzalez\\Dotenv\\Filter\\UppercaseFirstKeyFilter', 'josegonzalez\\Dotenv\\Filter\\UnderscoreArrayFilter', function ($data) {
        $keys = ['Debug' => 'debug', 'Email.transport' => 'EmailTransport', 'Database.debug.kit' => 'Datasources.debug_kit', 'Database.test' => 'Datasources.test', 'Database' => 'Datasources.default', 'Cache.duration' => null, 'Cache.cakemodel' => 'Cache._cake_model_', 'Cache.cakecore' => 'Cache._cake_core_'];
        foreach ($keys as $key => $newKey) {
            if ($newKey === null) {
                $data = Hash::remove($data, $key);
                continue;
            }
            $value = Hash::get($data, $key);
            $data = Hash::remove($data, $key);
            $data = Hash::insert($data, $newKey, $value);
        }
        foreach ($data['Email'] as $key => $config) {
            if (isset($config['profile'])) {
                parse_str($config['profile'], $output);
                $data['Email'][$key] = array_merge($output, $data['Email'][$key]);
                unset($data['Email'][$key]['profile'], $output);
            }
        }
        return $data;
    }]);
    $dotenv->parse();
    $dotenv->filter();
    $config = $dotenv->toArray();
}
Example #14
0
<?php

use josegonzalez\Dotenv\Loader as Dotenv;
use Radar\Adr\Boot;
use Relay\Middleware\ExceptionHandler;
use Relay\Middleware\ResponseSender;
use Zend\Diactoros\Response;
use Zend\Diactoros\ServerRequestFactory;
require_once '../db.php';
/**
 * Bootstrapping
 */
require '../vendor/autoload.php';
Dotenv::load(['filepath' => dirname(__DIR__) . DIRECTORY_SEPARATOR . '.env', 'toEnv' => true]);
$boot = new Boot();
$adr = $boot->adr();
/**
 * Middleware
 */
$adr->middle(new ResponseSender());
$adr->middle(new ExceptionHandler(new Response()));
$adr->middle('Radar\\Adr\\Handler\\RoutingHandler');
$adr->middle('Radar\\Adr\\Handler\\ActionHandler');
/**
 * Routes
 */
// Just gets all the names of users in the database
$adr->get('AllUserNames', '/allUserNames', function (array $input) {
    global $conn;
    // the database connection I know globals are bad but I'm pretty new at this
    $sql = "SELECT `name` FROM `user`";
Example #15
0
 /**
  * Pushes (uploads) files to ShootProof from the specified local directory
  *
  * @param string $dir The directory to process
  * @param Options $baseOptions
  * @param OptionsFactory $optionsFactory
  */
 protected function processDirectory($dir, Options $baseOptions, OptionsFactory $optionsFactory)
 {
     // Reload the options and read the directory config file
     $options = $optionsFactory->newInstance([], $this->getValidators(), $this->getDefaults());
     $configPath = new TildeExpander($dir) . '/.shootproof';
     $configLoader = new DotenvLoader((string) $configPath);
     try {
         $configData = $configLoader->parse()->toArray();
         $options->loadOptionData($configData, false);
         // don't overwrite CLI data
         $this->logger->addDebug('Config file found', [$configPath, $configData]);
     } catch (\InvalidArgumentException $e) {
         // ignore
         $this->logger->addDebug('Config file not found', [$configPath]);
     }
     // Make sure all required options are present
     $options->validateAllRequired();
     // Get local file list
     $localFiles = array_map('basename', $this->getFileList($dir));
     $eventId = $options->event ? $options->event : null;
     $albumId = $options->album ? $options->album : null;
     // Get remote file list
     switch ($options->target) {
         case 'album':
             // Create the album
             if (!$albumId) {
                 list($eventId, $albumId) = $this->createAlbum($options, basename($dir));
             }
             $this->logger->addDebug('Fetching album photos', [$albumId]);
             if ($baseOptions->preview) {
                 $remoteFiles = new \ArrayObject();
             } else {
                 $remoteFiles = new ResultPager(function ($page) use($albumId) {
                     $response = $this->api->getAlbumPhotos($albumId, $page + 1);
                     return [(int) $response['total_pages'], $response['photos']];
                 });
             }
             break;
         case 'event':
             // Create the event
             if (!$eventId) {
                 $eventId = $this->createEvent($options, basename($dir));
             }
             $this->logger->addDebug('Fetching event photos', [$eventId]);
             if ($baseOptions->preview) {
                 $remoteFiles = new \ArrayObject();
             } else {
                 $remoteFiles = new ResultPager(function ($page) use($eventId) {
                     $response = $this->api->getEventPhotos($eventId, $page + 1);
                     return [(int) $response['total_pages'], $response['photos']];
                 });
             }
             break;
     }
     // Turn the response into an array of stringifiable objects so we can compare file names
     $remoteFiles = array_map([new ShootProofFile(), 'arrayFactory'], $remoteFiles->getArrayCopy());
     // Compute files to add, remove, and replace
     $calculator = new FileSetCalculator($localFiles, $remoteFiles, $options->replace);
     foreach ($calculator->add() as $file) {
         $filePath = $dir . DIRECTORY_SEPARATOR . $file;
         $this->logger->addNotice('Uploading new file to ShootProof', [$filePath]);
         if (!$baseOptions->preview) {
             $this->uploadFile($filePath, $eventId, $albumId, $options->retryLimit);
         }
     }
     foreach ($calculator->remove() as $file) {
         $this->logger->addNotice('Deleting remote file', [$file->getId(), (string) $file]);
         if (!$baseOptions->preview) {
             $this->deleteFile($file->getId(), $options->retryLimit);
         }
     }
     foreach ($calculator->replace() as $file) {
         $filePath = $dir . DIRECTORY_SEPARATOR . $file;
         $this->logger->addNotice('Replacing remote file', [$file->getId(), $filePath]);
         if (!$baseOptions->preview) {
             $this->updateFile($filePath, $file->getId(), $options->retryLimit);
         }
     }
     // Write ShootProof metadata to the directory
     try {
         $writer = new ConfigWriter(['target' => $options->target, 'event' => $eventId, 'album' => $albumId]);
         if (!$baseOptions->preview) {
             $writer->write($configPath);
         }
         $this->logger->addDebug('ShootProof settings file saved', [$configPath]);
     } catch (\InvalidArgumentException $e) {
         $this->logger->addWarning('ShootProof settings file is unwritable', [$configPath]);
     } catch (\RuntimeException $e) {
         $this->logger->addWarning('Failed writing ShootProof settings file', [$configPath]);
     }
 }
Example #16
0
 /**
  * Pulls (downloads) files from ShootProof to the specified local directory
  *
  * @param string $dir The directory to process
  * @param Options $baseOptions
  * @param OptionsFactory $optionsFactory
  * @throws ValidatorException if event or album options are not provided
  */
 protected function processDirectory($dir, Options $baseOptions, OptionsFactory $optionsFactory)
 {
     // If the directory doesn't exist, create it and any parent dirs
     if (!file_exists($dir)) {
         if ($baseOptions->preview || @mkdir($dir, 0777, true)) {
             $this->logger->addNotice('Created directory', [$dir]);
         } else {
             $this->logger->addError('Failed to create directory', [$dir]);
             return;
         }
     }
     // Reload the options and read the directory config file
     $options = $optionsFactory->newInstance([], $this->getValidators(), $this->getDefaults());
     $configPath = new TildeExpander($dir) . '/.shootproof';
     $configLoader = new DotenvLoader((string) $configPath);
     try {
         $configData = $configLoader->parse()->toArray();
         $options->loadOptionData($configData, false);
         // don't overwrite CLI data
         $this->logger->addDebug('ShootProof settings file found', [$configPath, $configData]);
     } catch (\InvalidArgumentException $e) {
         // ignore
         $this->logger->addDebug('ShootProof settings file not found', [$configPath]);
     }
     // Make sure all required options are present
     $options->validateAllRequired();
     if (!$options->event && !$options->album) {
         throw new ValidatorException('Either --event or --album is required');
     }
     // Get local file list
     $localFiles = array_map('basename', $this->getFileList($dir));
     // Get remote file list
     switch ($options->target) {
         case 'album':
             $this->logger->addDebug('Fetching album photos', [$options->album]);
             $remoteFiles = new ResultPager(function ($page) use($options) {
                 $response = $this->api->getAlbumPhotos($options->album, $page + 1);
                 return [(int) $response['total_pages'], $response['photos']];
             });
             break;
         case 'event':
             $this->logger->addDebug('Fetching event photos', [$options->event]);
             $remoteFiles = new ResultPager(function ($page) use($options) {
                 $response = $this->api->getEventPhotos($options->event, $page + 1);
                 return [(int) $response['total_pages'], $response['photos']];
             });
             break;
     }
     // Turn the response into an array of stringifiable objects so we can compare file names
     $remoteFiles = array_map([new ShootProofFile(), 'arrayFactory'], $remoteFiles->getArrayCopy());
     // Compute files to add, remove, and replace
     $calculator = new FileSetCalculator($remoteFiles, $localFiles, $options->replace);
     foreach ($calculator->add() as $file) {
         // download
         $filePath = $dir . DIRECTORY_SEPARATOR . $file;
         $this->logger->addNotice('Downloading new file from ShootProof', [$filePath]);
         if (!$baseOptions->preview) {
             $this->downloadFile($file->getUrl('original'), $filePath, $baseOptions);
         }
     }
     foreach ($calculator->remove() as $file) {
         $filePath = $dir . DIRECTORY_SEPARATOR . $file;
         $this->logger->addNotice('Deleting local file', [$filePath]);
         if (!$baseOptions->preview) {
             @unlink($filePath);
         }
     }
     foreach ($calculator->replace() as $file) {
         $filePath = $dir . DIRECTORY_SEPARATOR . $file;
         $this->logger->addNotice('Replacing local file', [$filePath]);
         if (!$baseOptions->preview) {
             @unlink($filePath);
             $this->downloadFile($file->getUrl('original'), $filePath, $baseOptions);
         }
     }
     // Write ShootProof metadata to the directory
     try {
         $writer = new ConfigWriter(['target' => $options->target, $options->target => $options->{$options->target}]);
         if (!$baseOptions->preview) {
             $writer->write($configPath);
         }
         $this->logger->addDebug('ShootProof settings file saved', [$configPath]);
     } catch (\InvalidArgumentException $e) {
         $this->logger->addWarning('ShootProof settings file is unwritable', [$configPath]);
     } catch (\RuntimeException $e) {
         $this->logger->addWarning('Failed writing ShootProof settings file', [$configPath]);
     }
 }
Example #17
0
<?php

use josegonzalez\Dotenv\Loader as DotenvLoader;
use Symfony\Component\ClassLoader\ApcClassLoader;
use Symfony\Component\Debug\Debug;
use Symfony\Component\HttpFoundation\Request;
/**
 * @var Composer\Autoload\ClassLoader
 */
$loader = (require __DIR__ . '/../app/autoload.php');
// include_once __DIR__.'/../app/bootstrap.php.cache';
DotenvLoader::load(['filepath' => __DIR__ . '/../.env', 'putenv' => true, 'toEnv' => true, 'toServer' => true]);
if ('prod' === $_SERVER['SYMFONY_ENV'] && extension_loaded('apc')) {
    $apcLoader = new ApcClassLoader(sha1(__FILE__), $loader);
    $loader->unregister();
    $apcLoader->register(true);
}
if ('dev' === $_SERVER['SYMFONY_ENV']) {
    Debug::enable();
}
$kernel = new AppKernel($_SERVER['SYMFONY_ENV'], (bool) $_SERVER['SYMFONY_DEBUG']);
// $kernel->loadClassCache();
if ('prod' === $_SERVER['SYMFONY_ENV'] && true === (bool) $_SERVER['SYMFONY___USE_REVERSE_PROXY']) {
    $kernel = new AppCache($kernel);
    Request::enableHttpMethodParameterOverride();
}
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
Example #18
0
<?php

use josegonzalez\Dotenv\Loader as Dotenv;
require dirname(__DIR__) . '/vendor/autoload.php';
Dotenv::load(['filepath' => dirname(__DIR__) . '/.env', 'expect' => ['DB_DSN', 'DB_USER'], 'toEnv' => true]);
preg_match("/(.*?):(.*)/", $_ENV['DB_DSN'], $parts);
$type = $parts[1];
preg_match("/host=(\\w+)/", $_ENV['DB_DSN'], $parts);
$host = $parts[1];
preg_match("/dbname=(\\w+)/", $_ENV['DB_DSN'], $parts);
$dbName = $parts[1];
$dsn = sprintf('%s:host=%s', $type, $host);
try {
    $pdo = new \PDO($dsn, $_ENV['DB_USER'], $_ENV['DB_PASS']);
    $pdo->exec("CREATE DATABASE IF NOT EXISTS {$dbName}");
    $pdo->exec("CREATE DATABASE IF NOT EXISTS {$dbName}_test");
    error_log("Database [{$dbName}] and [{$dbName}_test] are created.");
} catch (PDOException $e) {
    echo $e->getMessage() . PHP_EOL;
    exit(1);
}
 /**
  * Changes the access level for a ShootProof gallery (event)
  *
  * If no event option is specified and a .shootproof file exists in the
  * directory, then event will be read from that file.
  *
  * @param string $dir The directory to process
  * @param Options $baseOptions
  * @param OptionsFactory $optionsFactory
  */
 protected function processDirectory($dir, Options $baseOptions, OptionsFactory $optionsFactory)
 {
     // Reload the options and read the directory config file
     $options = $optionsFactory->newInstance([], $this->getValidators());
     $configPath = new TildeExpander($dir) . '/.shootproof';
     $configLoader = new DotenvLoader((string) $configPath);
     try {
         $configData = $configLoader->parse()->toArray();
         $options->loadOptionData($configData, false);
         // don't overwrite CLI data
         $this->logger->addDebug('ShootProof settings file found', [$configPath, $configData]);
     } catch (\InvalidArgumentException $e) {
         // ignore
         $this->logger->addDebug('ShootProof settings file not found', [$configPath]);
     }
     // Make sure all required options are present
     $options->validateAllRequired();
     $options->validate('password', $options->password);
     // Set the event access level
     $this->logger->addNotice('Setting access level', ['event' => $options->event, 'level' => $options->accessLevel, 'password' => $options->password ? str_repeat('*', strlen($options->password)) : null]);
     if (!$baseOptions->preview) {
         $result = $this->api->setEventAccessLevel($options->event, $options->accessLevel, $options->password);
         $this->logger->addDebug('Operation completed', $result);
     }
 }