While connections can be added and removed dynamically during the course of your application (using Connections::add()), it is most typical to define all connections at once, in config/bootstrap/connections.php. The Connections class handles adapter classes efficiently by only loading adapter classes and creating instances when they are requested (using Connections::get()). Adapters are usually subclasses of lithium\data\Source.
See also: lithium\data\Source
Inheritance: extends lithium\core\Adaptable
Esempio n. 1
0
	public function skip() {
		$isAvailable = (
			Connections::get('test', array('config' => true)) &&
			Connections::get('test')->isConnected(array('autoConnect' => true))
		);
		$this->skipIf(!$isAvailable, "No test connection available");
	}
Esempio n. 2
0
 /**
  * Check request reCAPTCHA validity
  * This method return `true` or `false` after validation, and set error in
  * helper. If `true` error is set to null, otherwise `'incorrect-captcha-sol'`
  * 
  * Example:
  * {{{
  *		class YourController extends \lithium\action\Controller {
  *			public function index() {
  *				if ($this->request->data) {
  *					if (!Recaptcha::check($this->request)) {
  *						return;
  *					}
  *				}
  *			}
  *		}
  * }}}
  * @param object $request Pass request object to check method
  * @return boolean
  * @throws ConfigException
  * @throws RuntimeException 
  */
 public static function check(\lithium\net\http\Request $request)
 {
     $config = Libraries::get('li3_recaptcha', 'keys');
     if (!$config['private']) {
         throw new ConfigException('To use reCAPTCHA you must get API key from' . 'https://www.google.com/recaptcha/admin/create');
     }
     if (!$request->env('SERVER_ADDR')) {
         throw new RuntimeException('For security reasons, you must pass the remote ip to reCAPTCHA');
     }
     $data = array('privatekey' => $config['private'], 'remoteip' => $request->env('SERVER_ADDR'), 'challenge' => null, 'response' => null);
     if ($request->data) {
         $data['challenge'] = $request->data['recaptcha_challenge_field'];
         $data['response'] = $request->data['recaptcha_response_field'];
     }
     if (!$data['challenge'] || !$data['response']) {
         RecaptchaHelper::$error = 'incorrect-captcha-sol';
         return false;
     }
     $service = Connections::get('recaptcha');
     $serviceRespond = explode("\n", $service->post('/recaptcha/api/verify', $data));
     if ($serviceRespond[0] == 'true') {
         RecaptchaHelper::$error = null;
         return true;
     } else {
         RecaptchaHelper::$error = 'incorrect-captcha-sol';
         return false;
     }
 }
 public static function __init(array $options = array())
 {
     parent::__init($options);
     $self = static::_instance();
     $self->_finders['count'] = function ($self, $params, $chain) use(&$query, &$classes) {
         $db = Connections::get($self::meta('connection'));
         $records = $db->read('SELECT count(*) as count FROM posts', array('return' => 'array'));
         return $records[0]['count'];
     };
     Post::applyFilter('save', function ($self, $params, $chain) {
         $post = $params['record'];
         if (!$post->id) {
             $post->created = date('Y-m-d H:i:s');
         } else {
             $post->modified = date('Y-m-d H:i:s');
         }
         $params['record'] = $post;
         return $chain->next($self, $params, $chain);
     });
     Validator::add('isUniqueTitle', function ($value, $format, $options) {
         $conditions = array('title' => $value);
         // If editing the post, skip the current psot
         if (isset($options['values']['id'])) {
             $conditions[] = 'id != ' . $options['values']['id'];
         }
         // Lookup for posts with same title
         return !Post::find('first', array('conditions' => $conditions));
     });
 }
 /**
  * Skip the test if a Sqlite adapter configuration is unavailable.
  *
  * @return void
  * @todo Tie into the Environment class to ensure that the test database is being used.
  */
 public function skip()
 {
     $this->_dbConfig = Connections::get('sqlite3', array('config' => true));
     $hasDb = isset($this->_dbConfig['adapter']) && $this->_dbConfig['adapter'] == 'Sqlite3';
     $message = 'Test database is either unavailable, or not using a Sqlite adapter';
     $this->skipIf(!$hasDb, $message);
 }
 public function testStreamConnection()
 {
     $config = array('socket' => 'Stream', 'host' => 'localhost', 'login' => 'root', 'password' => '', 'port' => '80');
     Connections::add('stream-test', 'Http', $config);
     $result = Connections::get('stream-test');
     $this->assertTrue($result instanceof \lithium\data\source\Http);
 }
Esempio n. 6
0
 public function testBasicGet()
 {
     $topsy = Connections::get('test-topsy');
     $headers = array('Content-Type' => 'application/json');
     $results = json_decode($topsy->connection->get('authorinfo.json?url=http://twitter.com/mehlah', array(), compact('headers')));
     $this->assertEqual('Mehdi Lahmam B.', $results->response->name);
 }
Esempio n. 7
0
 /**
  * Skip the test if no `test` CouchDb connection available.
  *
  * @return void
  */
 public function skip()
 {
     $isAvailable = Connections::get('test', array('config' => true)) && Connections::get('test')->isConnected(array('autoConnect' => true));
     $this->skipIf(!$isAvailable, "No test connection available");
     $couchConnection = strpos(get_class(Connections::get('test')), 'CouchDb');
     $this->skipIf(!$couchConnection, "Test connection is not CouchDb");
 }
Esempio n. 8
0
 /**
  * Skip the test if no test database connection available.
  */
 public function skip()
 {
     $dbConfig = Connections::get($this->_connection, ['config' => true]);
     $isAvailable = $dbConfig && Connections::get($this->_connection)->isConnected(['autoConnect' => true]);
     $this->skipIf(!$isAvailable, "No {$this->_connection} connection available.");
     $db = Connections::get($this->_connection);
     $this->skipIf(!$db instanceof Database, "The {$this->_connection} connection is not a relational database.");
 }
Esempio n. 9
0
 public function tearDown()
 {
     $connection = Connections::get('default');
     $mongo = $connection->connection;
     foreach ($mongo->listCollections() as $collection) {
         $collection->drop();
     }
 }
Esempio n. 10
0
 /**
  * Skip the test if a MySQL adapter configuration is unavailable.
  *
  * @return void
  * @todo Tie into the Environment class to ensure that the test database is being used.
  */
 public function skip()
 {
     $this->skipIf(!MySql::enabled(), 'MySQL Extension is not loaded');
     $this->_dbConfig = Connections::get('test', array('config' => true));
     $hasDb = isset($this->_dbConfig['adapter']) && $this->_dbConfig['adapter'] == 'MySql';
     $message = 'Test database is either unavailable, or not using a MySQL adapter';
     $this->skipIf(!$hasDb, $message);
 }
Esempio n. 11
0
 public function skip()
 {
     $connection = $this->_connection;
     $this->_dbConfig = Connections::get($this->_connection, array('config' => true));
     $this->skipIf(!$this->with(array('Sqlite3')));
     $this->_db = new MockSqlite3($this->_dbConfig);
     $isConnected = $this->_db->isConnected(array('autoConnect' => true));
     $this->skipIf(!$isConnected, "No {$connection} connection available.");
 }
Esempio n. 12
0
 /**
  * Tests Collection accessors (getters/setters).
  */
 public function testAccessorMethods()
 {
     Connections::config(array('mock-source' => array('type' => 'lithium\\tests\\mocks\\data\\MockSource')));
     $model = $this->_model;
     $model::config(array('connection' => false, 'key' => 'id'));
     $collection = new DocumentSet(compact('model'));
     $this->assertEqual($model, $collection->model());
     $this->assertEqual(compact('model'), $collection->meta());
 }
Esempio n. 13
0
 public function connect($connection, $options = array())
 {
     $options += array('autoConnect' => true);
     $this->_dbConfig = Connections::get($connection, array('config' => true));
     $db = $this->_db = Connections::get($connection);
     $this->skipIf(!$db, "The `{$connection}` connection is not correctly configured.");
     $this->skipIf(!$db::enabled(), 'Extension is not loaded.');
     $this->skipIf(!$db->isConnected($options), "No `{$connection}` connection available.");
 }
Esempio n. 14
0
 public function testIssuesRead()
 {
     $gh = Connections::get('test-gh');
     $query = new Query(array('model' => $this->_models['issues']));
     $results = $gh->read($query);
     $expected = 'octocat';
     $result = $results->first();
     $this->assertEqual($expected, $result->user->login);
 }
Esempio n. 15
0
 public function skip()
 {
     $connection = 'lithium_mysql_test';
     $this->_dbConfig = Connections::get($connection, array('config' => true));
     $isAvailable = $this->_dbConfig && Connections::get($connection)->isConnected(array('autoConnect' => true));
     $this->skipIf(!$isAvailable, "No {$connection} connection available.");
     $this->db = Connections::get($connection);
     $this->skipIf(!$this->db instanceof Database, "The {$connection} connection is not a relational database.");
 }
Esempio n. 16
0
 /**
  * Skip the test if a MySQL adapter configuration is unavailable.
  *
  * @return void
  * @todo Tie into the Environment class to ensure that the test database is being used.
  */
 public function skip()
 {
     $message = 'MySQLi extension is not available for testing the adapter.';
     $hasClass = class_exists('\\mysqli');
     $this->skipIf(!$hasClass, $message);
     $this->_dbConfig = Connections::get('MySQLi-tests', array('config' => true));
     $hasDb = isset($this->_dbConfig['adapter']) && $this->_dbConfig['adapter'] == 'MySQLi';
     $message = 'Test database is either unavailable, or not using a MySQLi adapter';
     $this->skipIf(!$hasDb, $message);
 }
 public function setUp()
 {
     $this->_backup['cwd'] = getcwd();
     $this->_backup['_SERVER'] = $_SERVER;
     $_SERVER['argv'] = array();
     Libraries::add('create_test', array('path' => $this->_testPath . '/create_test'));
     $this->request = new Request(array('input' => fopen('php://temp', 'w+')));
     $this->request->params = array('library' => 'create_test', 'action' => null);
     Connections::add('default', array('type' => null, 'adapter' => 'lithium\\tests\\mocks\\data\\model\\MockDatabase'));
 }
Esempio n. 18
0
 public function tearDown()
 {
     Connections::remove('mockconn');
     MockQueryPost::reset();
     MockQueryComment::reset();
     MockGallery::reset();
     MockImage::reset();
     MockImageTag::reset();
     MockTag::reset();
 }
Esempio n. 19
0
 /**
  * Skip the test if no test database connection available.
  */
 public function skip()
 {
     $connection = 'lithium_couch_test';
     $config = Connections::get($connection, array('config' => true));
     $isAvailable = $config && Connections::get($connection)->isConnected(array('autoConnect' => true));
     $this->skipIf(!$isAvailable, "No {$connection} connection available.");
     $this->_key = Companies::key();
     $this->_database = $config['database'];
     $this->_connection = Connections::get($connection);
 }
 public function testConnectWithWrongPassword()
 {
     $config = $this->_dbConfig;
     $config['login'] = '******';
     $config['password'] = '******';
     $connection = 'wrong_passord';
     Connections::add($connection, $config);
     $this->expectException('/Host connected, but could not access database/');
     Connections::get($connection)->connect();
 }
Esempio n. 21
0
 /**
  * Skip the test if a Sqlite adapter configuration is unavailable.
  *
  * @return void
  * @todo Tie into the Environment class to ensure that the test database is being used.
  */
 public function skip()
 {
     $this->skipIf(!Sqlite3::enabled(), 'Sqlite3 adapter is not enabled.');
     $this->_dbConfig = Connections::get('test', array('config' => true));
     $hasDb = isset($this->_dbConfig['adapter']) && $this->_dbConfig['adapter'] == 'Sqlite3';
     $message = 'Test database is either unavailable, or not using a Sqlite3 adapter';
     $this->skipIf(!$hasDb, $message);
     $isMemory = $this->_dbConfig['database'] == ':memory:';
     $message = "Test database is not an in-memory database.";
     $this->skipIf(!$isMemory, $message);
 }
Esempio n. 22
0
 /**
  * 添加数据库链接
  * @param string $name 名称
  * @param array $config 配置
  * @param bool $overwrite 是否覆盖已有配置,默认否
  * @return array
  */
 public static function add($name, array $config = array(), $overwrite = false)
 {
     if ($overwrite) {
         parent::add($name, $config);
     } else {
         if (!isset(static::$_configurations[$name])) {
             parent::add($name, $config);
         }
     }
     return static::$_configurations[$name];
 }
Esempio n. 23
0
 public function testConnectWithWrongPassword()
 {
     $this->skipIf(!$this->with('PostgreSql'));
     $config = $this->_dbConfig;
     $config['login'] = '******';
     $config['password'] = '******';
     $config['object'] = null;
     $connection = 'wrong_passord';
     Connections::add($connection, $config);
     $this->expectException();
     Connections::get($connection)->connect();
 }
Esempio n. 24
0
 public function tearDown()
 {
     Connections::remove('mockconn');
     MockDatabasePost::reset();
     MockDatabaseComment::reset();
     MockDatabaseTagging::reset();
     MockDatabasePostRevision::reset();
     MockGallery::reset();
     MockImage::reset();
     MockImageTag::reset();
     MockTag::reset();
 }
Esempio n. 25
0
 public static function __init(array $options = array())
 {
     parent::__init($options);
     $self = static::_object();
     #		$self = static::_instance(__CLASS__);
     #var_dump($self);
     $self->_finders['count'] = function ($self, $params, $chain) use(&$query, &$classes) {
         $db = Connections::get($self::meta('connection'));
         $records = $db->read('SELECT count(*) as count FROM posts', array('return' => 'array'));
         return $records[0]['count'];
     };
 }
Esempio n. 26
0
 public function tearDown()
 {
     Connections::remove('mocksource');
     Connections::remove('mockconn');
     MockPost::reset();
     MockTag::reset();
     MockComment::reset();
     MockCreator::reset();
     MockSubProduct::reset();
     MockProduct::reset();
     MockPostForValidates::reset();
 }
Esempio n. 27
0
 public function connections()
 {
     $data = Connections::get();
     $connections = new Collection(compact('data'));
     if (true || $this->request->is('json')) {
         $connections->each(function ($name) {
             $config = Connections::get($name, array('config' => true));
             unset($config['object']);
             return array_merge(compact('name'), Set::flatten($config));
         });
     }
     return compact('connections');
 }
Esempio n. 28
0
 /**
  * Skip the test if a MySQL adapter configuration is unavailable.
  * @todo Tie into the Environment class to ensure that the test database is being used.
  */
 public function skip()
 {
     $this->skipIf(!MySql::enabled(), 'MySQL Extension is not loaded');
     $this->_dbConfig = Connections::get('test', array('config' => true));
     $hasDb = isset($this->_dbConfig['adapter']) && $this->_dbConfig['adapter'] == 'MySql';
     $message = 'Test database is either unavailable, or not using a MySQL adapter';
     $this->skipIf(!$hasDb, $message);
     $this->db = new MySql($this->_dbConfig);
     $lithium = LITHIUM_LIBRARY_PATH . '/lithium';
     $sqlFile = $lithium . '/tests/mocks/data/source/database/adapter/mysql_companies.sql';
     $sql = file_get_contents($sqlFile);
     $this->db->read($sql, array('return' => 'resource'));
 }
Esempio n. 29
0
 public function skip()
 {
     $this->_dbConfig = Connections::get('test', array('config' => true));
     $isAvailable = $this->_dbConfig && Connections::get('test')->isConnected(array('autoConnect' => true));
     $this->skipIf(!$isAvailable, "No test connection available.");
     $isDatabase = Connections::get('test') instanceof Database;
     $this->skipIf(!$isDatabase, "The 'test' connection is not a relational database.");
     $this->db = Connections::get('test');
     $mockBase = LITHIUM_LIBRARY_PATH . '/lithium/tests/mocks/data/source/database/adapter/';
     $files = array('galleries' => '_galleries.sql', 'images' => '_images.sql');
     $files = array_diff_key($files, array_flip($this->db->sources()));
     foreach ($files as $file) {
         $sqlFile = $mockBase . strtolower($this->_dbConfig['adapter']) . $file;
         $this->skipIf(!file_exists($sqlFile), "SQL file {$sqlFile} does not exist.");
         $sql = file_get_contents($sqlFile);
         $this->db->read($sql, array('return' => 'resource'));
     }
 }
 public function index()
 {
     $fh = fopen("../resources/primary.csv", "r");
     $posts = $groups = 0;
     $connection = Connections::get('default')->connection;
     foreach (array('posts', 'groups', 'grants', 'grant_groups') as $collection) {
         $connection->{$collection}->remove(array());
     }
     while ($data = fgetcsv($fh)) {
         list($tmp, $postId, $desc, $y2011, $y2010, $y2009) = $data;
         if (!empty($tmp)) {
             /**
              * Keep track of group name
              */
             if (strpos($tmp, "Totalt") === false) {
                 $group = Group::create();
                 list($number, $name) = explode(" - ", $tmp);
                 $name = str_replace('"', "", trim($name));
                 $number = trim($number);
                 $group->save(array('name' => $name, 'number' => $number));
                 $groupId = $group->_id;
                 $groups++;
             } elseif ($group) {
                 $group->y2011 = (int) ($y2011 / 1000);
                 $group->y2010 = (int) ($y2010 / 1000);
                 $group->y2009 = (int) ($y2009 / 1000);
                 $group->save();
                 continue;
             }
         }
         /**
          * Place in previously mentioned group
          */
         if (isset($groupId)) {
             $post = Post::create();
             $post->save(array('post' => (double) $postId, 'desc' => trim($desc), 'y2011' => (int) ($y2011 / 1000), 'y2010' => (int) ($y2010 / 1000), 'y2009' => (int) ($y2009 / 1000), 'groupId' => $groupId));
             $posts++;
         }
     }
     // Grants
     return compact('groups', 'posts') + $this->grants();
 }