From 5d01e62a381375475ace39b9c288189db5c60e1c Mon Sep 17 00:00:00 2001 From: Lenivene Bezerra Date: Mon, 21 Oct 2019 00:14:14 -0300 Subject: [PATCH 1/2] Add unique ID Generate a unique ID when insert value --- src/JSONDB.php | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/JSONDB.php b/src/JSONDB.php index 1657183..98cc09f 100644 --- a/src/JSONDB.php +++ b/src/JSONDB.php @@ -110,12 +110,17 @@ public function update( array $columns ) { * * @param string $file json filename without extension * @param array $values Array of columns as keys and values + * @param bool $_id Generate a unique ID * * @return array $last_indexes Array of last index inserted */ - public function insert( $file, array $values ) : array { + public function insert( $file, array $values, $_id = true ) : array { $this->from( $file ); + if( $_id ) { + $values['_id'] = uniqid( '', false ); + } + if( !empty( $this->content[ 0 ] ) ) { $nulls = array_diff_key( ( array ) $this->content[ 0 ], $values ); if( $nulls ) { From af7bd8138ba419ff2fa75a442f27752476eeae5e Mon Sep 17 00:00:00 2001 From: Lenivene Bezerra Date: Sat, 25 Jan 2020 11:36:40 -0300 Subject: [PATCH 2/2] Generate IDs like MongoDB --- src/JSONDB.php | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/src/JSONDB.php b/src/JSONDB.php index 98cc09f..f83c39f 100644 --- a/src/JSONDB.php +++ b/src/JSONDB.php @@ -118,7 +118,24 @@ public function insert( $file, array $values, $_id = true ) : array { $this->from( $file ); if( $_id ) { - $values['_id'] = uniqid( '', false ); + $bin = sprintf( + "%s%s%s%s", + pack('N', time()), + substr(md5(php_uname('n')), 0, 3), + pack('n', getmypid()), + substr(pack('N', mt_rand(0, mt_getrandmax())), 1, 3) + ); + + $_id = ''; + for ($i = 0; $i < 12; $i++) { + $_id .= sprintf("%02x", ord($bin[$i])); + } + + /** + * Generate ID like MongoDB + * @author Julius Beckmann + */ + $values['_id'] = $_id; } if( !empty( $this->content[ 0 ] ) ) {