Skip to content
This repository has been archived by the owner on Jun 2, 2024. It is now read-only.

Generate AutoId for new Records #60

Open
wants to merge 1 commit into
base: 1.0
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*
Expand Down
50 changes: 49 additions & 1 deletion src/Database.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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
*
Expand Down