From d40e1309a61780f778cff8d901e6bad324698835 Mon Sep 17 00:00:00 2001 From: Christian Sander Date: Thu, 16 May 2019 06:05:04 +0200 Subject: [PATCH] Generate AutoId for new Records --- src/Config.php | 10 ++++++++++ src/Database.php | 50 +++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 59 insertions(+), 1 deletion(-) diff --git a/src/Config.php b/src/Config.php index 56c2d3b..dff804b 100644 --- a/src/Config.php +++ b/src/Config.php @@ -76,6 +76,16 @@ class Config */ public $validate = []; + /** + * $auto_id_mode + * + * how new ids are generated when no id is given + * Possible values: autoincrement/hash + * + * default autoincrement + */ + public $auto_id_mode = 'autoincrement'; + /** * __construct * diff --git a/src/Database.php b/src/Database.php index 40b189b..24ceda4 100644 --- a/src/Database.php +++ b/src/Database.php @@ -114,8 +114,12 @@ public function findAll($include_documents = true, $data_only = false) * * @return $document \Filebase\Document object */ - public function get($id) + public function get($id = null) { + if(is_null($id)) + { + $id = $this->getAutoId(); + } $content = $this->read($id); $document = new Document($this); @@ -132,6 +136,50 @@ public function get($id) return $document; } + /** + * getAutoId + * + * Generates a unique id + * + * @return mixed $id + */ + public function getAutoId() + { + $mode = $this->config->auto_id_mode; + + if($mode == 'hash') + { + do{ + // Build random id with 8 characters + $id = substr(md5(rand(0,1000000000)), 0, 8); + + // If id is unique break out of the loop + if(!$this->has($id)) break; + } while(0); + + // Return the found id + return $id; + }elseif($mode == 'autoincrement'){ + $files = Filesystem::getAllFiles( $this->config->dir, $this->config->format::getFileExtension()); + $id = 1; + + // Run through all available files and find max id + foreach($files as $file){ + // If filename contains letters or starts with zero ignore it + if (!preg_match('/^[1-9][0-9]*$/', $file)) + { + continue; + } + // If filename is bigger than current id then increase id + if(intval($file) >= $id) $id = intval($file) +1; + } + // Return the found id + return $id; + }else{ + throw new \Exception('Filebase Error: Unknown Autoid Mode.'); + } + } + /** * has *