<?php

/**
 * Flash messaging class
 * Implements the ArrayAccess interface
 * @author Jérôme Brilland
 * @version 1.0.1
 * @copyright (c) 2009-2019, Jérôme Brilland
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License
 */
class Flash implements ArrayAccess {

    /**
     * @var array
     * @access private
     */
    private $messages = array();

    public function set( $type, $message ) {
        $_SESSION['flash_messages'][$type] = $message;
    }

    public function get( $type ) {
        if ( empty( $this->messages[$type] ) ) {
            $this->messages[$type] = $_SESSION['flash_messages'][$type];
            unset( $_SESSION['flash_messages'][$type] );
        }
        return $this->messages[$type];
    }

    public function has( $type ) {
        return ( isset( $_SESSION['flash_messages'][$type] ) || isset( $this->messages[$type] ) );
    }

    public function notice( $message ) {
        $this->set( 'notice', $message );
    }

    public function warning( $message ) {
        $this->set( 'warning', $message );
    }

    public function error( $message ) {
        $this->set( 'error', $message );
    }

    public function success( $message ) {
        $this->set( 'success', $message );
    }

    /**
     * Whether or not an offset exists.
     * @param string offset An offset to check for.
     * @return boolean True if the offset exists, false otherwise.
     * @access public
     */
    public function offsetExists( $offset ) {
        return $this->has( $offset );
    }

    /**
     * Returns the value at specified offset.
     * @param string offset The offset to retrieve.
     * @return string The value at specified offset.
     * @access public
     */
    public function offsetGet( $offset ) {
        return $this->get( $offset );
    }

    /**
     * Assigns a value to the specified offset.
     * @param string offset The offset to assign the value to.
     * @param string value The value to set.
     * @access public
     */
    public function offsetSet( $offset, $value ) {
        $this->set( $offset, $value );
    }

    /**
     * Unsets an offset.
     * @param string offset The offset to unset.
     * @access public
     */
    public function offsetUnset( $offset ) {
        unset( $_SESSION['flash_messages'][$offset] );
    }

    /**
     * Discards all Flash variables
     * @access public
     */
    public function discard() {
        unset( $_SESSION['flash_messages'] );
    }

    /**
     * @return array An array containing all flash variables
     * @access public
     */
    public function getValues() {
        return $_SESSION['flash_messages'];
    }

    /**
     * Checks whether the Flash object is empty
     * @return boolean True if the flash object is empty, false otherwise.
     * @access public
     */
    public function isEmpty() {
        return empty( $_SESSION['flash_messages'] );
    }

}

