From 36ef34af2abcdea63a73b578208f20ca40b52f49 Mon Sep 17 00:00:00 2001 From: vincent-peugnet Date: Thu, 1 Nov 2018 15:56:24 +0100 Subject: flywheel database added --- w/class/art2.php | 4 +- w/class/controllerdb.php | 14 +- w/class/controllerhome.php | 2 +- w/class/dbengine.php | 309 --------------------------------------------- w/class/modelart.php | 28 +++- w/class/modeldb.php | 163 +----------------------- 6 files changed, 36 insertions(+), 484 deletions(-) delete mode 100644 w/class/dbengine.php (limited to 'w/class') diff --git a/w/class/art2.php b/w/class/art2.php index fd7a403..2298147 100644 --- a/w/class/art2.php +++ b/w/class/art2.php @@ -44,12 +44,12 @@ class Art2 // _____________________________________________________ F U N ____________________________________________________ - public function __construct(array $donnees) + public function __construct($donnees) { $this->hydrate($donnees); } - public function hydrate(array $donnees) + public function hydrate($donnees) { foreach ($donnees as $key => $value) { $method = 'set' . $key; diff --git a/w/class/controllerdb.php b/w/class/controllerdb.php index 5952627..f21d265 100644 --- a/w/class/controllerdb.php +++ b/w/class/controllerdb.php @@ -15,15 +15,6 @@ class Controllerdb extends Controller } - public function dbinit() - { - $this->database = new SleekDBw(__DIR__ . '/../../w_database', [ - 'auto_cache' => false - ]); - $this->artstore = $this->database->store(Config::arttable()); - - } - public function fetch() @@ -42,6 +33,11 @@ class Controllerdb extends Controller } + public function add() + { + $user = $usersDB->where( 'name', '=', 'Joshua Edwards' )->fetch(); + } + diff --git a/w/class/controllerhome.php b/w/class/controllerhome.php index 8c98949..6e62426 100644 --- a/w/class/controllerhome.php +++ b/w/class/controllerhome.php @@ -22,7 +22,7 @@ class Controllerhome extends Controllerdb public function table2() { - $table = $this->artmanager->getlister(['id', 'tag', 'linkfrom', 'linkto', 'description', 'title', 'datemodif', 'datecreation', 'secure']); + $table = $this->artmanager->getlister(); $this->opt = $this->modelhome->optinit($table); $table2 = $this->modelhome->table2($table, $this->opt); diff --git a/w/class/dbengine.php b/w/class/dbengine.php deleted file mode 100644 index 7895a1a..0000000 --- a/w/class/dbengine.php +++ /dev/null @@ -1,309 +0,0 @@ -init($dataDir); - } - - public function init($dataDir) - { - // Handle directory path ending. - if (substr($dataDir, -1) !== '/') $dataDir = $dataDir . '/'; - - if (!file_exists($dataDir)) { - // The directory was not found, create one. - if (!mkdir($dataDir, 0777, true)) throw new \Exception('Unable to create the data directory at ' . $dataDir); - } - // Check if PHP has write permission in that directory. - if (!is_writable($dataDir)) throw new \Exception('Data directory is not writable at "' . $dataDir . '." Please change data directory permission.'); - // Finally check if the directory is readable by PHP. - if (!is_readable($dataDir)) throw new \Exception('Data directory is not readable at "' . $dataDir . '." Please change data directory permission.'); - // Set the data directory. - $this->dataDirectory = $dataDir; - } - - // Initialize the store. - public function store($storeName = false) - { - if (!$storeName or empty($storeName)) throw new \Exception('Store name was not valid'); - $this->storeName = $storeName; - // Boot store. - $this->bootStore(); - // Initialize variables for the store. - $this->initVariables(); - return $this; - } - - - public function insert(Art2 $art) - { - $artdata = $art->dry(); - $storableJSON = json_encode($artdata); - if ($storableJSON === false) throw new \Exception('Unable to encode the art object'); - $storePath = $this->storePath . $art->id() . '.json'; - if (!file_put_contents($storePath, $storableJSON)) { - throw new \Exception("Unable to write the object file! Please check if PHP has write permission."); - } - return true; - } - - public function get($id) - { - $filepath = $this->storePath . $id . '.json'; - if (file_exists($filepath)) { - $data = json_decode(file_get_contents($filepath), true); - if ($data !== false) return $data; - } else { - return false; - } - } - - public function update($id, $data) - { - foreach ($data as $key => $value) { - // Do not update the _id reserved index of a store. - if ($key != 'id') { - $data[$key] = $value; - } - } - $storePath = $this->storePath . $id . '.json'; - if (file_exists($storePath)) { - // Wait until it's unlocked, then update data. - file_put_contents($storePath, json_encode($data), LOCK_EX); - } - return true; - } - - - public function getidlist() - { - $lengh = strlen($this->storePath); - $list = []; - foreach (glob($listPath . '*.json') as $filename) { - $list[] = substr(substr($filename, $lengh), 0, -5); - } - return $list; - } - - // Method to boot a store. - protected function bootStore() - { - $store = trim($this->storeName); - // Validate the store name. - if (!$store || empty($store)) throw new \Exception('Invalid store name was found'); - // Prepare store name. - if (substr($store, -1) !== '/') $store = $store . '/'; - // Store directory path. - $this->storePath = $this->dataDirectory . $store; - // Check if the store exists. - if (!file_exists($this->storePath)) { - // The directory was not found, create one with cache directory. - if (!mkdir($this->storePath, 0777, true)) throw new \Exception('Unable to create the store path at ' . $this->storePath); - } - // Check if PHP has write permission in that directory. - if (!is_writable($this->storePath)) throw new \Exception('Store path is not writable at "' . $this->storePath . '." Please change store path permission.'); - // Finally check if the directory is readable by PHP. - if (!is_readable($this->storePath)) throw new \Exception('Store path is not readable at "' . $this->storePath . '." Please change store path permission.'); - } - - // Init data that SleekDB required to operate. - protected function initVariables() - { - // Set empty results - $this->results = []; - // Set a default limit - $this->limit = 0; - // Set a default skip - $this->skip = 0; - // Set default conditions - $this->conditions = []; - // Set default group by value - $this->orderBy = [ - 'order' => false, - 'field' => '_id' - ]; - // Set the default search keyword as an empty string. - $this->searchKeyword = ''; - } - - - - -// ______________________________________ analyse _______________________________ - - - // Find store objects with conditions, sorting order, skip and limits. - protected function findStoreDocuments() - { - $found = []; - $searchRank = []; - // Start collecting and filtering data. - foreach ($this->getidlist() as $id) { - // Collect data of current iteration. - $data = $this->get($id); - if (!empty($data)) { - // Filter data found. - if (empty($this->conditions)) { - // Append all data of this store. - $found[] = $data; - } else { - // Append only passed data from this store. - $storePassed = true; - // Iterate each conditions. - foreach ($this->conditions as $condition) { - // Check for valid data from data source. - $validData = true; - $fieldValue = ''; - try { - $fieldValue = $this->getNestedProperty($condition['fieldName'], $data); - } catch (\Exception $e) { - $validData = false; - $storePassed = false; - } - if ($validData === true) { - // Check the type of rule. - if ($condition['condition'] === '=') { - // Check equal. - if ($fieldValue != $condition['value']) $storePassed = false; - } else if ($condition['condition'] === '!=') { - // Check not equal. - if ($fieldValue == $condition['value']) $storePassed = false; - } else if ($condition['condition'] === '>') { - // Check greater than. - if ($fieldValue <= $condition['value']) $storePassed = false; - } else if ($condition['condition'] === '>=') { - // Check greater equal. - if ($fieldValue < $condition['value']) $storePassed = false; - } else if ($condition['condition'] === '<') { - // Check less than. - if ($fieldValue >= $condition['value']) $storePassed = false; - } else if ($condition['condition'] === '<=') { - // Check less equal. - if ($fieldValue > $condition['value']) $storePassed = false; - } - } - } - // Check if current store is updatable or not. - if ($storePassed === true) { - // Append data to the found array. - $found[] = $data; - } - } - } - } - if (count($found) > 0) { - // Check do we need to sort the data. - if ($this->orderBy['order'] !== false) { - // Start sorting on all data. - $found = $this->sortArray($this->orderBy['field'], $found, $this->orderBy['order']); - } - // If there was text search then we would also sort the result by search ranking. - if (!empty($this->searchKeyword)) { - $found = $this->performSerach($found); - } - // Skip data - if ($this->skip > 0) $found = array_slice($found, $this->skip); - // Limit data. - if ($this->limit > 0) $found = array_slice($found, 0, $this->limit); - } - return $found; - } - - - - // Sort store objects. - protected function sortArray($field, $data, $order = 'ASC') - { - $dryData = []; - // Check if data is an array. - if (is_array($data)) { - // Get value of the target field. - foreach ($data as $value) { - $dryData[] = $this->getNestedProperty($field, $value); - } - } - // Descide the order direction. - if (strtolower($order) === 'asc') asort($dryData); - else if (strtolower($order) === 'desc') arsort($dryData); - // Re arrange the array. - $finalArray = []; - foreach ($dryData as $key => $value) { - $finalArray[] = $data[$key]; - } - return $finalArray; - } - - // Get nested properties of a store object. - protected function getNestedProperty($field = '', $data) - { - if (is_array($data) and !empty($field)) { - // Dive deep step by step. - foreach (explode('.', $field) as $i) { - // If the field do not exists then insert an empty string. - if (!isset($data[$i])) { - $data = ''; - throw new \Exception('"' . $i . '" index was not found in the provided data array'); - break; - } else { - // The index is valid, collect the data. - $data = $data[$i]; - } - } - return $data; - } - } - - // Do a search in store objects. This is like a doing a full-text search. - protected function performSerach($data = []) - { - if (empty($data)) return $data; - $nodesRank = []; - // Looping on each store data. - foreach ($data as $key => $value) { - // Looping on each field name of search-able fields. - foreach ($this->searchKeyword['field'] as $field) { - try { - $nodeValue = $this->getNestedProperty($field, $value); - // The searchable field was found, do comparison against search keyword. - similar_text(strtolower($nodeValue), strtolower($this->searchKeyword['keyword']), $perc); - if ($perc > 50) { - // Check if current store object already has a value, if so then add the new value. - if (isset($nodesRank[$key])) $nodesRank[$key] += $perc; - else $nodesRank[$key] = $perc; - } - } catch (\Exception $e) { - continue; - } - } - } - if (empty($nodesRank)) { - // No matched store was found against the search keyword. - return []; - } - // Sort nodes in descending order by the rank. - arsort($nodesRank); - // Map original nodes by the rank. - $nodes = []; - foreach ($nodesRank as $key => $value) { - $nodes[] = $data[$key]; - } - return $nodes; - } - - - - - -} - - - - - - - - - -?> \ No newline at end of file diff --git a/w/class/modelart.php b/w/class/modelart.php index dfb6476..be72611 100644 --- a/w/class/modelart.php +++ b/w/class/modelart.php @@ -28,15 +28,17 @@ class Modelart extends Modeldb public function add(Art2 $art) { - $this->artstore->insert($art); + + $artdata = new \JamesMoss\Flywheel\Document($art->dry()); + $artdata->setId($art->id()); + $this->artstore->store($artdata); } public function get(Art2 $art) { - $artdata = $this->artstore->get($art->id()); + $artdata = $this->artstore->findById($art->id()); if($artdata !== false) { - $art = new Art2($artdata); - return $art; + return new Art2($artdata); } else { return false; } @@ -45,7 +47,19 @@ class Modelart extends Modeldb public function update(Art2 $art) { $art->updateedited(); - $this->artstore->update($art->id(), $art->dry()); + $artdata = new \JamesMoss\Flywheel\Document($art->dry()); + $artdata->setId($art->id()); + $this->artstore->store($artdata); + } + + public function getlister() + { + $artlist = []; + $list = $this->artstore->findAll(); + foreach ($list as $artdata) { + $artlist[] = new Art2($artdata); + } + return $artlist; } @@ -106,7 +120,7 @@ class Modelart extends Modeldb } - public function delete(Art2 $art) + public function delete3(Art2 $art) { $req = $this->bdd->prepare('DELETE FROM ' . Config::arttable() . ' WHERE id = :id '); $req->execute(array('id' => $art->id())); @@ -195,6 +209,8 @@ class Modelart extends Modeldb } } + + public function getlisterwhere3(array $select = ['id'], array $whereid = [], $by = 'id', $order = 'DESC') { // give an array using SELECTION columns and sort and desc OPTIONS diff --git a/w/class/modeldb.php b/w/class/modeldb.php index 6064b4f..d6a4c18 100644 --- a/w/class/modeldb.php +++ b/w/class/modeldb.php @@ -2,174 +2,23 @@ class Modeldb extends Model { /** @var PDO */ - protected $bdd; + protected $bdd; protected $arttable; protected $database; protected $artstore; - - public function __construct() { - //$this->setbdd(); - //self::setdb(); - $this->dbinit(); - } - - - public function dbinit() - { - $this->database = new Dbengine(__DIR__ . '/../../w_database'); - $this->artstore = $this->database->store(Config::arttable()); - - } - - - - - public function setbdd() - { - $caught = true; - - try { - $this->bdd = new PDO('mysql:host=' . Config::host() . ';dbname=' . Config::dbname() . ';charset=utf8', Config::user(), Config::password(), array(PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT)); - //$this->bdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - } catch (PDOException $e) { - $caught = false; - echo '

Error 500, database offline

'; - if ($this->session() >= self::EDITOR) { - echo '

Error : ' . $e->getMessage() . '

'; - if ($this->session() == self::ADMIN) { - echo '

Go to the Admin Panel to edit your database credentials

'; - } else { - echo '

Logout and and come back with an admin password to edit the database connexions settings.

'; - } - } else { - echo '

Homepage for admin login (connect on the top right side)

'; - } - exit; - } - - return $caught; - - } - - - public static function setdb() - { - $caught = true; - - try { - self::$db = new PDO('mysql:host=' . Config::host() . ';dbname=' . Config::dbname() . ';charset=utf8', Config::user(), Config::password(), array(PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT)); - //$this->bdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - } catch (PDOException $e) { - $caught = false; - echo '

Error 500, database offline

'; - if ($this->session() >= self::EDITOR) { - echo '

Error : ' . $e->getMessage() . '

'; - if ($this->session() == self::ADMIN) { - echo '

Go to the Admin Panel to edit your database credentials

'; - } else { - echo '

Logout and and come back with an admin password to edit the database connexions settings.

'; - } - } else { - echo '

Homepage for admin login (connect on the top right side)

'; - } - exit; - } - - return $caught; - - } - - public function settable(Config $config) - { - if (!empty(Config::arttable())) { - $this->arttable = Config::arttable(); - } else { - echo '

Table Error

'; - - if ($this->session() >= self::EDITOR) { - if ($this->session() == self::ADMIN) { - echo '

Go to the Admin Panel to select or add an Article table

'; - } else { - echo '

Logout and and come back with an admin password to edit table settings.

'; - } - } else { - echo '

Homepage for admin login (connect on the top right side)

'; - } - $caught = false; - exit; - } - } - - public function bddinit(Config $config) - { - $test = $this->setbdd($config); - if ($test) { - $this->settable($config); - } - } - - - - public function tableexist($dbname, $tablename) - { - - $req = $this->bdd->prepare('SELECT COUNT(*) - FROM information_schema.tables - WHERE table_schema = :dbname AND - table_name like :tablename'); - $req->execute(array( - 'dbname' => $dbname, - 'tablename' => $tablename - )); - $donnees = $req->fetch(PDO::FETCH_ASSOC); - $req->closeCursor(); - $exist = intval($donnees['COUNT(*)']); - return $exist; - - - - } - - public function tablelist($dbname) + public function __construct() { - $request = 'SHOW TABLES IN ' . $dbname; - $req = $this->bdd->query($request); - $donnees = $req->fetchAll(PDO::FETCH_ASSOC); - $req->closeCursor(); - - $arttables = []; - foreach ($donnees as $table) { - $arttables[] = $table['Tables_in_' . $dbname]; - } - return $arttables; - - + $this->dbinit(); } - - - - public function tableduplicate($dbname, $arttable, $tablename) + public function dbinit() { - $arttable = strip_tags($arttable); - $tablename = str_clean($tablename); - if ($this->tableexist($dbname, $arttable) && !$this->tableexist($dbname, $tablename)) { - $duplicate = " CREATE TABLE `$tablename` LIKE `$arttable`;"; - $alter = "ALTER TABLE `$tablename` ADD PRIMARY KEY (`id`);"; - $insert = "INSERT `$tablename` SELECT * FROM `$arttable`;"; - - - $req = $this->bdd->query($duplicate . $alter . $insert); - - return 'tableduplicated'; - } else { - return 'tablealreadyexist'; - } + $this->database = new \JamesMoss\Flywheel\Config(__DIR__ .'/../../w_database'); + $this->artstore = new \JamesMoss\Flywheel\Repository(Config::arttable(), $this->database); } - } -- cgit v1.2.3