Skip to content

Instantly share code, notes, and snippets.

@dana-ross
Last active January 4, 2016 13:09
Show Gist options
  • Select an option

  • Save dana-ross/8625999 to your computer and use it in GitHub Desktop.

Select an option

Save dana-ross/8625999 to your computer and use it in GitHub Desktop.
WP_Session mods to recursively check dirty flag
/**
* Write the data from the current session to the data storage system.
*/
public function write_data() {
$option_key = "_wp_session_{$this->session_id}";
// Only write the collection to the DB if it's changed.
$this->recursive_dirty_check( $this );
if ( $this->dirty ) {
if ( false === get_option( $option_key ) ) {
add_option( "_wp_session_{$this->session_id}", $this->container, '', 'no' );
add_option( "_wp_session_expires_{$this->session_id}", $this->expires, '', 'no' );
}
else {
delete_option( "_wp_session_{$this->session_id}" );
add_option( "_wp_session_{$this->session_id}", $this->container, '', 'no' );
}
}
}
/**
* Recursively walk all nodes of this session's container to check dirty status.
* Modeled on array_walk_recursive() but visits all nodes, not just leaves
*
* @param mixed $node
* @param WP_Session $top_node optional - do not specify on the first call
*
* @return WP_Session
*/
private function recursive_dirty_check( $node, WP_Session &$top_node = null ) {
if ( null === $top_node ) {
// First call. Set things up and start recursing.
$top_node = $node;
return $this->recursive_dirty_check( $node->container, $top_node );
}
elseif ( $top_node->dirty ) {
// Don't recurse further if we already know the data is dirty
return $top_node;
}
elseif ( $node instanceof Recursive_ArrayAccess ) {
$top_node->dirty = $top_node->dirty || $node->dirty;
if ( ! $top_node->dirty ) {
$top_node->dirty = $top_node->dirty || $this->recursive_dirty_check( $node->container, $top_node );
}
}
elseif ( is_array( $node ) ) {
foreach ( $node as $value ) {
if ( ! $top_node->dirty ) {
$top_node->dirty = $top_node->dirty || $this->recursive_dirty_check( $value, $top_node );
}
}
}
return $top_node;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment