4 * This file is part of the Behat Testwork.
5 * (c) Konstantin Kudryashov <ever.zet@gmail.com>
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
11 namespace Behat\Testwork\Exception;
13 use Behat\Testwork\Exception\Stringer\ExceptionStringer;
14 use Behat\Testwork\Output\Printer\OutputPrinter;
18 * Presents exceptions as strings using registered stringers.
20 * @author Konstantin Kudryashov <ever.zet@gmail.com>
22 final class ExceptionPresenter
30 * @var ExceptionStringer[]
32 private $stringers = array();
36 private $defaultVerbosity = OutputPrinter::VERBOSITY_NORMAL;
39 * Initializes presenter.
41 * @param string $basePath
42 * @param integer $defaultVerbosity
44 public function __construct($basePath = null, $defaultVerbosity = OutputPrinter::VERBOSITY_NORMAL)
46 if (null !== $basePath) {
47 $realBasePath = realpath($basePath);
50 $basePath = $realBasePath;
54 $this->basePath = $basePath;
55 $this->defaultVerbosity = $defaultVerbosity;
59 * Registers exception stringer.
61 * @param ExceptionStringer $stringer
63 public function registerExceptionStringer(ExceptionStringer $stringer)
65 $this->stringers[] = $stringer;
69 * Sets default verbosity to a specified level.
71 * @param integer $defaultVerbosity
73 public function setDefaultVerbosity($defaultVerbosity)
75 $this->defaultVerbosity = $defaultVerbosity;
79 * Presents exception as a string.
81 * @param Exception $exception
82 * @param integer $verbosity
86 public function presentException(Exception $exception, $verbosity = null)
88 $verbosity = $verbosity ?: $this->defaultVerbosity;
90 foreach ($this->stringers as $stringer) {
91 if ($stringer->supportsException($exception)) {
92 return $this->relativizePaths($stringer->stringException($exception, $verbosity));
96 if (OutputPrinter::VERBOSITY_VERY_VERBOSE <= $verbosity) {
97 return $this->relativizePaths(trim($exception));
100 return trim($this->relativizePaths($exception->getMessage()) . ' (' . get_class($exception) . ')');
104 * Relativizes absolute paths in the text.
106 * @param string $text
110 private function relativizePaths($text)
112 if (!$this->basePath) {
116 return str_replace($this->basePath . DIRECTORY_SEPARATOR, '', $text);