From 0d474cbd22c0aff6f80bc978f1bdda60965d78ee Mon Sep 17 00:00:00 2001 From: Wakeel Ogunsanya Date: Sun, 6 Nov 2016 14:41:01 +0100 Subject: [PATCH 1/4] Delete License.md This is not required here --- License.md | 23 ----------------------- 1 file changed, 23 deletions(-) delete mode 100644 License.md diff --git a/License.md b/License.md deleted file mode 100644 index cbc8347..0000000 --- a/License.md +++ /dev/null @@ -1,23 +0,0 @@ -MIT License Copyright (c) 2016 Wakeel Ogunsanya -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and -associated documentation files (the "Software"), to -deal in the Software without restriction, including -without limitation the rights to use, copy, modify, -merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to -whom the Software is furnished to do so, subject to -the following conditions: The above copyright notice -and this permission notice shall be included in all -copies or substantial portions of the Software. THE -SOFTWARE IS PROVIDED "AS IS", WITHOUT -WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR -PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. MIT License From a96d4c7f22e239377938c8fd8308cad2d38e4321 Mon Sep 17 00:00:00 2001 From: Wakeel Ogunsanya Date: Sun, 6 Nov 2016 15:02:40 +0100 Subject: [PATCH 2/4] Added features and fixed bugs ##Bug fixes 1. Library was adding new index after the **php closing tag** for file tha ends with `?>` 2. Fixed bug where new empty index is added to config if the index to update is not empty ##New Features 1. Added three new constants `Array_Config_Writer::SKIP_IF_EXIST` `Array_Config_Writer::SKIP_CREATE_IF_NOT_EXIS`T `Array_Config_Writer:: CREATE_OR_UPDATE` 1. write() method third parameter uses the predefined constant to determine how to handle updating index 2. write() method throws exception if the third argument does match any of required constant 3. The library removes white space from file using trim() 4. Added public method to check error `hasError()` --- class-array-config-writer.php | 139 +++++++++++++++++++++++++--------- 1 file changed, 105 insertions(+), 34 deletions(-) diff --git a/class-array-config-writer.php b/class-array-config-writer.php index 02e74d1..ea3c66a 100644 --- a/class-array-config-writer.php +++ b/class-array-config-writer.php @@ -4,12 +4,25 @@ Copyright 2016 Wakeel Ogunsanya Licensed under GPLv2 or above -Version 1.1.0 +Version 1.2.0 */ class Array_Config_Writer { - + /** + * Skip updating the index if the index acctually exist + * + * This will also create new index if not exist + */ + const SKIP_IF_EXIST = 0; + /** + * Skip creating new index if the specified index is not found + */ + const SKIP_CREATE_IF_NOT_EXIST = 1; + /** + * Update or create the index + */ + const CREATE_OR_UPDATE = 2; /** * The config file to write * @@ -117,18 +130,19 @@ public function __construct($config_file , $variable_name = '\$config' , $auto_s * will be array( 'default' , 'hostname' ) * * @param mixed $replacement - * @param boolean $skip_if_exists Skip updating item if already exists + * @param boolean $write_method Skip updating item if already exists * @param null|array $comments Comment to add to the top of item (new item), each element * will be placed oon a new line. * is added before each line , meaning * you dont have to put /** or * unless you want it show + * @throws Exception * - * @note you can not update existing item comment + * @note you can not update existing item comment * * * @return boolean * */ - public function write( $index = null, $replacement = null , $skip_if_exists = FALSE , $comments = null) + public function write( $index = null, $replacement = null , $write_method = self::CREATE_OR_UPDATE , $comments = null ) { // error exists in the constructor? if($this->_lastError) @@ -136,6 +150,8 @@ public function write( $index = null, $replacement = null , $skip_if_exists = F return $this; } + $this->_fileContent = trim($this->_fileContent); + if(!$index) { $this->_lastError = 'You must set index you want to update' ; @@ -163,47 +179,78 @@ public function write( $index = null, $replacement = null , $skip_if_exists = F // well config aleady exists // may be is application upgrade :) we wouldnt wana overide user settings - if( $skip_if_exists ) + if( $write_method == self::SKIP_IF_EXIST ) { return $this; } // update th content $this->_fileContent = preg_replace( $regex , '$1$2 = ' . var_export( $replacement , true ) , $this->_fileContent ) ; } - else{ - // new item here - $mark .= var_export( $replacement , true ) . ' ;' ; - $mark .= "\n" ; - - if(is_array($comments) && count($comments) > 0 ) + // config item doesnt exist yet create new index if reqyuired + else + { + switch ($write_method) { - // add the comment - $comment_str .= '/**' ; - $comment_str .= "\n" ; - foreach ($comments as $line) - { - $comment_str .= ' * ' . $line . "\n" ; - } - // close the comment - $comment_str .= '*/' . "\n"; - } + case self::SKIP_CREATE_IF_NOT_EXIST: + return $this; + case self::CREATE_OR_UPDATE: + case self::SKIP_IF_EXIST: - // lets try remove traling slash from the variable name since - // we are writing php here - if ( substr($mark, 0 , 1) == '\\' ) - { - $mark = substr($mark, 1 ); + // new item here + $mark .= var_export( $replacement , true ) . ' ;' ; + $mark .= "\n" ; + $mark .= "\n" ; + + // add comment if provided + if(is_array($comments) && count($comments) > 0 ) + { + //open comment + $comment_str .= '/**' ; + $comment_str .= "\n" ; + foreach ($comments as $line) + { + $comment_str .= ' * ' . $line . "\n" ; + } + // close the comment + $comment_str .= '*/' . "\n"; + } + + // lets try remove traling slash from the variable name since + // we are writing php here + if ( substr($mark, 0 , 1) == '\\' ) + { + $mark = substr($mark, 1 ); + } + + // we have updated the index, the file will save automatically in the class shutdwon + // we did this allow update multiple index by call write() method as manay times + // as required + // + + // check if the file has php closing tag + if(substr($this->_fileContent, -2) === '?>' ) + { + // remove the closing tag before adding our new item + $this->_fileContent = substr($this->_fileContent, 0 , -2). "\n" . $comment_str . "\n" . $mark . ' ?>' ; + } + else + { + $this->_fileContent = $this->_fileContent . "\n" . $comment_str . "\n" . $mark . "\n" ; + } + break; + case self::SKIP_CREATE_IF_NOT_EXIST: + return $this; + default : + throw new Exception('Class: '.__CLASS__ .' Method :'.__METHOD__.'third parameter is invalid. Use the class constant'); } - // we have updated the index, the file will save automatically in the class shutdwon - // we did this allow update multiple index by call write() method as manay times - // as required - $this->_fileContent = $this->_fileContent . "\n" . $comment_str . "\n" . $mark . "\n" ; } return $this; } /** - * Update the variable name of the array config + * Update the file name of the array config + * + * You will olnly do this to transfer the php file content to another file * * @param string $name * @@ -226,7 +273,12 @@ public function setFilename($name = null) public function setVariableName($name = null) { - + if(!is_string($name)) + { + $this->_lastError = 'Variable name not string: '. $name; + return $this; + } + if(substr($name, 1, 1 ) != '$') { $name = '$' . $name ; @@ -271,8 +323,16 @@ public function save() } return $this; } - + /** + * Check if any error has occured + * + * @return boolean + */ + public function hasError() + { + return !empty($this->_lastError); + } /** * Get last error that occured * @@ -282,4 +342,15 @@ public function getLastError() { return $this->_lastError; } + + /** + * Set auto save option + * + * @since 1.1.1 + * @param boolean $option + */ + public function setAutoSave($option = true) + { + $this->_autoSave = $option; + } } From 2fb3de0f8269b1a65f511e4099822f77df3cec35 Mon Sep 17 00:00:00 2001 From: Wakeel Ogunsanya Date: Mon, 7 Nov 2016 12:04:03 +0100 Subject: [PATCH 3/4] Update class-array-config-writer.php Fixed bug where library not differentiating numeric from string --- class-array-config-writer.php | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/class-array-config-writer.php b/class-array-config-writer.php index ea3c66a..ade3d84 100644 --- a/class-array-config-writer.php +++ b/class-array-config-writer.php @@ -4,7 +4,7 @@ Copyright 2016 Wakeel Ogunsanya Licensed under GPLv2 or above -Version 1.2.0 +Version 1.2.1 */ class Array_Config_Writer { @@ -163,14 +163,27 @@ public function write( $index = null, $replacement = null , $write_method = sel // add a mark in case config item doesnt exists $mark = "{$prefix}" ; // we can update multi dementional - $indece = is_array($index)? $index : array( $index ) ; + $indices = is_array($index)? $index : array( $index ) ; $comment_str = '' ; - foreach ( $indece as $index => $i) + foreach ( $indices as $i) { - $regex .= '\[\s*(\'|\")(' . $i . ')*(\'|\")\s*\]' ; - $mark .= "['{$i}']" ; + $is_int = is_int($i) ; + // we make sure we dont chenge the index type if its numeric + $new_item_index = $is_int? $i : "'$i'" ; + // if the index is int, we dont need ' or "" to be checked in the regex + $regex .= '\[\s*'; + $regex .= $is_int? '' : '(\'|\")' ; + $regex .= '('.$i.')*'; + $regex .= $is_int? '' : '(\'|\")'; + $regex .= '\s*\]' ; + // Used before we seperated numeric index from string + //$regex .= '\[\s*(\'|\")(' . $i . ')*(\'|\")\s*\]' ; + + + $mark .= "[$new_item_index]" ; } + // closing $regex .= ')\s*=[^\;]*#' ; $mark .= " = "; @@ -212,7 +225,7 @@ public function write( $index = null, $replacement = null , $write_method = sel $comment_str .= ' * ' . $line . "\n" ; } // close the comment - $comment_str .= '*/' . "\n"; + $comment_str .= '*/'; } // lets try remove traling slash from the variable name since From b5d82ceea4c43aaac2b59ba9212451165ded5209 Mon Sep 17 00:00:00 2001 From: Wakeel Ogunsanya Date: Mon, 7 Nov 2016 12:12:04 +0100 Subject: [PATCH 4/4] Update README.md Updated to reflect the changes to the library --- README.md | 159 +++++++++++++++++++++++++++++++++--------------------- 1 file changed, 98 insertions(+), 61 deletions(-) diff --git a/README.md b/README.md index 8a18312..b74def4 100644 --- a/README.md +++ b/README.md @@ -1,90 +1,127 @@ -# array-config-writer -Write and update config item. This library was inspired by a CodeIgniter project when there was a need to permanently update the configuration values instead of setting configuration in every request. +# Array Config Writer -for instance, some of the codeigniter config file has $config array with different key and value-pairs as options. +This php library can be used to update array values in php a file. +Some applications use php array to store configuration values and to update the values +users will have to manually open the configuration file and update the value. -lets say we want to update the default language of the config +This library makes the task of updating the array easy. You programmatically update +the values of the array. +##Installation + +* Download the library and extract it in a folder of your application. The folder choice depends on your application. + + +##Usage +* Include the class library to be available for usage `require_once 'class-array-config-writer.php';` +* Create an instance of `Array_Config_Writer` class for the file that holds the php array we want to update + + $config_writer = new Array_Config_Writer($config_file, $variable_name , $auto_save ); + +Where : + +* **$config_file** (string) : The absolute path to the file where the array is place +* **$variable_name** (string) : The variable name of the array we want to update +* **$auto_save** (boolean) : Whether to automatically save the changes after the operation + +Supported variable Styles: +* `Single index $config[ 'key'] = 'value' ;` +* `Multi dimensional $config['key1']['key2'] = 'value';` + +You can not use the library to update something like `$config = array( 'key' => 'value' );` + +**Notes:** +* The library expect the variable to be indexed +* The file can have other variables aside our target variable + + +Now you can start updating the index of the array like this + + $config_writer->write('key' , value ); + +**Note:** +* You can set value to any php variable type +* The library treats numeric index as it is. Meaning '21' is different from 21 + +##Examples + +**PHP File** config.php + +```php /* |-------------------------------------------------------------------------- - | Default Language + | Site Name |-------------------------------------------------------------------------- | - | This determines which set of language files should be used. Make sure - | there is an available translation if you intend to use something other - | than english. + | | */ - $config['language'] = 'english'; - - $config['compress_output'] = false ; - -Lets say the path to config file is [PATH_TO_SITE_FILES]/config/config.php + $config[ 'site_name'] = 'Example Site'; -//include the Writer - require_once PATH_TO_SITE_FILES . 'libraries/array_config_writer/class-array-config-writer.php'; + /* + |-------------------------------------------------------------------------- + | Enable caching + |-------------------==------------------------------------------------------- + | + | + */ + $config[ 'enable_caching'] = true; - $congig_writer = new Array_Config_Writer( '[PATH_TO_SITE_FILES]/config/config.php' , 'config' ); + /* + |-------------------------------------------------------------------------- + | Custom Array + |-------------------==------------------------------------------------------- + | + | + */ + $config[ 'message'] = array( + 'title' => 'Welcome' , + 'body' => 'Thanks for your interest in the library' + ); - $congig_writer->write( 'language' , 'french' ) ; -And thats all. The value of $config['language'] in the [PATH_TO_SITE_FILES]/config/config.php will be updated to 'french' + /* + |-------------------------------------------------------------------------- + | Another Config Variable for the database + |-------------------==------------------------------------------------------- + | + | + */ + $db[ 'database'] = ''; + $db[ 'username'] = ''; +``` -now [PATH_TO_SITE_FILES]/config/config.php is +Create an instance of the library - /* - |-------------------------------------------------------------------------- - | Default Language - |-------------------------------------------------------------------------- - | - | This determines which set of language files should be used. Make sure - | there is an available translation if you intend to use something other - | than english. - | - */ - $config['language'] = 'french'; - - - -WHat if the $config array in '[PATH_TO_SITE_FILES]/config/config.php file does not have 'language' index? - -Well the the writer will create a new index of 'language' + $config_writer = new Array_Config_Writer( APP_PATH.'config/config.php', 'config' ); + + // update the site name -if you set the third parameter of write() method to true and the 'language' index already exists the writer will skip updating the index value. This can be useful on application upgrades + $config_writer->write('site_name' , "New Site Name' ); -Awesome right? +## Method chaining + $config_writer->write('site_name' , "New Site Name' )->write('enable_caching' , false ); -Features -=> Method chaining is allowed +To update the `'message'` index which has array has value - $congig_writer->write( 'language' , 'french' )->write('compress_output' , true ) ; +* First get the current value + $meesage = $config['message']; +* Then change its value(s) -=> if your config varible is multi dimentional array like - $db['default']['hostname'] = 'localhost' - -You can update the 'hostname' index like this - 1 . You either instatiate new class - - $congig_writer = new Array_Config_Writer( '[PATH_TO_SITE_FILES]/config/database.php' , 'db' ); - - $congig_writer->write( array( default' , 'hostname' ) , 'remotehost' ); - -or - -2. Update the config variable name for the config writer if '[PATH_TO_SITE_FILES]/config/config.php' has $db['default']['hostname'] index - - $congig_writer->setVariableName('db'); - $congig_writer->write( array( default' , 'hostname' ) , 'remotehost' ); - -Now every write() call will search for $db variable - - + $message['title'] = 'My New title' ; + $message['body'] = 'New message body' ; +* Or completely set new array for the message index + + // assuming the admin sent a form, Just an example, you should validate user post! :d + $message = $_POST['message']; +* Save it with the library - + $config_writer->write('message' , $message );