/trasweb/common/helpers/Notice.class.php
PHP | 283 lines | 173 code | 38 blank | 72 comment | 23 complexity | eefda624f531f688d41328d7879b1c01 MD5 | raw file
Possible License(s): BSD-3-Clause
- <?php
- /**
- New Licence bsd:
- Copyright (c) <2012>, Manuel Jesus Canga Muñoz
- All rights reserved.
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
- * Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in the
- documentation and/or other materials provided with the distribution.
- * Neither the name of the Trasweb.net nor the
- names of its contributors may be used to endorse or promote products
- derived from this software without specific prior written permission.
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- DISCLAIMED. IN NO EVENT SHALL Manuel Jesus Canga Muñoz BE LIABLE FOR ANY
- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
- /** **************************************************************************************
- Sistema de notificaciones/Avisos/Alertas. Muy útil para devolver mensajes fácilmente al usuario
- de la web después de que este haya realizado alguna operación.
- Se basa en proceso, un proceso puede tener éxito o pudo tener un error crítico.
- A su vez, los pasos del proceso, pudieron tener avisos informátivos o avisos de errores(normales).
- También, pudo haber otro tipo de errores, ocasionados por el sistema(fallo de acceso a la bd, un archivo que no se encuentra, ...
- *************************************************************************************** */
- class Notice
- {
- /** Errores posibles en php. Si tiene asociado un 1 es que puede continuar a pesar del error. 0 es que no es posible continuar */
- static public $php_errors = array(
- E_ERROR => 0, E_WARNING => 0, E_PARSE => 0, E_NOTICE => 1, E_CORE_ERROR => 0,E_CORE_WARNING => 1, E_COMPILE_ERROR => 0,
- E_COMPILE_WARNING => 1, E_USER_ERROR => 0, E_USER_WARNING => 1, E_USER_NOTICE => 1, E_STRICT => 1, E_RECOVERABLE_ERROR => 0,
- E_DEPRECATED => 1, E_USER_DEPRECATED => 1
- );
-
- static public $php_errors_code = array(
- E_ERROR => "E_ERROR", E_WARNING => "E_WARNING", E_PARSE => "E_PARSE", E_NOTICE => "E_NOTICE", E_CORE_ERROR => "E_CORE_ERROR",
- E_CORE_WARNING => "E_CORE_WARNING", E_COMPILE_ERROR => "E_COMPILE_ERROR", E_COMPILE_WARNING => "E_COMPILE_WARNING",
- E_USER_ERROR => "E_USER_ERROR", E_USER_WARNING => "E_USER_WARNING", E_USER_NOTICE => "E_USER_NOTICE", E_STRICT => "E_STRICT",
- E_RECOVERABLE_ERROR => "E_RECOVERABLE_ERROR", E_DEPRECATED => "E_DEPRECATED", E_USER_DEPRECATED => "E_USER_DEPRECATED"
- );
- /** Tipos de avisos: */
- const INFO = 1; //Información de lo que está ocurriendo(suele terminar en un SUCCESS ).
- const SUCCESS = 0; //El proceso entero, del módulo, ha tenido éxito
- const WARNING = 2; //Es un error que se da, en una de las operaciones del proceso.(warning)
- const ERROR = 3; //Error en el proceso, del módulo, que se esperaba realizar..
- const SYSTEM = 4; //Error producido de manera externa al framework(bbdd, clase, ...
- static private $types = array( self::SUCCESS => "SUCCESS", self::INFO => "INFO", self::WARNING => "WARNING", self::ERROR => "ERROR");
- /** indice de la cola de mensajes. */
- static private $index = 0;
- /** listado de avisos ( notices[$index][$tipo][] = msg */
- static public $notices = array();
- /** avisos del nivel superior que ya no existen */
- static public $last = array();
- /** Carga de comienzo de la clase */
- public static function load() { }
-
- /** Inicializador de la clase */
- public static function __initialize() {
- ini_set('display_errors', 0);
- // Report all PHP errors
- error_reporting(E_ALL );
- set_error_handler( array( '\Notice', 'errorEnviroment' ),E_ALL );
- register_shutdown_function(array( '\Notice', 'fatalError' ));
- if(!function_exists("Notice") ) {
- function Notice($_msg = NULL ) { Notice::send($_msg); }
- }
-
- self::$notices[0] = array( "SUCCESS" => NULL, "INFO" => array(), "WARNING" => array(), "ERROR" => NULL);
- }
- public static function type($_type) { return self::$types[$_type]; }
- /** Empezamos la captura de avisos, dentro del bloque. */
- public static function up() {
- self::$index++;
- self::$notices[self::$index] = array( "SUCCESS" => NULL, "INFO" => array(), "WARNING" => array(), "ERROR" => NULL);
- }
- /** Terminamos la captura de avisos, dentro del bloque en el que estamos */
- public static function down()
- {
- //Guardamos el listado de avisos del nivel actual.
- \State::setNotices(self::$notices[self::$index]);
-
-
- //Hacemos una copia del nivel antes de bajarlo
- self::$last = self::$notices[self::$index];
- //Borramos los avisos del nivel actual
- //ya que hemos hecho una copia
- unset(self::$notices[self::$index]);
- self::$index = ( ( self::$index -1 ) < 0 ) ? 0 : self::$index - 1; //Bajamos la cola
- }
- /**
- Mandamos un aviso a la cola, con un mensaje($_msg) y especificando el self::type($_type)
- @param @_msg es el mensage del aviso
- @param $_type el tipo de aviso ocurrido
- */
- public static function send($_msg = "", $_type = self::WARNING, $_code = NULL )
- {
- if(empty($_msg) ) return ;
-
- if($_type != self::SYSTEM ) {
- //Sino es un mensaje del sistema.
- $_name_type = self::type($_type);
- if( $_type == self::WARNING || $_type == self::INFO ) {
- if(is_array($_msg) ){
- //si es un array de mensajes lo mezclamos con los que hay
- self::$notices[self::$index][$_name_type] = array_merge(self::$notices[self::$index][$_name_type], $_msg);
- }else {
- self::$notices[self::$index][$_name_type][] = $_msg;
- }
- }else {//Se supone que si es exito o critico, sólo habrá un mensaje
- self::$notices[self::$index][$_name_type] = $_msg;
- }
- }else {
- \Debug::getFileLine($_file, $_line);
- //En caso de ser un error del sistema, lo tratamos directamente.
- self::errorSystem($_msg, $_code, $_file, $_line);
- }
- }
- public static function system($_msg, $_code = NULL) {
- \Debug::getFileLine($_file, $_line);
- self::errorSystem($_msg, $_code, $_file, $_line);
- return false;
- }
- public static function success($_msg) { self::send($_msg, self::SUCCESS); return true; }
- public static function info($_msg) { self::send($_msg, self::INFO); }
- public static function warning($_msg) { self::send($_msg, self::WARNING); }
- public static function error($_msg) { self::send($_msg, self::ERROR); return false; }
- public static function ok($_msg) { self::send($_msg, self::SUCCESS); return true; }
- public static function nok($_msg) { self::send($_msg, self::ERROR); return false; }
- /**
- Devuelve un listado con todos los Avisos del nivel actual o del nivel $_index
- @param $_index el nivel del que se quiere los vaisos.
- @param $_type por si queremos filtrar los avisos por un determinado tipo.
- */
- public static function get($_type = NULL, $_index = NULL)
- {
- if ($_index == NULL ) $_index = self::$index;
- if ($_type != NULL ) {
- $_name_type = self::type($_type);
- if(array_key_exists($_name_type,self::$notices[$_index]) ) {
- return self::$notices[$_index][$_name_type];
- } else {
- return array();
- }
- }else
- return self::$notices[$_index];
- }
- public static function getSuccess() { return self::get(self::SUCCESS); }
- public static function getInfos() { return self::get(self::INFO); }
- public static function getWarnings(){ return self::get(self::WARNING); }
- public static function getError() { return self::get(self::ERROR); }
- public static function getAll() { return self::all(); }
- public static function getLast() { return self::$last; }
-
- /** Devuelve todos los avisos, independientemente del nivel */
- public static function all() { return self::$notices; }
- /**
- Comprueba si hubo algun aviso del tipo especificado, en el nivel actual
- @param $_type es el tipo del que se quiere comprobar si hay o no, aviso.
- @return true|false, true si lo hubo, false sino.
- */
- public static function check($_type = self::ERROR )
- {
- $_type = self::type($_type);
- return array_key_exists($_type,self::$notices[self::$index]) && !empty(self::$notices[self::$index][$_type]);
- }
-
- public static function checkSuccess() { return self::check(self::SUCCESS); }
- public static function checkInfos() { return self::check(self::INFO); }
- public static function checkWarnings() { return self::check(self::WARNING); }
- public static function checkError() { return self::check(self::ERROR); }
- /** Se añade aquí la vista, porque puede que haya sido error a cargar la vista, y sería una tontería intentar cargar otra vista Daría un error recursivo
- @param $_error es el texto de error que se quiere presentar */
- public static function errorSystem($_msg, $_code, $_file = NULL, $_line = NULL)
- {
- if(null == $_file && null == $_line) {
- \Debug::getFileLine($_file, $_line);
- }
-
- //@error_log($_error, 0);
- $e = new System_Error($_msg, $_code);
- $e->setFile($_file);
- $e->setLine($_line);
- throw $e;
- }
-
- private static function showError($_errno, $_errstr, $_errfile, $_errline, $_context = array()) {
- $namespace = \State::getNamespace();
- $file = $_errfile;
- $line = $_errline;
- if(array_key_exists("_smarty_tpl", $_context) ) {
- $context = "| Smarty template ";
- $title = " Error in template";
- $file = PATH.$_context["_smarty_tpl"]->template_resource;
- $line = "..";
- $_errfile = $file;
- }else if(!empty($_context) ) {
- $context = "| context: ".print_r($_context, true);
- $title = " Error in System";
- }else {
- $context = "";
- $title = "";
- }
-
- Debug::info("[{$namespace}][".self::$php_errors_code[$_errno]."]: {$_errstr} . file {$_errfile} {$context} ", $title, $file, $line);
- }
-
- public static function errorEnviroment($_errno, $_errstr, $_errfile, $_errline, $_context = array()) {
- self::showError($_errno, $_errstr, $_errfile, $_errline, $_context);
- if(!self::$php_errors[$_errno] ) {
- //Es un error grave y necesita tratamiento.
- $SE = new System_Error($_errstr, '\\php\\', $_errno);
- $SE->setFile($_errfile);
- $SE->setLine($_errline);
- $SE->setNamespace(\State::getNamespace());
- throw $SE;
- }
-
-
- return true;
- }
-
- public static function fatalError() {
- $error = error_get_last();
- if (!empty($error) && array_key_exists("type", $error) && $error['type'] >= 0) {
- // fatal error
- self::showError($error['type'], $error['message'], $error['file'], $error['line']);
- $data = new Data($error);
- $data->state = \State::get();
- \Event("Critical", '\trasweb')->ocurred($data);
- }else {
- \State::down();
- }
- }
-
- public static function debug() {
- $backtrace = debug_backtrace();
- $file = $backtrace[0]["file"];
- $line = $backtrace[0]["line"];
-
- \Debug(self::$notices, "Notice Log", $file, $line);
- }
- }