getInstance() public static method

public static getInstance ( )
コード例 #1
0
ファイル: BaseTestCase.php プロジェクト: azole/LazyRecord
 public static function createNeutralConfigLoader()
 {
     $config = ConfigLoader::getInstance();
     $config->loaded = true;
     $config->setConfigStash(array('schema' => array('auto_id' => true)));
     return $config;
 }
コード例 #2
0
ファイル: ModelTestCase.php プロジェクト: appleboy/LazyRecord
 public function setUp()
 {
     $annnotations = $this->getAnnotations();
     $configLoader = ConfigLoader::getInstance();
     $configLoader->loadFromSymbol(true);
     $configLoader->setDefaultDataSourceId($this->getDriverType());
     $connManager = ConnectionManager::getInstance();
     $connManager->init($configLoader);
     try {
         $dbh = $connManager->getConnection($this->getDriverType());
     } catch (PDOException $e) {
         if ($this->allowConnectionFailure) {
             $this->markTestSkipped(sprintf("Can not connect to database by data source '%s' message:'%s' config:'%s'", $this->getDriverType(), $e->getMessage(), var_export($configLoader->getDataSource($this->getDriverType()), true)));
             return;
         } else {
             echo sprintf("Can not connect to database by data source '%s' message:'%s' config:'%s'", $this->getDriverType(), $e->getMessage(), var_export($configLoader->getDataSource($this->getDriverType()), true));
             throw $e;
         }
     }
     $driver = $connManager->getQueryDriver($this->getDriverType());
     $this->assertInstanceOf('SQLBuilder\\Driver\\BaseDriver', $driver, 'QueryDriver object OK');
     // Rebuild means rebuild the database for new tests
     $rebuild = true;
     $basedata = true;
     if (isset($annnotations['method']['rebuild'][0]) && $annnotations['method']['rebuild'][0] == 'false') {
         $rebuild = false;
     }
     if (isset($annnotations['method']['basedata'][0]) && $annnotations['method']['basedata'][0] == 'false') {
         $basedata = false;
     }
     if ($rebuild) {
         $builder = SqlBuilder::create($driver, array('rebuild' => true));
         $this->assertNotNull($builder);
         // $schemas = ClassUtils::schema_classes_to_objects($this->getModels());
         $schemas = ClassUtils::schema_classes_to_objects($this->getModels());
         foreach ($schemas as $schema) {
             $sqls = $builder->build($schema);
             $this->assertNotEmpty($sqls);
             foreach ($sqls as $sql) {
                 $dbh->query($sql);
             }
         }
         if ($basedata) {
             $runner = new SeedBuilder($this->config, $this->logger);
             foreach ($schemas as $schema) {
                 $runner->buildSchemaSeeds($schema);
             }
             if ($scripts = $this->config->getSeedScripts()) {
                 foreach ($scripts as $script) {
                     $runner->buildScriptSeed($script);
                 }
             }
         }
     }
 }
コード例 #3
0
ファイル: BaseCommand.php プロジェクト: corneltek/lazyrecord
 public function getConfigLoader($required = true)
 {
     if (!$this->config) {
         $this->config = ConfigLoader::getInstance();
         $this->config->loadFromSymbol(true);
         // force loading
         if (!$this->config->isLoaded() && $required) {
             throw new RuntimeException("ConfigLoader did not loaded any config file. Can't initialize the settings.");
         }
     }
     return $this->config;
 }
コード例 #4
0
ファイル: DatabaseService.php プロジェクト: azole/Phifty
 public function register($kernel, $options = array())
 {
     $config = $kernel->config->stashes['database'];
     $loader = \LazyRecord\ConfigLoader::getInstance();
     if (!$loader->loaded) {
         $loader->load($config);
         $loader->init();
         // init data source and connection
     }
     $kernel->db = function () {
         return ConnectionManager::getInstance()->getConnection();
     };
 }
コード例 #5
0
 public function register(Kernel $kernel, $options = array())
 {
     // TODO: move to generate prepare...
     $loader = \LazyRecord\ConfigLoader::getInstance();
     if (!$loader->loaded) {
         $loader->load($this->config);
         $loader->init();
         // init data source and connection
     }
     $kernel->db = function () {
         return ConnectionManager::getInstance()->getConnection('default');
     };
 }
コード例 #6
0
 public function schemaProvider()
 {
     $loader = \LazyRecord\ConfigLoader::getInstance();
     $loader->loadFromArray(array('bootstrap' => array('tests/bootstrap.php'), 'schema' => array('auto_id' => 1, 'paths' => array('tests/TestApp')), 'data_sources' => array('default' => array('dsn' => 'sqlite::memory:', 'user' => NULL, 'pass' => NULL), 'pgsql' => array('dsn' => 'pgsql:host=localhost;dbname=testing', 'user' => 'postgres'))));
     // force loading
     $g = $this->createSchemaGenerator();
     $schemas = array();
     $schemas[] = [$g, new \TestApp\Model\UserSchema()];
     $schemas[] = [$g, new \AuthorBooks\Model\AddressSchema()];
     $schemas[] = [$g, new \AuthorBooks\Model\BookSchema()];
     $schemas[] = [$g, new \TestApp\Model\IDNumberSchema()];
     $schemas[] = [$g, new \TestApp\Model\NameSchema()];
     return $schemas;
 }
コード例 #7
0
ファイル: DeclareSchema.php プロジェクト: appleboy/LazyRecord
 /**
  * Build schema
  */
 protected function build(array $options = array())
 {
     $this->schema($options);
     // postSchema is added for mixin that needs all schema information, for example LocalizeMixin
     foreach ($this->mixinSchemas as $mixin) {
         $mixin->postSchema();
     }
     $this->primaryKey = $this->findPrimaryKey();
     // if the primary key is not define, we should append the default primary key => id
     // AUTOINCREMENT is only allowed on an INTEGER PRIMARY KEY
     if (null === $this->primaryKey) {
         if ($config = ConfigLoader::getInstance()) {
             if ($config->hasAutoId() && !isset($this->columns['id'])) {
                 $this->insertAutoIdColumn();
             }
         }
     }
 }
コード例 #8
0
 public function insertIntoDataSource($schema)
 {
     $connManager = LazyRecord\ConnectionManager::getInstance();
     $configLoader = ConfigLoader::getInstance();
     $configLoader->loadFromSymbol(true);
     $connManager->init($configLoader);
     $pdo = $connManager->getConnection(self::getCurrentDriverType());
     $this->assertInstanceOf('PDO', $pdo);
     $queryDriver = $connManager->getQueryDriver(self::getCurrentDriverType());
     $builder = SqlBuilder::create($queryDriver, array('rebuild' => true));
     $builder->build($schema);
     $sqls = $builder->build($schema);
     $this->assertNotEmpty($sqls);
     foreach ($sqls as $sql) {
         $this->assertQueryOK($pdo, $sql);
     }
     $this->assertTableExists($pdo, $schema->getTable());
 }
コード例 #9
0
 public function execute()
 {
     $logger = $this->getLogger();
     $options = $this->getOptions();
     $this->logger->debug("Loading config");
     $loader = ConfigLoader::getInstance();
     $loader->loadFromSymbol(true);
     $loader->initForBuild();
     $this->logger->debug("Initializing schema generator...");
     $generator = new SchemaGenerator($loader, $logger);
     $args = func_get_args();
     $classes = Utils::findSchemasByArguments($loader, $args, $this->logger);
     foreach ($classes as $class) {
         $rfc = new ReflectionClass($class);
         $this->logger->info(sprintf("  %-50s %s", $class, $rfc->getFilename()));
     }
     $logger->info('Done');
 }
コード例 #10
0
 public function __construct()
 {
     $this['config_loader'] = function ($c) {
         $config = ConfigLoader::getInstance();
         $config->loadFromSymbol(true);
         // force loading
         if ($config->isLoaded()) {
             $config->initForBuild();
         }
         return $config;
     };
     $this['logger'] = function ($c) {
         return Console::getInstance()->getLogger();
     };
     $this['schema_finder'] = function ($c) {
         $finder = new SchemaFinder();
         $finder->paths = $c['config_loader']->getSchemaPaths() ?: [];
         return $finder;
     };
 }
コード例 #11
0
ファイル: BuildConfCommand.php プロジェクト: azole/LazyRecord
 public function execute($configFile = null)
 {
     /**
      * $ lazy bulid-conf config/lazy.yml phifty/config/lazy.yml
      * 
      * build/lazy/config.php   # is generated
      */
     if (!$configFile) {
         $possiblePaths = array('db/config/site_database.yml', 'db/config/database.yml', 'config/database.yml', 'config/site_database.yml');
         foreach ($possiblePaths as $path) {
             if (file_exists($path)) {
                 $this->logger->info("Found default config file: {$path}");
                 $configFile = $path;
                 ConfigLoader::compile($configFile);
             }
         }
     }
     if (!$configFile) {
         throw new Exception("config file path is required.");
     }
     $this->logger->info("Building config from {$configFile}");
     $dir = dirname($configFile);
     ConfigLoader::compile($configFile);
     // make master config link
     $loader = ConfigLoader::getInstance();
     if (file_exists($loader->symbolFilename)) {
         $this->logger->info('Cleaning up symbol link');
         unlink($loader->symbolFilename);
     }
     if (file_exists('.lazy.php')) {
         $this->logger->info('Cleaning up symbol link');
         unlink('.lazy.php');
     }
     $this->logger->info("Making link => " . $loader->symbolFilename);
     if (cross_symlink($configFile, $loader->symbolFilename) === false) {
         $this->logger->error("Config linking failed.");
     }
     $this->logger->info("Done.");
 }
コード例 #12
0
 public function execute($configFile = null)
 {
     /*
      * $ lazy bulid-conf config/lazy.yml phifty/config/lazy.yml
      * 
      * build/lazy/config.php   # is generated
      */
     if (!$configFile && $this->options->{'search'}) {
         $possiblePaths = array('db/config/site_database.yml', 'db/config/database.yml', 'config/database.yml', 'config/site_database.yml');
         foreach ($possiblePaths as $path) {
             if (file_exists($path)) {
                 $this->logger->info("Found default config file: {$path}");
                 $configFile = $path;
                 ConfigLoader::compile($configFile);
             }
         }
     }
     if (!$configFile) {
         throw new Exception('config file is required.');
     }
     $this->logger->info("Building config from {$configFile}");
     $dir = dirname($configFile);
     ConfigLoader::compile($configFile, $this->options->force);
     // make master config link
     $loader = ConfigLoader::getInstance();
     $cleanup = [$loader->symbolFilename, '.lazy.php', '.lazy.yml'];
     foreach ($cleanup as $symlink) {
         if (file_exists($symlink)) {
             $this->logger->debug('Cleaning up symbol link: ' . $symlink);
             unlink($symlink);
         }
     }
     $this->logger->info('Creating symbol link: ' . $loader->symbolFilename . ' -> ' . $configFile);
     if (cross_symlink($configFile, $loader->symbolFilename) === false) {
         $this->logger->error('Config linking failed.');
     }
     $this->logger->info('Done');
 }
コード例 #13
0
    public function execute()
    {
        $logger = $this->getLogger();
        $configFile = $this->options->config ?: 'db/config/database.yml';
        if (file_exists($configFile)) {
            $logger->info("Config file {$configFile} already exists.");
            return;
        }
        $driver = $this->options->driver ?: $this->ask('Database driver [sqlite]', array('sqlite', 'pgsql', 'mysql', null)) ?: 'sqlite';
        $dbName = $this->options->database ?: $this->ask('Database name [:memory:]') ?: ':memory:';
        $logger->info("Using {$driver} driver");
        $logger->info("Using database {$dbName}");
        $user = '';
        $password = '';
        if ($driver != 'sqlite') {
            // FIXME: fix DSN for sqlite, "sqlite:mydb.sqlite3" doesn't require dbname= ...
            $user = $this->options->username ?: $this->ask('Database user');
            $password = $this->options->password ?: $this->ask('Database password');
        }
        $logger->info('Creating config file skeleton...');
        $content = <<<EOS
---
bootstrap:
- vendor/autoload.php
schema:
  # Insert auto-increment primary key to every schema classes
  auto_id: true
  # Customize your schema class loader
  #
  # loader: custom_schema_loader.php
  #  Customize your schema paths
  # paths:
  # - src
data_source:
  default: master
  nodes:
    master:
      driver: {$driver}
      database: {$dbName}
      user: {$user}
      pass: {$password}
EOS;
        if (file_put_contents($configFile, $content) !== false) {
            $logger->info("Config file is generated: {$configFile}");
            $logger->info('Please run build-conf to compile php format config file.');
        }
        $this->logger->info("Building config from {$configFile}");
        $dir = dirname($configFile);
        ConfigLoader::compile($configFile, true);
        // make master config link
        $loader = ConfigLoader::getInstance();
        $cleanup = [$loader->symbolFilename, '.lazy.php', '.lazy.yml'];
        foreach ($cleanup as $symlink) {
            if (file_exists($symlink)) {
                $this->logger->debug('Cleaning up symbol link: ' . $symlink);
                unlink($symlink);
            }
        }
        $this->logger->info('Creating symbol link: ' . $loader->symbolFilename . ' -> ' . $configFile);
        if (cross_symlink($configFile, $loader->symbolFilename) === false) {
            $this->logger->error('Config linking failed.');
        }
        $this->logger->info('Done');
    }
コード例 #14
0
 public function createSchemaGenerator()
 {
     $g = new \LazyRecord\Schema\SchemaGenerator(ConfigLoader::getInstance(), Logger::getInstance());
     $g->forceUpdate = true;
     return $g;
 }
コード例 #15
0
ファイル: bootstrap.php プロジェクト: appleboy/LazyRecord
<?php

$loader = (require "vendor/autoload.php");
require "tests/model_helpers.php";
mb_internal_encoding('UTF-8');
error_reporting(E_ALL);
$loader->add(null, 'tests');
$loader->add(null, 'tests/src');
use LazyRecord\Schema\SchemaGenerator;
use LazyRecord\ConfigLoader;
use CLIFramework\Logger;
$config = ConfigLoader::getInstance();
$config->loadFromSymbol(true);
$config->initForBuild();
$logger = new Logger();
$logger->quiet();
$logger->info("Building schema class files...");
// build schema class files
$schemas = array(new \AuthorBooks\Model\AddressSchema(), new \AuthorBooks\Model\AuthorBookSchema(), new \AuthorBooks\Model\AuthorSchema(), new \AuthorBooks\Model\BookSchema(), new \AuthorBooks\Model\PublisherSchema(), new \AuthorBooks\Model\TagSchema(), new \MetricApp\Model\MetricValueSchema(), new \PageApp\Model\PageSchema(), new \StoreApp\Model\StoreSchema(), new \TestApp\Model\EdmSchema(), new \TestApp\Model\IDNumberSchema(), new \TestApp\Model\NameSchema(), new \TestApp\Model\PostSchema(), new \TestApp\Model\TableSchema(), new \TestApp\Model\UserSchema(), new \TestApp\Model\WineCategorySchema(), new \TestApp\Model\WineSchema());
$g = new \LazyRecord\Schema\SchemaGenerator($config, $logger);
$g->setForceUpdate(true);
$g->generate($schemas, true);
// $logger->info("Starting tests...");
コード例 #16
0
ファイル: BaseModel.php プロジェクト: appleboy/LazyRecord
 public static function getCacheInstance()
 {
     if (self::$_cacheInstance) {
         return self::$_cacheInstance;
     }
     return self::$_cacheInstance = ConfigLoader::getInstance()->getCacheInstance();
 }
コード例 #17
0
ファイル: BaseTestCase.php プロジェクト: appleboy/LazyRecord
 public function __construct($name = NULL, array $data = array(), $dataName = '')
 {
     parent::__construct($name, $data, $dataName);
     if (!extension_loaded('pdo')) {
         $this->markTestSkipped('pdo extension is required for model testing');
         return;
     }
     // free and override default connection
     ConnectionManager::getInstance()->free();
     $configLoader = ConfigLoader::getInstance();
     $configLoader->loadFromSymbol(true);
     $configLoader->setDefaultDataSourceId($this->getDriverType());
     $connManager = ConnectionManager::getInstance();
     $connManager->init($configLoader);
     // $config = self::createNeutralConfigLoader();
     $this->setConfig($configLoader);
     $this->logger = new Logger();
     $this->logger->setQuiet();
     if (method_exists($this, 'getModels')) {
         /*
         $generator = new SchemaGenerator($this->config, $this->logger);
         $schemas = ClassUtils::schema_classes_to_objects($this->getModels());
         $classMap = $generator->generate($schemas);
         */
     }
 }