Last active
August 30, 2016 16:58
-
-
Save roukmoute/d97ed37620f6c0a20cdc to your computer and use it in GitHub Desktop.
Exception with possibility to use a formatted string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Exception; | |
class Exception extends \Exception | |
{ | |
/** | |
* @param string $message | |
* @param string|array $arguments | |
* @param int $code | |
* @param Exception|null $previous | |
*/ | |
public function __construct($message = '', $arguments, $code = 0, Exception $previous = null) | |
{ | |
parent::__construct(vsprintf($message, $this->formatArguments($arguments)), $code, $previous); | |
} | |
private function formatArguments($arguments) | |
{ | |
if (!is_array($arguments)) { | |
$arguments = [$arguments]; | |
} | |
foreach ($arguments as $key => &$value) { | |
$value = $this->varToString($value); | |
} | |
return $arguments; | |
} | |
private function varToString($var) | |
{ | |
if (is_object($var)) { | |
return sprintf('Object(%s)', get_class($var)); | |
} | |
if (is_array($var)) { | |
$a = []; | |
foreach ($var as $k => $v) { | |
$a[] = sprintf('%s => %s', $k, $this->varToString($v)); | |
} | |
return sprintf('Array(%s)', implode(', ', $a)); | |
} | |
if (is_resource($var)) { | |
return sprintf('Resource(%s)', get_resource_type($var)); | |
} | |
if (null === $var) { | |
return 'null'; | |
} | |
if (false === $var) { | |
return 'false'; | |
} | |
if (true === $var) { | |
return 'true'; | |
} | |
return (string) $var; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment