throw new Exception("Configuration parameter missing: \$Config['DocumentStorage']['Path']. Expected value for this parameter is the path to the collections folders.");
use Waystone\Workspaces\Engines\Framework\Context;
+use Exception;
+use InvalidArgumentException;
+use Iterator;
+
/**
* 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
+ * @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.
+ * 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 = '') {
+ 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'])) {
+ if (!array_key_exists('DocumentStorage', $Config)
throw new Exception("Configuration parameter missing: \$Config['DocumentStorage']['Table']. Expected value for this parameter is the table to store the collections documents.");
protected function initializeCollectionsTable () {
- if (defined('COLLECTIONS_MYSQL_DATABASE_READY') && COLLECTIONS_MYSQL_DATABASE_READY) {
+ 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. Otherwise, an associative array, the fields as keys, the row as values.
+ *
+ * @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) {
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
+ * @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'";
+ $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.");
- * Abstract class with SQL standard implementation of CRUD features for collections using a SQL database.
+ * 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. Otherwise, an associative array, the fields as keys, the row as values.
+ *
+ * @return mixed If the query doesn't return any null, nothing. 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 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) {
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
///
/**
* Initializes collections table
*/
protected function initializeCollectionsTable () {
- if (defined('COLLECTIONS_SQLITE_DATABASE_READY') && COLLECTIONS_SQLITE_DATABASE_READY) {
+ if (defined('COLLECTIONS_SQLITE_DATABASE_READY')
- * @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.
+ *
+ * @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()
+ . $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()
+ . $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
+ * @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'";
+ $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)) {
$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
* Initializes the resources needed for thist test.
*/
public function setUp () : void {
$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
*/
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
*/
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."
$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.");
$this->assertNull($resultNull, "The query() specifications provides: 'If the query doesn't return any result, return null.'. This is expected for $sqlNullResult.");
$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.");
$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.");
$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.");
"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."