Created
January 29, 2021 21:43
-
-
Save rgadon107/a312af2dc31e8c5d77c2085509e7390b to your computer and use it in GitHub Desktop.
Solution to Code Challenge 5 from "Refactoring Tweaks Workbook"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Code Challenge 5, from “Refactoring Tweaks Workbook” by Tonya Mork ( 2016, LeanPub (https://leanpub.com/littlegreenbookofrefactoringtweaks-workbook) ). */ | |
/*************************************************** | |
* | |
* Original code to be refactored. | |
* | |
**************************************************/ | |
class Session { | |
/** | |
* Flag whether or not the internal collection has been changed. | |
* | |
* @var bool | |
*/ | |
protected $dirty = false; | |
.. | |
/** | |
* Write the data from the current session to the data storage system. | |
*/ | |
public function write_data() { | |
$option_key = "_prefix_session_{$this->session_id}"; | |
// Only write the collection to the DB if it's changed. | |
if ( $this->dirty ) { | |
if ( false === get_option( $option_key ) ) { | |
add_option( "_prefix_session_{$this->session_id}", $this->container, '', 'no' ); | |
add_option( "_prefix_session_expires_{$this->session_id}", $this->expires, '', 'no' ); | |
} else { | |
delete_option( "_prefix_session_{$this->session_id}" ); | |
add_option( "_prefix_session_{$this->session_id}", $this->container, '', 'no' ); | |
} | |
} | |
} | |
.. | |
} | |
/*************************************************** | |
* | |
* Refactored Code | |
* | |
**************************************************/ | |
class Session { | |
/** | |
* Flag whether or not the internal collection has been changed. | |
* | |
* @var bool | |
*/ | |
protected $dirty = false; | |
/** | |
* Write the data from the current session to the data storage system. | |
*/ | |
public function write_data() { | |
if ( ! $this->is_dirty() ) { | |
return; | |
} | |
$this->write_collection_to_db(); | |
} | |
protected function is_dirty( $dirty ) { | |
return $dirty = true; | |
} | |
protected function write_collection_to_db() { | |
$option_key = "_prefix_session_{$this->session_id}"; | |
if ( false === get_option( $option_key ) ) { | |
add_option( "_prefix_session_{$this->session_id}", $this->container, '', 'no' ); | |
add_option( "_prefix_session_expires_{$this->session_id}", $this->expires, '', 'no' ); | |
} else { | |
delete_option( "_prefix_session_{$this->session_id}" ); | |
add_option( "_prefix_session_{$this->session_id}", $this->container, '', 'no' ); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment