Page MenuHomeDevCentral

No OneTemporary

diff --git a/includes/autoload.php b/includes/autoload.php
index a5b2453..f302f96 100644
--- a/includes/autoload.php
+++ b/includes/autoload.php
@@ -1,100 +1,103 @@
<?php
/**
* _, __, _, _ __, _ _, _, _
* / \ |_) (_ | | \ | /_\ |\ |
* \ / |_) , ) | |_/ | | | | \|
* ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
*
* Classes and interfaces auto loader
*
* @package ObsidianWorkspaces
* @filesource
*/
/**
* This SPL autoloader method is called when a class or an interface can't be loaded.
*/
function obsidian_autoload ($name) {
$dir = dirname(__DIR__);
///
/// Applications
///
if ($name == 'DocumentsApplication') { require $dir . '/apps/documents/DocumentsApplication.php'; return true; }
if ($name == 'DocumentsApplicationConfiguration') { require $dir . '/apps/documents/DocumentsApplicationConfiguration.php'; return true; }
if ($name == 'HelloWorldApplication') { require $dir . '/apps/helloworld/HelloWorldApplication.php'; return true; }
if ($name == 'MediaWikiMirrorApplication') { require $dir . '/apps/mediawikimirror/MediaWikiMirrorApplication.php'; return true; }
if ($name == 'MediaWikiMirrorApplicationConfiguration') { require $dir . '/apps/mediawikimirror/MediaWikiMirrorApplicationConfiguration.php'; return true; }
if ($name == 'StaticContentApplication') { require $dir . '/apps/staticcontent/StaticContentApplication.php'; return true; }
if ($name == 'StaticContentApplicationConfiguration') { require $dir . '/apps/staticcontent/StaticContentApplicationConfiguration.php'; return true; }
///
/// Core controllers
///
if ($name == 'ErrorPageController') { require $dir . '/controllers/errorpage.php'; return true; }
if ($name == 'FooterController') { require $dir . '/controllers/footer.php'; return true; }
if ($name == 'HeaderController') { require $dir . '/controllers/header.php'; return true; }
if ($name == 'HomepageController') { require $dir . '/controllers/home.php'; return true; }
///
/// Keruald and Obsidian Workspaces libraries
///
if ($name == 'Events') { require $dir . '/includes/Events.php'; return true; }
if ($name == 'LoadableWithContext') { require $dir . '/includes/LoadableWithContext.php'; return true; }
if ($name == 'ObjectDeserializable') { require $dir . '/includes/ObjectDeserializable.php'; return true; }
if ($name == 'ObjectDeserializableWithContext') { require $dir . '/includes/ObjectDeserializable.php'; return true; }
if ($name == 'Application') { require $dir . '/includes/apps/Application.php'; return true; }
if ($name == 'ApplicationConfiguration') { require $dir . '/includes/apps/ApplicationConfiguration.php'; return true; }
if ($name == 'ApplicationContext') { require $dir . '/includes/apps/ApplicationContext.php'; return true; }
if ($name == 'AddToGroupUserAction') { require $dir . '/includes/auth/AddToGroupUserAction.php'; return true; }
if ($name == 'AuthenticationMethod') { require $dir . '/includes/auth/AuthenticationMethod.php'; return true; }
if ($name == 'AzharProvider') { require $dir . '/includes/auth/AzharProvider.php'; return true; }
if ($name == 'GivePermissionUserAction') { require $dir . '/includes/auth/GivePermissionUserAction.php'; return true; }
if ($name == 'UserAction') { require $dir . '/includes/auth/UserAction.php'; return true; }
if ($name == 'Cache') { require $dir . '/includes/cache/cache.php'; return true; }
if ($name == 'CacheMemcached') { require $dir . '/includes/cache/memcached.php'; return true; }
if ($name == 'CacheVoid') { require $dir . '/includes/cache/void.php'; return true; }
if ($name == 'Collection') { require $dir . '/includes/collection/Collection.php'; return true; }
if ($name == 'CollectionDocument') { require $dir . '/includes/collection/CollectionDocument.php'; return true; }
if ($name == 'FilesCollection') { require $dir . '/includes/collection/FilesCollection.php'; return true; }
if ($name == 'MongoDBCollection') { require $dir . '/includes/collection/MongoDBCollection.php'; return true; }
if ($name == 'MongoDBCollectionIterator') { require $dir . '/includes/collection/MongoDBCollectionIterator.php'; return true; }
+ if ($name == 'MySQLCollection') { require $dir . '/includes/collection/MySQLCollection.php'; return true; }
+ if ($name == 'SQLiteCollection') { require $dir . '/includes/collection/SQLiteCollection.php'; return true; }
+ if ($name == 'SQLCollection') { require $dir . '/includes/collection/SQLCollection.php'; return true; }
if ($name == 'Context') { require $dir . '/includes/controller/Context.php'; return true; }
if ($name == 'Controller') { require $dir . '/includes/controller/Controller.php'; return true; }
if ($name == 'RunnableWithContext') { require $dir . '/includes/controller/RunnableWithContext.php'; return true; }
if ($name == 'Database') { require $dir . '/includes/database/Database.php'; return true; }
if ($name == 'DatabaseException') { require $dir . '/includes/database/DatabaseException.php'; return true; }
if ($name == 'DatabaseResult') { require $dir . '/includes/database/DatabaseResult.php'; return true; }
if ($name == 'EmptyDatabaseResult') { require $dir . '/includes/database/EmptyDatabaseResult.php'; return true; }
if ($name == 'MySQLDatabase') { require $dir . '/includes/database/MySQLDatabase.php'; return true; }
if ($name == 'MySQLDatabaseResult') { require $dir . '/includes/database/MySQLDatabaseResult.php'; return true; }
if ($name == 'Language') { require $dir . '/includes/i18n/Language.php'; return true; }
if ($name == 'Message') { require $dir . '/includes/i18n/Message.php'; return true; }
if ($name == 'TextFileMessage') { require $dir . '/includes/i18n/TextFileMessage.php'; return true; }
if ($name == 'Disclaimer') { require $dir . '/includes/objects/Disclaimer.php'; return true; }
if ($name == 'Permission') { require $dir . '/includes/objects/Permission.php'; return true; }
if ($name == 'User') { require $dir . '/includes/objects/user.php'; return true; }
if ($name == 'UserGroup') { require $dir . '/includes/objects/usergroup.php'; return true; }
if ($name == 'Workspace') { require $dir . '/includes/workspaces/Workspace.php'; return true; }
if ($name == 'WorkspaceConfiguration') { require $dir . '/includes/workspaces/WorkspaceConfiguration.php'; return true; }
return false;
}
spl_autoload_register('obsidian_autoload');
diff --git a/includes/collection/MySQLCollection.php b/includes/collection/MySQLCollection.php
new file mode 100644
index 0000000..c0362b2
--- /dev/null
+++ b/includes/collection/MySQLCollection.php
@@ -0,0 +1,167 @@
+<?php
+
+/**
+ * _, __, _, _ __, _ _, _, _
+ * / \ |_) (_ | | \ | /_\ |\ |
+ * \ / |_) , ) | |_/ | | | | \|
+ * ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
+ *
+ * MySQL Collection class
+ *
+ * @package ObsidianWorkspaces
+ * @subpackage Collection
+ * @author Sébastien Santoro aka Dereckson <dereckson@espace-win.org>
+ * @license http://www.opensource.org/licenses/bsd-license.php BSD
+ * @filesource
+ */
+
+/**
+ * MySQL Collection class
+ *
+ * This class represents a collection of documents, stored on MySQL.
+ */
+class MySQLCollection extends SQLCollection {
+ ///
+ /// Singleton pattern to get the MySQLDatabase instance
+ ///
+
+ /**
+ * @var MySQLDatabase The mongo client to the database the collection is hosted
+ */
+ public static $client = null;
+
+
+ /**
+ * Gets the existing MySQLDatabase instance, or if not available, initializes one.
+ *
+ * @param Context $context
+ * @return MySQLDatabase The MySQLDatabase instance
+ */
+ public static function getCurrentSiteDatabaseClient () {
+ if (self::$client === null) {
+ $client = Database::load();
+ if ($candidateClient instanceof MySQLDatabase) {
+ self::$client = $client;
+ } else {
+ throw new InvalidArgumentException("The MySQLDatabase driver is intended to be used when your main database product is MySQL. We recommend whether you pick the same engine for collections and other db use, whether you use a key/store storage solution for collections, like MongoDB.");
+ }
+ }
+ return self::$client;
+ }
+
+ ///
+ /// Constructor
+ ///
+
+ /**
+ * Initializes a new instance of MongoCollection
+ *
+ * @param string $id the collection identifiant
+ */
+ public function __construct ($id, MySQLDatabase $client = null, $table = '') {
+ global $Config;
+
+ if ($client === null) {
+ self::getCurrentSiteDatabaseClient();
+ } else {
+ self::$client = $client;
+ }
+
+ if ($table == '') {
+ if (!array_key_exists('DocumentStorage', $Config) || !array_key_exists('Table', $Config['DocumentStorage'])) {
+ throw new Exception("Configuration parameter missing: \$Config['DocumentStorage']['Table']. Expected value for this parameter is the table to store the collections documents.");
+ }
+ $this->table = $Config['DocumentStorage']['Table'];
+ } else {
+ $this->table = $table;
+ }
+
+ $this->id = $id;
+ $this->initializeCollectionsTable();
+ }
+
+ ///
+ /// Helper to create schema if required
+ ///
+
+ /**
+ * Initialiazes collections table
+ */
+ protected function initializeCollectionsTable () {
+ if (defined('COLLECTIONS_MYSQL_DATABASE_READY') && COLLECTIONS_MYSQL_DATABASE_READY) {
+ return;
+ }
+
+ self::$client->query("
+ CREATE TABLE if not exists $this->table (
+ collection_id VARCHAR(255),
+ document_id VARCHAR(255),
+ document_value BLOB,
+ PRIMARY KEY (collection_id, document_id)
+ );"
+ );
+
+ define('COLLECTIONS_MYSQL_DATABASE_READY', true);
+ }
+
+ ///
+ /// SqlCollection implementation
+ ///
+
+ /**
+ * Executes a SQL query
+ *
+ * @param string $sql The SQL query
+ * @return mixed If the query doesn't return any result, null. If the query return a row with one field, the scalar value. Otheriwse, an aossciative array, the fields as keys, the row as values.
+ */
+ public function query ($sql) {
+ if ($sql == "") {
+ return null;
+ }
+
+ $db = self::$client;
+ if (!$result = $db->query($sql, MYSQL_ASSOC)) {
+ throw new Exception("Can't execute collection query.");
+ }
+
+ if (!$row = $db->fetchRow($result)) {
+ return null;
+ }
+
+ if (count($row) == 1) {
+ return array_shift($row);
+ } else {
+ return $row;
+ }
+ }
+
+ /**
+ * Escapes the SQL string
+ *
+ * @param string $value The value to escape
+ * @return string The escaped value
+ */
+ public function escape ($value) {
+ return self::$client->escape($value);
+ }
+
+ /**
+ * Gets all the documents from the collection
+ *
+ * @return Iterator An iterator to the documents, each item an instance of CollectionDocument
+ */
+ public function getAll () {
+ $db = self::$client;
+
+ $collectionId = $this->escape($this->id);
+ $sql = "SELECT * FROM $this->table WHERE collection_id = '$collectionId'";
+ if (!$result = $db->query($sql, MYSQL_ASSOC)) {
+ throw new Exception("Can't get each collection documents.");
+ }
+ $type = $this->documentType;
+ while ($row = $db->fetchRow($result)) {
+ $data = json_decode($row['document_value']);
+ yield $type::loadFromObject($data);
+ }
+ }
+}
diff --git a/includes/collection/SQLCollection.php b/includes/collection/SQLCollection.php
new file mode 100644
index 0000000..ea29761
--- /dev/null
+++ b/includes/collection/SQLCollection.php
@@ -0,0 +1,139 @@
+<?php
+
+/**
+ * _, __, _, _ __, _ _, _, _
+ * / \ |_) (_ | | \ | /_\ |\ |
+ * \ / |_) , ) | |_/ | | | | \|
+ * ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
+ *
+ * SQL Collection abstract class
+ *
+ * @package ObsidianWorkspaces
+ * @subpackage Collection
+ * @author Sébastien Santoro aka Dereckson <dereckson@espace-win.org>
+ * @license http://www.opensource.org/licenses/bsd-license.php BSD
+ * @filesource
+ */
+
+/**
+ * Abstract class with SQL standard implementation of CRUD features for collections using a SQL database.
+ */
+abstract class SQLCollection extends Collection {
+ /**
+ * @var string The SQL collections table
+ */
+ public $table;
+
+ /**
+ * Executes a SQL query
+ *
+ * @param string $sql The SQL query
+ * @return mixed If the query doesn't return any null, nothing. If the query return a row with one field, the scalar value. Otheriwse, an aossciative array, the fields as keys, the row as values.
+ */
+ public abstract function query ($sql);
+
+ /**
+ * Escapes the SQL string
+ *
+ * @param string $value The value to escape
+ * @return string The escaped value
+ */
+ public abstract function escape ($value);
+
+ /**
+ * Adds a document to the collection
+ *
+ * @param CollectionDocument $document The document to add
+ * @return boolean true if the operation succeeded; otherwise, false.
+ */
+ public function add (CollectionDocument &$document) {
+ if ($document->id === '') {
+ $document->id = uniqid();
+ }
+
+ $collectionId = $this->escape($this->id);
+ $documentId = $this->escape($document->id);
+ $value = $this->escape(json_encode($document));
+
+ $sql = "INSERT INTO $this->table "
+ . "(collection_id, document_id, document_value) VALUES "
+ . "('$collectionId', '$documentId', '$value')";
+ $this->query($sql);
+ }
+
+ /**
+ * Deletes a document from the collection
+ *
+ * @param string $documentId The identifiant of the document to delete
+ * @return boolean true if the operation succeeded; otherwise, false.
+ */
+ public function delete ($documentId) {
+ $collectionId = $this->escape($this->id);
+ $documentId = $this->escape($documentId);
+
+ $sql = "DELETE FROM $this->table WHERE collection_id = '$collectionId' AND document_id = '$documentId'";
+ $this->query($sql);
+ }
+
+ /**
+ * Determines if a document exists
+ *
+ * @param CollectionDocument $document The document to check
+ * @return boolean true if the document exists; otherwise, false.
+ */
+ public function exists (CollectionDocument $document) {
+ $collectionId = $this->escape($this->id);
+ $documentId = $this->escape($document->id);
+
+ $sql = "SELECT count(*) FROM $this->table WHERE collection_id = '$collectionId' AND document_id = '$documentId'";
+ return $this->query($sql) == 1;
+ }
+
+ /**
+ * Updates a document in the collection
+ *
+ * @param CollectionDocument $document The document to update
+ * @return boolean true if the operation succeeded; otherwise, false.
+ */
+ public function update (CollectionDocument &$document) {
+ $collectionId = $this->escape($this->id);
+ $documentId = $this->escape($document->id);
+ $value = $this->escape(json_encode($document));
+
+ $sql = "UPDATE $this->table SET document_value = '$value' WHERE collection_id = '$collectionId' AND document_id = '$documentId'";
+ $this->query($sql);
+ }
+
+ /**
+ * Gets a document from the collection
+ *
+ * @param string $documentId The identifiant of the document to get
+ * @param CollectionDocument $document The document
+ */
+ public function get ($documentId){
+ $type = $this->documentType;
+ if (!class_exists($type)) {
+ throw new Exception("Can't create an instance of $type. If the class exists, did you registered a SPL autoloader or updated includes/autoload.php?");
+ }
+
+ $collectionId = $this->escape($this->id);
+ $documentId = $this->escape($documentId);
+
+ $sql = "SELECT document_value FROM $this->table WHERE collection_id = '$collectionId' AND document_id = '$documentId'";
+ $data = $this->query($sql);
+ $data = json_decode($data);
+
+ return $type::loadFromObject($data);
+ }
+
+ /**
+ * Gets a count of the documents in the collection
+ *
+ * @return int The number of documents
+ */
+ public function count () {
+ $collectionId = $this->escape($this->id);
+ $sql = "SELECT count(*) FROM $this->table WHERE collection_id = '$collectionId'";
+ return $this->query($sql);
+ }
+}
diff --git a/includes/collection/SQLiteCollection.php b/includes/collection/SQLiteCollection.php
new file mode 100644
index 0000000..e948c73
--- /dev/null
+++ b/includes/collection/SQLiteCollection.php
@@ -0,0 +1,184 @@
+<?php
+
+/**
+ * _, __, _, _ __, _ _, _, _
+ * / \ |_) (_ | | \ | /_\ |\ |
+ * \ / |_) , ) | |_/ | | | | \|
+ * ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
+ *
+ * SQLite Collection class
+ *
+ * @package ObsidianWorkspaces
+ * @subpackage Collection
+ * @author Sébastien Santoro aka Dereckson <dereckson@espace-win.org>
+ * @license http://www.opensource.org/licenses/bsd-license.php BSD
+ * @filesource
+ */
+
+/**
+ * SQLite Collection class
+ *
+ * This class represents a collection of documents, stored on MySQL.
+ */
+class SQLiteCollection extends SQLCollection {
+
+ ///
+ /// Singleton pattern to get or initialize the SQLite instance
+ ///
+
+ /**
+ * @var SQLite3 The SQLite client to the database the collection is hosted
+ */
+ public static $client = null;
+
+
+ /**
+ * Gets the existing SQLite3 instance, or if not available, initializes one.
+ *
+ * @return SQLite3 The SQLite3 instance
+ */
+ public static function getClient () {
+ if (self::$client === null) {
+ self::$client = self::initializeClient();
+ }
+ return self::$client;
+ }
+
+ /**
+ * Initializes a new SQLite3 instance
+ *
+ * @return SQLite3 the client
+ */
+ public static function initializeClient () {
+ global $Config;
+ if (!array_key_exists('DocumentStorage', $Config) || !array_key_exists('File', $Config['DocumentStorage'])) {
+ throw new Exception("Configuration parameter missing: \$Config['DocumentStorage']['File']. Expected value for this parameter is the path to the SQLite database file.");
+ }
+
+ return new SQLite3($Config['DocumentStorage']['File']);
+ }
+
+ ///
+ /// Constructor
+ ///
+
+ /**
+ * Initializes a new instance of MongoCollection
+ *
+ * @param string $id the collection identifiant
+ */
+ public function __construct ($id) {
+ $this->table = 'collections';
+ $this->id = $id;
+ $this->initializeCollectionsTable();
+ }
+
+ ///
+ /// Helper to create SQLite3 schema if required
+ ///
+
+ /**
+ * Initializaes collections table
+ */
+ protected function initializeCollectionsTable () {
+ if (defined('COLLECTIONS_SQLITE_DATABASE_READY') && COLLECTIONS_SQLITE_DATABASE_READY) {
+ return;
+ }
+
+ $client = static::getClient();
+ $client->exec("
+ CREATE TABLE if not exists $this->table (
+ collection_id TEXT,
+ document_id TEXT,
+ document_value BLOB,
+ PRIMARY KEY (collection_id, document_id)
+ );"
+ );
+
+ define('COLLECTIONS_SQLITE_DATABASE_READY', true);
+ }
+
+ ///
+ /// SqlCollection implementation
+ ///
+
+ /**
+ * Determines if the SQL query is a statement
+ *
+ * @return boolean true is a SELECT one; otherwise, false.
+ * @todo To use this outside the Collection scope, adds the other cases where a query is indicated.
+ */
+ public static function isStatement ($sql) {
+ $instruction = strtoupper(strstr($sql, ' ', true));
+ return $instruction != "SELECT" && $instruction != "PRAGMA";
+ }
+
+ /**
+ * Executes a SQL query
+ *
+ * @param string $sql The SQL query
+ * @return mixed If the query doesn't return any result, null. If the query return a row with one field, the scalar value. Otherwise, an associative array, the fields as keys, the row as values.
+ */
+ public function query ($sql) {
+ $client = static::getClient();
+
+ if (static::isStatement($sql)) {
+ if (!$client->exec($sql)) {
+ throw new Exception(
+ "Can't execute collection query. "
+ . $client->lastErrorMsg()
+ );
+ }
+ return null;
+ }
+
+ $result = $client->query($sql);
+ if ($result === true) {
+ return null;
+ }
+ if ($result === false) {
+ throw new Exception(
+ "Can't execute collection query. "
+ . $client->lastErrorMsg()
+ );
+ }
+
+ $row = $result->fetchArray(SQLITE3_ASSOC);
+ $scalar = ($result->numColumns() == 1);
+ $result->finalize();
+
+ if ($scalar) {
+ return array_shift($row);
+ } else {
+ return $row;
+ }
+ }
+
+ /**
+ * Escapes the SQL string
+ *
+ * @param string $value The value to escape
+ * @return string The escaped value
+ */
+ public function escape ($value) {
+ return SQLite3::escapeString($value);
+ }
+
+ /**
+ * Gets all the documents from the collection
+ *
+ * @return Iterator An iterator to the documents, each item an instance of CollectionDocument
+ */
+ public function getAll () {
+ $collectionId = $this->escape($this->id);
+ $sql = "SELECT document_value FROM $this->table WHERE collection_id = '$collectionId'";
+ $client = static::getClient();
+ $type = $this->documentType;
+
+ $result = $client->query($sql);
+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
+ $data = json_decode($row['document_value']);
+ yield $type::loadFromObject($data);
+ }
+ }
+}
diff --git a/tests/includes/collection/CRUDTestTrait.php b/tests/includes/collection/CRUDTestTrait.php
index 6320d6d..bedf63e 100644
--- a/tests/includes/collection/CRUDTestTrait.php
+++ b/tests/includes/collection/CRUDTestTrait.php
@@ -1,221 +1,235 @@
<?php
/**
* _, __, _, _ __, _ _, _, _
* / \ |_) (_ | | \ | /_\ |\ |
* \ / |_) , ) | |_/ | | | | \|
* ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
*
* CRUD features tests for each Collection class.
*
* @package ObsidianWorkspaces
* @subpackage Tests
* @author Sébastien Santoro aka Dereckson <dereckson@espace-win.org>
* @license http://www.opensource.org/licenses/bsd-license.php BSD
* @filesource
*/
require_once('../includes/autoload.php');
/**
* A CollectionDocument class, for our tests.
*/
class BookDocument extends CollectionDocument {
/**
* @var string The book title
*/
public $title;
/**
* @var string The book author
*/
public $author;
/**
* Initializes a new instance of the BookDocument object
*/
public function __construct ($author = null, $title = null) {
if ($title !== null) $this->title = $title;
if ($author !== null) $this->author = $author;
}
}
/**
* The tests for our basic, non storage engine specific CRUD features
*
* For coverage purposes, it requires a coversDefaultClass annotation in the classes using this trait.
*/
trait CRUDTestTrait {
/**
* @var BookDocument The document to test every CRUD feature
*/
protected $redBook;
/**
* @var BookDocument A second document to test Set in two scenarii
*/
protected $blueBook;
/**
* Initializes two documents for the tests
*/
public function initializeDocuments() {
$this->blueBook = new BookDocument('Isaac Asimov', 'Foundation');
$this->redBook = new BookDocument('Iain Banks', 'Matter'); //M. will be added in update test
$this->redBook->id = 'redBook';
}
/**
+ * Tests if the constructor correctly initializes the id property
+ *
+ * @covers ::_construct()
+ */
+ public function testId () {
+ $this->assertEquals('quux', $this->collection->id, "The collection constructor should have initialized the Collection::id property.");
+ }
+
+ /**
+ * Tests CRUD methods
+ *
* @covers ::add
* @covers ::exists
* @covers ::update
* @covers ::get
* @covers ::set
* @covers ::delete
* @covers ::count
* @covers ::getAll
*/
public function testCRUD () {
global $Config;
$Config = static::getConfig();
//::count
$this->assertEquals(
0, $this->collection->count(),
"The test collection isn't empty. Check the last test run cleaned correctly the resources."
);
//::add
$this->collection->add($this->redBook);
$this->assertNotEmpty(
$this->redBook->id,
- "After a document has been added, the is has been deleted."
+ "After a document has been added, the id has been deleted."
);
$this->assertEquals(
'redBook',
$this->redBook->id,
- "After a document has been added, the is has been modified."
+ "After a document has been added, the id has been modified."
);
//:ccount
$this->assertEquals(1, $this->collection->count());
//::exists
$this->assertFalse(
$this->collection->exists($this->blueBook),
"A non added document has been marked existing."
);
$this->assertTrue(
$this->collection->exists($this->redBook),
"An added document hasn't been found as existing."
);
//::update
$this->redBook->author = 'Iain M. Banks';
$this->collection->update($this->redBook);
$this->assertEquals(
'redBook',
$this->redBook->id,
"The document ID has been modified during an update operation. It should stay the same. Old id: redBook. New id: " . $this->redBook->id
);
//::count
- $this->assertEquals(1, $this->collection->count()
- );
+ $this->assertEquals(1, $this->collection->count());
//::get - when our collection uses the generic CollectionDocument class
$newDocument = $this->collection->get($this->redBook->id);
$this->assertInstanceOf('CollectionDocument', $newDocument);
$this->assertNotInstanceOf('BookDocument', $newDocument);
//::set - when our collection uses a proper CollectionDocument descendant
$this->collection->documentType = 'BookDocument';
$newBook = $this->collection->get($this->redBook->id);
$this->assertInstanceOf('BookDocument', $newBook);
$this->assertObjectHasAttribute('title', $newBook);
$this->assertObjectHasAttribute('author', $newBook);
$this->assertObjectHasAttribute('id', $newBook);
$this->assertEquals('Matter', $newBook->title);
$this->assertEquals('Iain M. Banks', $newBook->author);
$this->assertEquals('redBook', $newBook->id);
//::set - an existing document as parameter
$previousId = $this->redBook->id;
$this->collection->set($this->redBook);
$this->assertEquals(
$previousId,
$this->redBook->id,
"The document ID has been modified during a set operation on an already added dcoument. It should stay the same. Old id: $previousId. New id: " . $this->redBook->id
);
//::count
$this->assertEquals(1, $this->collection->count());
//::set - a new document as parameter
$this->collection->set($this->blueBook);
$this->assertNotEmpty(
$this->blueBook->id,
"After a document has been added, the expected behavior is the id property is filled with the generated identifiant."
);
$this->assertTrue(
$this->collection->exists($this->blueBook),
"An added document with set hasn't been found as existing."
);
//::count
$this->assertEquals(2, $this->collection->count());
//::getAll
$documents = $this->collection->getAll();
$count = 0;
foreach ($documents as $document) {
switch ($document->id) {
case $this->blueBook->id:
$this->assertInstanceOf('BookDocument', $document);
$this->assertObjectHasAttribute('title', $document);
$this->assertObjectHasAttribute('author', $document);
$this->assertObjectHasAttribute('id', $document);
$this->assertEquals('Foundation', $document->title);
$this->assertEquals('Isaac Asimov', $document->author);
break;
case 'redBook':
$this->assertInstanceOf('BookDocument', $document);
$this->assertObjectHasAttribute('title', $document);
$this->assertObjectHasAttribute('author', $document);
$this->assertObjectHasAttribute('id', $document);
$this->assertEquals('Matter', $document->title);
$this->assertEquals('Iain M. Banks', $document->author);
break;
+ case '':
+ $this->fail("An object without id has been returned by the getAll method.");
+ break;
+
default:
- $this->fail('A document with an id nor redBook, the blueBook generated id has been returned.');
+ $this->fail("A document with an id nor 'redBook', nor the blueBook generated id ('{$this->blueBook->id}') has been returned: $document->id.");
}
$count++;
}
$this->assertEquals(2, $count);
//::delete
$this->collection->delete($this->blueBook->id);
$this->assertFalse(
$this->collection->exists($this->blueBook),
"A deleted document has been marked existing."
);
$this->assertTrue(
$this->collection->exists($this->redBook),
"An unexpected document has been deleted."
);
//::count
$this->assertEquals(1, $this->collection->count());
//::delete, ::count
$this->collection->delete($this->redBook->id);
$this->assertEquals(0, $this->collection->count());
//::getAll
$documents = $this->collection->getAll();
$this->assertCount(0, $documents, "We expected each collection document would have been deleted.");
}
}
diff --git a/tests/includes/collection/MySQCollectionTest.php b/tests/includes/collection/MySQCollectionTest.php
new file mode 100644
index 0000000..36a6538
--- /dev/null
+++ b/tests/includes/collection/MySQCollectionTest.php
@@ -0,0 +1,135 @@
+<?php
+
+/**
+ * _, __, _, _ __, _ _, _, _
+ * / \ |_) (_ | | \ | /_\ |\ |
+ * \ / |_) , ) | |_/ | | | | \|
+ * ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
+ *
+ * Unit testing — MySQLCollection class
+ *
+ * @package ObsidianWorkspaces
+ * @subpackage Tests
+ * @author Sébastien Santoro aka Dereckson <dereckson@espace-win.org>
+ * @license http://www.opensource.org/licenses/bsd-license.php BSD
+ * @filesource
+ */
+
+require_once('CRUDTestTrait.php');
+require_once('SQLTestTrait.php');
+
+/**
+ * Tests MySQLCollection class
+ * @coversDefaultClass MySQLCollection
+ */
+class MySQLCollectionTest extends PHPUnit_Framework_TestCase {
+ ///
+ /// Traits
+ ///
+
+ use CRUDTestTrait;
+ use SQLTestTrait;
+
+ ///
+ /// Test properties
+ ///
+
+ /**
+ * @var string Our collection
+ */
+ protected $collection;
+
+ ///
+ /// Class initialisation
+ ///
+
+ /**
+ * Gets default configuration for this test
+ *
+ * @return array The configuration block
+ */
+ protected static function getConfig () {
+ return [
+ 'DocumentStorage' => [
+ 'Type' => 'MySQL',
+ 'Table' => UNITTESTING_MYSQL_TABLE
+ ]
+ ];
+ }
+
+ /**
+ * Initializes the resources needed for thist test.
+ */
+ public function setUp () {
+ $db = new MySQLDatabase(
+ UNITTESTING_MYSQL_HOST,
+ UNITTESTING_MYSQL_USERNAME,
+ UNITTESTING_MYSQL_PASSWORD,
+ UNITTESTING_MYSQL_DATABASE
+ );
+
+ $this->initializeDocuments();
+ $this->collection = new MySQLCollection('quux', $db, UNITTESTING_MYSQL_TABLE);
+ }
+
+ ///
+ /// Tests specific to MySQLCollection
+ ///
+
+ /**
+ * Tests the property table is correctly set
+ *
+ * @covers MySQLCollection::construct
+ */
+ public function testTable () {
+ $this->assertEquals(UNITTESTING_MYSQL_TABLE, $this->collection->table, "The collection constructor should have initialized the MySQLCollection::table property.");
+ }
+
+ /**
+ * Tests if the ready constant has been correctly defined
+ *
+ * @covers MySQLCollection::initializeCollectionsTable
+ */
+ public function testReadyConstant () {
+ $this->assertTrue(
+ defined('COLLECTIONS_MYSQL_DATABASE_READY'),
+ "After the client has been initialized, we shall have a 'COLLECTIONS_SQLITE_DATABASE_READY' constant defined."
+ );
+
+ $this->assertSame(
+ COLLECTIONS_MYSQL_DATABASE_READY,
+ true,
+ "COLLECTIONS_MYSQL_DATABASE_READY constant value shall be the boolean true."
+ );
+ }
+
+ /**
+ * Tests if strings are correctly escaped
+ *
+ * @covers MySQLCollection::escape
+ */
+ public function testEscape () {
+ $toEscapeExpressions = [
+ "",
+ "Lorem ipsum dolor",
+ "L'arbre",
+ "''",
+ "cœur"
+ ];
+ $escapedExpressions = [
+ "",
+ "Lorem ipsum dolor",
+ "L\\'arbre",
+ "\\'\\'",
+ "cœur"
+ ];
+
+ for ($i = 0 ; $i < count($toEscapeExpressions) ; $i++) {
+ $this->assertEquals(
+ $escapedExpressions[$i],
+ $this->collection->escape($toEscapeExpressions[$i]),
+ "The following string isn't properly escaped: '$toEscapeExpressions[$i]'"
+ );
+ }
+ }
+}
diff --git a/tests/includes/collection/SQLTestTrait.php b/tests/includes/collection/SQLTestTrait.php
new file mode 100644
index 0000000..18c0d6b
--- /dev/null
+++ b/tests/includes/collection/SQLTestTrait.php
@@ -0,0 +1,66 @@
+<?php
+
+/**
+ * _, __, _, _ __, _ _, _, _
+ * / \ |_) (_ | | \ | /_\ |\ |
+ * \ / |_) , ) | |_/ | | | | \|
+ * ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
+ *
+ * SQL schema tests for each Collection class.
+ *
+ * @package ObsidianWorkspaces
+ * @subpackage Tests
+ * @author Sébastien Santoro aka Dereckson <dereckson@espace-win.org>
+ * @license http://www.opensource.org/licenses/bsd-license.php BSD
+ * @filesource
+ */
+
+require_once('../includes/autoload.php');
+
+/**
+ * The tests for our SQL storage engines, to ensure the schema is created correctly.
+ *
+ * For coverage purposes, it requires a coversDefaultClass annotation in the classes using this trait.
+ */
+trait SQLTestTrait {
+ /**
+ * @covers ::query()
+ */
+ public function testQuery () {
+ /*
+ The query method is a complicated aspect of the code, as it returns a different
+ result according the kind of query:
+
+ (1) If the query doesn't return any result, null.
+ (2) If the query return a row with one field, the scalar value.
+ (3) Otherwise, an associative array, the fields as keys, the row as values.
+ */
+ $sqlNoQueryResult = "";
+ $sqlNullResult = "UPDATE {$this->collection->table} SET collection_id = 'lorem' WHERE collection_id = 'lorem'";
+ $sqlScalarResult = "SELECT 1+1";
+ $sqlArrayResult = "SELECT 8+2 as sum, 8*2 as product, 8/2 as quotient, 8-2 as difference";
+
+ try {
+ $resultNull = $this->collection->query($sqlNoQueryResult);
+ } catch (Exception $ex) {
+ $this->fail("The query() specifications provides: 'If the query doesn't return any result, return null.'. This is also the expected behavior for empty queries. Instead we got an exception.");
+
+ }
+ $this->assertNull($resultNull, "The query() specifications provides: 'If the query doesn't return any result, return null.'. This is also the expected behavior for empty queries.");
+
+ $resultNull = $this->collection->query($sqlNullResult);
+ $this->assertNull($resultNull, "The query() specifications provides: 'If the query doesn't return any result, return null.'. This is expected for $sqlNullResult.");
+
+ $resultScalar = $this->collection->query($sqlScalarResult);
+ $this->assertEquals(2, $resultScalar, "The query() specifications provides: 'If the query return a row with one field, the scalar value.' This is expected for $sqlScalarResult.");
+
+ $resultArray = $this->collection->query($sqlArrayResult);
+ $expectedResultArray = [
+ 'sum' => 10,
+ 'product' => 16,
+ 'quotient' => 4,
+ 'difference' => 6,
+ ];
+ $this->assertEquals($expectedResultArray, $resultArray, "The query() specifications provides: '[If the query returns a non scalar result, return] an associative array, the fields as keys, the row as values.'. This is expected for $sqlArrayResult.");
+ }
+}
\ No newline at end of file
diff --git a/tests/includes/collection/SQLiteCollectionTest.php b/tests/includes/collection/SQLiteCollectionTest.php
new file mode 100644
index 0000000..e3654b8
--- /dev/null
+++ b/tests/includes/collection/SQLiteCollectionTest.php
@@ -0,0 +1,187 @@
+<?php
+
+/**
+ * _, __, _, _ __, _ _, _, _
+ * / \ |_) (_ | | \ | /_\ |\ |
+ * \ / |_) , ) | |_/ | | | | \|
+ * ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
+ *
+ * Unit testing — SQLiteCollection class
+ *
+ * @package ObsidianWorkspaces
+ * @subpackage Tests
+ * @author Sébastien Santoro aka Dereckson <dereckson@espace-win.org>
+ * @license http://www.opensource.org/licenses/bsd-license.php BSD
+ * @filesource
+ */
+
+require_once('CRUDTestTrait.php');
+require_once('SQLTestTrait.php');
+
+/**
+ * Tests SQLiteCollection class
+ * @coversDefaultClass SQLiteCollection
+ */
+class SQLiteCollectionTest extends PHPUnit_Framework_TestCase {
+ ///
+ /// Traits
+ ///
+
+ use CRUDTestTrait;
+ use SQLTestTrait;
+
+ ///
+ /// Test properties
+ ///
+
+ /**
+ * @var string Our collection
+ */
+ protected $collection;
+
+ ///
+ /// Class initizliation
+ ///
+
+ /**
+ * Gets default configuration for this test
+ *
+ * @return array The configuration block
+ */
+ public static function getConfig () {
+ return [
+ 'DocumentStorage' => [
+ 'Type' => 'SQLite',
+ 'File' => UNITTESTING_SQLITE_FILE
+ ]
+ ];
+ }
+
+ /**
+ * Initializes a new instance of the PHPUnit_Framework_TestCase class
+ *
+ * @param string $name The test case name
+ */
+ public function __construct (string $name = null) {
+ parent::__construct($name);
+
+ $this->initializeDocuments();
+
+ global $Config;
+ $Config = static::getConfig();
+
+ $this->collection = new SQLiteCollection('quux');
+ }
+
+ ///
+ /// Tests specific to SQLiteCollection
+ ///
+
+ /**
+ * Tests the client related methods
+ *
+ * @covers SQLiteCollection::getClient
+ * @covers SQLiteCollection::initializeClient
+ * @covers SQLiteCollection::initializeCollectionsTable
+ */
+ public function testClient () {
+ global $Config;
+ $client1 = SQLiteCollection::getClient();
+ $client2 = SQLiteCollection::getClient();
+
+ $this->assertInstanceOf('SQLite3', $client1);
+ $this->assertInstanceOf('SQLite3', $client2);
+ $this->assertSame($client1, $client2, "The collection classes are expected to use a singleton pattern for the client: you should return the same object initialized before instead to create another one.");
+
+ $databaseList = $this->collection->query("PRAGMA database_list");
+ $this->assertEquals(
+ [
+ 'seq' => 0,
+ 'name' => 'main',
+ 'file' => realpath($Config['DocumentStorage']['File'])
+ ],
+ $databaseList,
+ "The query PRAGMA database_list hasn't returned what we expected: one database opened by the client, the file returned by the database matching our configuration file."
+ );
+
+ $this->assertTrue(
+ defined('COLLECTIONS_SQLITE_DATABASE_READY'),
+ "After the client has been initialized, we shall have a 'COLLECTIONS_SQLITE_DATABASE_READY' constant defined."
+ );
+
+ $this->assertSame(
+ COLLECTIONS_SQLITE_DATABASE_READY,
+ true,
+ "COLLECTIONS_SQLITE_DATABASE_READY constant value shall be the boolean true."
+ );
+ }
+
+ /**
+ * Tests string escapement
+ *
+ * @covers SQLiteCollection::escape
+ */
+ public function testEscape () {
+ $toEscapeExpressions = [
+ "",
+ "Lorem ipsum dolor",
+ "L'arbre",
+ "''",
+ "cœur"
+ ];
+ $escapedExpressions = [
+ "",
+ "Lorem ipsum dolor",
+ "L''arbre",
+ "''''",
+ "cœur"
+ ];
+
+ for ($i = 0 ; $i < count($toEscapeExpressions) ; $i++) {
+ $this->assertEquals(
+ $escapedExpressions[$i],
+ $this->collection->escape($toEscapeExpressions[$i]),
+ "The following string isn't properly escaped: '$toEscapeExpressions[$i]'"
+ );
+ }
+ }
+
+ /**
+ * @covers SQLiteCollection::isStatement
+ */
+ public function testStatements () {
+ $sqlQueries = [
+ "SELECT foo FROM bar",
+ "PRAGMA foo"
+ ];
+
+ $sqlStatements = [
+ "UPDATE bar SET foo = 'quux'",
+ "DELETE FROM bar WHERE foo = 'quux'",
+ "INSERT INTO bar (foo) VALUES ('quux')",
+ "REPLACE INTO bar (foo) VALUES ('quux')",
+ "INSERT INTO bar SELECT FROM baz"
+ ];
+
+ foreach ($sqlQueries as $sql) {
+ $this->assertFalse(
+ $this->collection->isStatement($sql),
+ "The query $sql should be considered as a query, not as a statement, to use SQLite3::query() and not SQLite3::exec()"
+ );
+ }
+
+ foreach ($sqlStatements as $sql) {
+ $this->assertTrue(
+ $this->collection->isStatement($sql),
+ "The query $sql should be considered as a statement, not as a query, as long as SQLite3 is concerned, to use SQLite3::exec() and not SQLite3::query()"
+ );
+ }
+ }
+
+ /**
+ * Clears resources created for this test
+ */
+ public static function tearDownAfterClass () {
+ unlink(UNITTESTING_SQLITE_FILE);
+ }
+}
diff --git a/tests/phpunit.xml b/tests/phpunit.xml
index 3a8f1ac..af4512f 100644
--- a/tests/phpunit.xml
+++ b/tests/phpunit.xml
@@ -1,25 +1,26 @@
<phpunit
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/3.7/phpunit.xsd"
forceCoversAnnotation="true"
>
<php>
<!-- MySQL -->
<const name="UNITTESTING_MYSQL_HOST" value="localhost" />
<const name="UNITTESTING_MYSQL_USERNAME" value="root" />
<const name="UNITTESTING_MYSQL_PASSWORD" value="" />
<const name="UNITTESTING_MYSQL_DATABASE" value="obsidian" />
+ <const name="UNITTESTING_MYSQL_TABLE" value="collections_unittesting" />
<!-- SQLite -->
<const name="UNITTESTING_SQLITE_FILE" value="/tmp/collections.db" />
<!-- MongoDB -->
<const name="UNITTESTING_MONGODB_HOST" value="localhost" />
<const name="UNITTESTING_MONGODB_PORT" value="27017" />
<const name="UNITTESTING_MONGODB_SSL" value="true" />
<!-- FilesCollection -->
<const name="UNITTESTING_FILESCOLLECTION_PATH" value="/tmp/obsidiancollections" />
</php>
</phpunit>

File Metadata

Mime Type
text/x-diff
Expires
Sat, Mar 7, 02:33 (1 d, 20 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
3500408
Default Alt Text
(44 KB)

Event Timeline