Error.php 1.87 KB
Newer Older
Indra Raja's avatar
Indra Raja committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
<?php
namespace Khansia\Generic;

class Error extends Result {

  protected $_level;
  protected $_trace = array();

  public function __construct($guid = 0, $code = self::CODE_SUCCESS, $info = self::INFO_SUCCESS, $owner = null, $level = E_USER_NOTICE) {

    $this->_level = $level;
    parent::__construct($guid, $code, $info);
    parent::extend('owner', $owner);
  }

  public function clear() {

    parent::clear();
    $this->owner = null;
    $this->_trace = array();
  }

  public function trace($text) {

    if (is_array($text)) {
      foreach ($text as $item) {
        $this->_trace[] = $item;
      }
    } else {
      $this->_trace[] = $text;
    }
  }

  public function merge(Error $error) {

    $data = $error->toArray();
    $count = 0;

    if (count($data['trace']) > 0) {
      foreach ($data['trace'] as $trace) {
        $this->trace($trace);
        $count++;
      }
    }

    if ($data['info']) {
      $this->trace($data['info']);
      $count++;
    }

    return $count;
  }

  public function display($html = true) {

    if ($html) { echo('<pre>'); }
    echo($this->toString() . "\n");
    if ($html) { echo('</pre>'); }
    return true;
  }

  public function log() {

    return error_log($this->toString());
  }

  public function trigger() {

    return trigger_error($this->toString(), $this->_level);
  }

  public function toString() {

    $out = 'Trace for owner ' . ($this->owner ? $this->owner : 'global') . ' at ' . date('Y-m-d H:i:s') . " {\n" .
           '  Code #' . $this->code . ': ' . $this->info . "\n";
    foreach ($this->_trace as $text) {
      $out .= '  : ' . $text . "\n";
    }
    $out .= "}";

    return $out;
  }

  public function toArray() {

    return array_merge(parent::toArray(), array(
      'owner' => $this->owner,
      'trace' => $this->_trace,
    ));
  }

  public function toJson() {

    return json_encode($this->toArray());
  }
}