<?php

class wpFlashMessages {
    const ATTRIBUTE_NAMESPACE = 'symfony/wpFlashMessages';

    static $names = array('error', 'warning', 'confirmation', 'information');

    protected static function add($name, $message) {
        $message = trim($message);
        if (!empty($message)) {
            $messages = self::get($name);
            $messages[] = $message;
            self::set($name, $messages);
        }
    }

    public static function addError($message) {
        self::add('error', $message);
    }

    public static function addWarning($message) {
        self::add('warning', $message);
    }

    public static function addConfirmation($message) {
        self::add('confirmation', $message);
    }

    public static function addInformation($message) {
        self::add('information', $message);
    }

    public static function count() {
        $count = 0;
        foreach(self::$names as $name) {
            $count += count(self::get($name));
        }
        return $count;
    }

    public static function purge() {
        $flash_messages = array();
        foreach(self::$names as $name) {
            $messages = self::get($name);
            if (count($messages) > 0) {
                $flash_messages[$name] = $messages;
            }
            sfContext::getInstance()->getUser()->setAttribute($name, null, self::ATTRIBUTE_NAMESPACE);
        }
        return $flash_messages;
    }

    protected static function set($name, $value) {
        sfContext::getInstance()->getUser()->setAttribute($name, $value, self::ATTRIBUTE_NAMESPACE);
    }

    protected static function get($name) {
        return sfContext::getInstance()->getUser()->getAttribute($name, array(), self::ATTRIBUTE_NAMESPACE);
    }
}