Repository: filp/whoops Branch: master Commit: 67342bc80785 Files: 76 Total size: 283.3 KB Directory structure: gitextract_qw9s0v9n/ ├── .editorconfig ├── .gitattributes ├── .github/ │ ├── FUNDING.yml │ └── workflows/ │ └── tests.yml ├── .gitignore ├── .mailmap ├── .scrutinizer.yml ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── SECURITY.md ├── composer.json ├── docs/ │ ├── API Documentation.md │ ├── Framework Integration.md │ ├── Open Files In An Editor.md │ └── Replay Errors.md ├── examples/ │ ├── example-ajax-only.php │ ├── example.php │ └── lib.php ├── phpunit.xml.dist ├── src/ │ └── Whoops/ │ ├── Exception/ │ │ ├── ErrorException.php │ │ ├── Formatter.php │ │ ├── Frame.php │ │ ├── FrameCollection.php │ │ └── Inspector.php │ ├── Handler/ │ │ ├── CallbackHandler.php │ │ ├── Handler.php │ │ ├── HandlerInterface.php │ │ ├── JsonResponseHandler.php │ │ ├── PlainTextHandler.php │ │ ├── PrettyPageHandler.php │ │ └── XmlResponseHandler.php │ ├── Inspector/ │ │ ├── InspectorFactory.php │ │ ├── InspectorFactoryInterface.php │ │ └── InspectorInterface.php │ ├── Resources/ │ │ ├── css/ │ │ │ ├── prism.css │ │ │ └── whoops.base.css │ │ ├── js/ │ │ │ ├── prism.js │ │ │ └── whoops.base.js │ │ └── views/ │ │ ├── env_details.html.php │ │ ├── frame_code.html.php │ │ ├── frame_list.html.php │ │ ├── frames_container.html.php │ │ ├── frames_description.html.php │ │ ├── header.html.php │ │ ├── header_outer.html.php │ │ ├── layout.html.php │ │ ├── panel_details.html.php │ │ ├── panel_details_outer.html.php │ │ ├── panel_left.html.php │ │ └── panel_left_outer.html.php │ ├── Run.php │ ├── RunInterface.php │ └── Util/ │ ├── HtmlDumperOutput.php │ ├── Misc.php │ ├── SystemFacade.php │ └── TemplateHelper.php └── tests/ ├── Whoops/ │ ├── Exception/ │ │ ├── FormatterTest.php │ │ ├── FrameCollectionTest.php │ │ ├── FrameTest.php │ │ └── InspectorTest.php │ ├── Handler/ │ │ ├── CallbackHandlerTest.php │ │ ├── JsonResponseHandlerTest.php │ │ ├── PlainTextHandlerTest.php │ │ ├── PrettyPageHandlerTest.php │ │ └── XmlResponseHandlerTest.php │ ├── RunTest.php │ ├── TestCase.php │ └── Util/ │ ├── HtmlDumperOutputTest.php │ ├── MiscTest.php │ ├── SystemFacadeTest.php │ └── TemplateHelperTest.php ├── bootstrap.php └── fixtures/ ├── frame.lines-test.php └── template.php ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ # http://editorconfig.org root = true [*] indent_style = space indent_size = 2 end_of_line = lf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true [*.{json,php}] indent_size = 4 [*.md] trim_trailing_whitespace = false ================================================ FILE: .gitattributes ================================================ docs/ export-ignore examples/ export-ignore tests/ export-ignore .github/ export-ignore .editorconfig export-ignore .gitattributes export-ignore .gitignore export-ignore .scrutinizer.yml export-ignore phpunit.xml.dist export-ignore CONTRIBUTING.md export-ignore README.md export-ignore ================================================ FILE: .github/FUNDING.yml ================================================ github: denis-sokolov ================================================ FILE: .github/workflows/tests.yml ================================================ name: Tests on: push: pull_request: jobs: tests: name: PHP ${{ matrix.php }} runs-on: ubuntu-22.04 strategy: matrix: php: ['7.1', '7.2', '7.3', '7.4', '8.0', '8.1', '8.2', '8.3', '8.4', '8.5'] steps: - name: Checkout Code uses: actions/checkout@v6 - name: Setup PHP uses: shivammathur/setup-php@v2 with: php-version: ${{ matrix.php }} tools: composer:v2 coverage: none env: update: true - name: Setup Problem Matchers run: echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json" - name: Fix PHPUnit Version PHP < 7.4 uses: nick-invision/retry@v3 with: timeout_minutes: 5 max_attempts: 5 command: composer require "phpunit/phpunit:^4.8.36 || ^5.7.27 || ^6.5.14 || ^7.5.20 || ^8.5.8" --dev --no-update --no-interaction if: "matrix.php < 7.4" - name: Fix PHPUnit Version PHP >= 7.4 uses: nick-invision/retry@v3 with: timeout_minutes: 5 max_attempts: 5 command: composer require "phpunit/phpunit:^9.3.3" --dev --no-update --no-interaction if: "matrix.php >= 7.4" - name: Install PHP Dependencies uses: nick-invision/retry@v3 with: timeout_minutes: 5 max_attempts: 5 command: composer update --no-interaction --no-progress - name: Execute PHPUnit run: vendor/bin/phpunit ================================================ FILE: .gitignore ================================================ composer.lock phpunit.xml report vendor ================================================ FILE: .mailmap ================================================ Denis Sokolov Filipe Dobreira ================================================ FILE: .scrutinizer.yml ================================================ imports: - php filter: paths: [src/*] tools: php_cs_fixer: config: { level: psr1 } php_hhvm: true php_mess_detector: true sensiolabs_security_checker: true external_code_coverage: timeout: '3600' ================================================ FILE: CHANGELOG.md ================================================ # CHANGELOG ## v2.18.0 * Line numbers are now clickable. ## v2.17.0 * Support cursor IDE. ## v2.16.0 * Support PHP `8.4`. * Drop support for PHP older than `7.1`. ## v2.15.4 * Improve link color in comments. ## v2.15.3 * Improve performance of the syntax highlighting (#758). ## v2.15.2 * Fixed missing code highlight, which additionally led to issue with switching tabs, between application and all frames ([#747](https://github.com/filp/whoops/issues/747)). ## v2.15.1 * Fixed bug with PrettyPageHandler "*Calling `getFrameFilters` method on null*" ([#751](https://github.com/filp/whoops/pull/751)). ## v2.15.0 * Add addFrameFilter ([#749](https://github.com/filp/whoops/pull/749)) ## v2.14.6 * Upgraded prismJS to version `1.29.0` due to security issue ([#741][i741]). [i741]: https://github.com/filp/whoops/pull/741 ## v2.14.5 * Allow `ArrayAccess` on super globals. ## v2.14.4 * Fix PHP `5.5` support. * Allow to use psr/log `2` or `3`. ## v2.14.3 * Support PHP `8.1`. ## v2.14.1 * Fix syntax highlighting scrolling too far. * Improve the way we detect xdebug linkformat. ## v2.14.0 * Switched syntax highlighting to Prism.js. Avoids licensing issues with prettify, and uses a maintained, modern project. ## v2.13.0 * Add Netbeans editor. ## v2.12.1 * Avoid redirecting away from an error. ## v2.12.0 * Hide non-string values in super globals when requested. ## v2.11.0 * Customize exit code. ## v2.10.0 * Better chaining on handler classes. ## v2.9.2 * Fix copy button styles. ## v2.9.1 * Fix xdebug function crash on PHP `8`. ## v2.9.0 * `JsonResponseHandler` includes the exception code. ## v2.8.0 * Support PHP 8. ## v2.7.3 * `PrettyPageHandler` functionality to hide superglobal keys has a clearer name (`hideSuperglobalKey`). ## v2.7.2 * `PrettyPageHandler` now accepts custom js files. * `PrettyPageHandler` and `templateHelper` is now accessible through inheritance. ## v2.7.1 * Fix a PHP warning in some cases with anonymous classes. ## v2.7.0 * Added `removeFirstHandler` and `removeLastHandler`. ## v2.6.0 * Fix 2.4.0 `pushHandler` changing the order of handlers. ## v2.5.1 * Fix error messaging in a rare case. ## v2.5.0 * Automatically configure xdebug if available. ## v2.4.1 * Try harder to close all output buffers. ## v2.4.0 * Allow to prepend and append handlers. ## v2.3.2 * Various fixes from the community. ## v2.3.1 * Prevent exception in Whoops when caught exception frame is not related to real file. ## v2.3.0 * Show previous exception messages. ## v2.2.0 * Support PHP `7.2`. ## v2.1.0 * Add a `SystemFacade` to allow clients to override Whoops behavior. * Show frame arguments in `PrettyPageHandler`. * Highlight the line with the error. * Add icons to search on Google and Stack Overflow. ## v2.0.0 Backwards compatibility breaking changes: * `Run` class is now `final`. If you inherited from `Run`, please now instead use a custom `SystemFacade` injected into the `Run` constructor, or contribute your changes to our core. * PHP < 5.5 support dropped. ================================================ FILE: CONTRIBUTING.md ================================================ If you want to give me some feedback or make a suggestion, create an [issue on GitHub](https://github.com/filp/whoops/issues/new). If you want to get your hands dirty, great! Here's a couple of steps/guidelines: - See [a list of possible features to add](https://github.com/filp/whoops/wiki/Possible-features-to-add) for ideas on what can be improved. - Add tests for your changes (in `tests/`). - Remember to stick to the existing code style as best as possible. When in doubt, follow `PSR-2`. - Before investing a lot of time coding, create an issue to get our opinion on your big changes. - Update the documentation, if applicable. - If you want to add an integration to a web framework, please [review our guidelines for that](docs/Framework%20Integration.md#contributing-an-integration-with-a-framework). In `PrettyPageHandler` we are using a Zepto library, but if you are only familiar with jQuery, note that it is pretty much identical. ================================================ FILE: LICENSE.md ================================================ # The MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # whoops PHP errors for cool kids [![Total Downloads](https://img.shields.io/packagist/dm/filp/whoops.svg)](https://packagist.org/packages/filp/whoops) [![Latest Version](http://img.shields.io/packagist/v/filp/whoops.svg)](https://packagist.org/packages/filp/whoops) [![Build Status on newer versions](https://github.com/filp/whoops/workflows/Tests/badge.svg)](https://github.com/filp/whoops/actions?query=workflow%3ATests) [![Scrutinizer Quality Score](https://scrutinizer-ci.com/g/filp/whoops/badges/quality-score.png?s=6225c36f2a2dd1fdca11ecc7b10b29105c8c62bd)](https://scrutinizer-ci.com/g/filp/whoops) [![Code Coverage](https://scrutinizer-ci.com/g/filp/whoops/badges/coverage.png?s=711feb2069144d252d111b211965ffb19a7d09a8)](https://scrutinizer-ci.com/g/filp/whoops) ----- ![Whoops!](http://i.imgur.com/0VQpe96.png) **whoops** is an error handler framework for PHP. Out-of-the-box, it provides a pretty error interface that helps you debug your web projects, but at heart it's a simple yet powerful stacked error handling system. ## Features - Flexible, stack-based error handling - Stand-alone library with (currently) no required dependencies - Simple API for dealing with exceptions, trace frames & their data - Includes a pretty rad error page for your webapp projects - Includes the ability to [open referenced files directly in your editor and IDE](docs/Open%20Files%20In%20An%20Editor.md) - Includes handlers for different response formats (JSON, XML, SOAP) - Easy to extend and integrate with existing libraries - Clean, well-structured & tested code-base ## Sponsors Blackfire.io ## Installing If you use Laravel 4, Laravel 5.5+ or [Mezzio](https://docs.mezzio.dev/mezzio/), you already have Whoops. There are also community-provided instructions on how to integrate Whoops into [Silex 1](https://github.com/whoops-php/silex-1), [Silex 2](https://github.com/texthtml/whoops-silex), [Phalcon](https://github.com/whoops-php/phalcon), [Laravel 3](https://gist.github.com/hugomrdias/5169713#file-start-php), [Laravel 5](https://github.com/GrahamCampbell/Laravel-Exceptions), [CakePHP 3](https://github.com/dereuromark/cakephp-whoops/tree/cake3), [CakePHP 4](https://github.com/dereuromark/cakephp-whoops), [Zend 2](https://github.com/ghislainf/zf2-whoops), [Zend 3](https://github.com/Ppito/zf3-whoops), [Yii 1](https://github.com/igorsantos07/yii-whoops), [FuelPHP](https://github.com/indigophp/fuel-whoops), [Slim](https://github.com/zeuxisoo/php-slim-whoops/), [Pimple](https://github.com/texthtml/whoops-pimple), [Laminas](https://github.com/Ppito/laminas-whoops), or any framework consuming [StackPHP middlewares](https://github.com/thecodingmachine/whoops-stackphp) or [PSR-7 middlewares](https://github.com/franzliedke/whoops-middleware). If you are not using any of these frameworks, here's a very simple way to install: 1. Use [Composer](http://getcomposer.org) to install Whoops into your project: ```bash composer require filp/whoops ``` 1. Register the pretty handler in your code: ```php $whoops = new \Whoops\Run; $whoops->pushHandler(new \Whoops\Handler\PrettyPageHandler); $whoops->register(); ``` For more options, have a look at the **example files** in [`examples/`](./examples) to get a feel for how things work. Also take a look at the [API Documentation](docs/API%20Documentation.md) and the list of available handlers below. You may also want to override some system calls Whoops does. To do that, extend `Whoops\Util\SystemFacade`, override functions that you want and pass it as the argument to the `Run` constructor. You may also collect the HTML generated to process it yourself: ```php $whoops = new \Whoops\Run; $whoops->allowQuit(false); $whoops->writeToOutput(false); $whoops->pushHandler(new \Whoops\Handler\PrettyPageHandler); $html = $whoops->handleException($e); ``` ### Available Handlers **whoops** currently ships with the following built-in handlers, available in the `Whoops\Handler` namespace: - [`PrettyPageHandler`](https://github.com/filp/whoops/blob/master/src/Whoops/Handler/PrettyPageHandler.php) - Shows a pretty error page when something goes pants-up - [`PlainTextHandler`](https://github.com/filp/whoops/blob/master/src/Whoops/Handler/PlainTextHandler.php) - Outputs plain text message for use in CLI applications - [`CallbackHandler`](https://github.com/filp/whoops/blob/master/src/Whoops/Handler/CallbackHandler.php) - Wraps a closure or other callable as a handler. You do not need to use this handler explicitly, **whoops** will automatically wrap any closure or callable you pass to `Whoops\Run::pushHandler` - [`JsonResponseHandler`](https://github.com/filp/whoops/blob/master/src/Whoops/Handler/JsonResponseHandler.php) - Captures exceptions and returns information on them as a JSON string. Can be used to, for example, play nice with AJAX requests. - [`XmlResponseHandler`](https://github.com/filp/whoops/blob/master/src/Whoops/Handler/XmlResponseHandler.php) - Captures exceptions and returns information on them as a XML string. Can be used to, for example, play nice with AJAX requests. You can also use pluggable handlers, such as [SOAP handler](https://github.com/whoops-php/soap). ## Authors This library was primarily developed by [Filipe Dobreira](https://github.com/filp), and is currently maintained by [Denis Sokolov](https://github.com/denis-sokolov). A lot of awesome fixes and enhancements were also sent in by [various contributors](https://github.com/filp/whoops/contributors). Special thanks to [Graham Campbell](https://github.com/GrahamCampbell) and [Markus Staab](https://github.com/staabm) for continuous participation. ================================================ FILE: SECURITY.md ================================================ # Security Policy ## Supported Versions Only the latest released version of Whoops is supported. To facilitate upgrades we almost never make backwards-incompatible changes. ## Reporting a Vulnerability Please report vulnerabilities over email, by sending an email to `denis` at `sokolov` dot `cc`. ================================================ FILE: composer.json ================================================ { "name": "filp/whoops", "license": "MIT", "description": "php error handling for cool kids", "keywords": ["library", "error", "handling", "exception", "whoops", "throwable"], "homepage": "https://filp.github.io/whoops/", "authors": [ { "name": "Filipe Dobreira", "homepage": "https://github.com/filp", "role": "Developer" } ], "scripts": { "demo": "php -S localhost:8000 ./examples/example.php", "test": "phpunit --testdox tests" }, "require": { "php": "^7.1 || ^8.0", "psr/log": "^1.0.1 || ^2.0 || ^3.0" }, "require-dev": { "phpunit/phpunit": "^7.5.20 || ^8.5.8 || ^9.3.3 || ^10.5.58", "mockery/mockery": "^1.0", "symfony/var-dumper": "^4.0 || ^5.0 || ^6.0 || ^7.0 || ^8.0" }, "suggest": { "symfony/var-dumper": "Pretty print complex values better with var-dumper available", "whoops/soap": "Formats errors as SOAP responses" }, "autoload": { "psr-4": { "Whoops\\": "src/Whoops/" } }, "autoload-dev": { "psr-4": { "Whoops\\": "tests/Whoops/" } }, "extra": { "branch-alias": { "dev-master": "2.7-dev" } } } ================================================ FILE: docs/API Documentation.md ================================================ # API Documentation ### Core Classes: - [`Whoops\Run`](#whoops-run) - The main `Whoops` class - represents the stack and current execution - [`Whoops\Handler\Handler` and `Whoops\Handler\HandlerInterface`](#handler-abstract) - Abstract representation of a Handler, and utility methods - [`Whoops\Exception\Inspector`](#inspector) - Exposes methods to inspect an exception - [`Whoops\Exception\FrameCollection`](#frame-collection) - Exposes methods to work with a list of frames - [`Whoops\Exception\Frame`](#frame) - Exposes methods to inspect a single stack trace frame from an exception ### Core Handlers: - [`Whoops\Handler\CallbackHandler`](#handler-callback) - Wraps regular closures as handlers - [`Whoops\Handler\JsonResponseHandler`](#handler-json) - Formats errors and exceptions as a JSON payload - [`Whoops\Handler\PrettyPageHandler`](#handler-pretty) - Outputs a detailed, fancy error page ### Core Functions: - [`Whoops\Util\Misc::isAjaxRequest()`](#fn-ajax) - Determines whether the current request was triggered by XMLHttpRequest - [`Whoops\Util\Misc::isCommandLine()`](#fn-cli) - Determines whether the current request was triggered via php commandline interface (CLI) # Core Classes: ## `Whoops\Run` The `Run` class models an instance of an execution, and integrates the methods to control whoops' execution in that context, and control the handlers stack. ### Constants ```php string Run::EXCEPTION_HANDLER // (name for exception handler method) string Run::ERROR_HANDLER // (name for error handler method) string Run::SHUTDOWN_HANDLER // (name for shutdown handler method) ``` ### Methods ```php Run::prependHandler(Whoops\HandlerInterface $handler) #=> Whoops\Run Run::appendHandler(Whoops\HandlerInterface $handler) #=> Whoops\Run Run::removeFirstHandler() #=> null Run::removeLastHandler() #=> null // Returns all handlers in the stack Run::getHandlers() #=> Whoops\HandlerInterface[] // Returns a Whoops\Inspector instance for a given Exception Run::getInspector(Exception $exception) #=> Whoops\Exception\Inspector // Registers this Whoops\Run instance as an error/exception/shutdown // handler with PHP Run::register() #=> Whoops\Run // I'll let you guess this one Run::unregister() #=> Whoops\Run // Send a custom exit code in CLI context (default: 1) Run::sendExitCode($code = null) #=> int // If true, allows Whoops to terminate script execution (default: true) Run::allowQuit($allowQuit = null) #=> bool // Silence errors for paths matching regular expressions and PHP error constants. // Can be called multiple times. Run::silenceErrorsInPaths($patterns, $levels = E_STRICT | E_DEPRECATED) #=> Whoops\Run // If true, allows Whoops to send output produced by handlers directly // to the client. You'll want to set this to false if you want to // package the handlers' response into your HTTP response abstraction // or something (default: true) Run::writeToOutput($send = null) #=> bool // ** HANDLERS ** // These are semi-internal methods that receive input from // PHP directly. If you know what you're doing, you can // also call them directly // Handles an exception with the current stack. Returns the // output produced by handlers. Run::handleException(Exception $exception) #=> string // Handles an error with the current stack. Errors are // converted into SPL ErrorException instances Run::handleError(int $level, string $message, string $file = null, int $line = null) #=> null // Hooked as a shutdown handler, captures fatal errors and handles them // through the current stack: Run::handleShutdown() #=> null // adds a new frame filter callback to the frame filters stack Run::addFrameFilter() #=> Whoops\Run ``` ## `Whoops\Handler\Handler` & `Whoops\Handler\HandlerInterface` This abstract class contains the base methods for concrete handler implementations. Custom handlers can extend it, or implement the `Whoops\Handler\HandlerInterface` interface. ### Constants ```php int Handler::DONE // If returned from HandlerInterface::handle, does absolutely nothing. int Handler::LAST_HANDLER // ...tells whoops to not execute any more handlers after this one. int Handler::QUIT // ...tells whoops to quit script execution immediately. ``` ### Methods ```php // Custom handlers should expose this method, which will be called once an // exception needs to be handled. The Handler::* constants can be used to // signal the underlying logic as to what to do next. HandlerInterface::handle() #=> null | int // Sets the Run instance for this handler HandlerInterface::setRun(Whoops\Run $run) #=> null // Sets the Inspector instance for this handler HandlerInterface::setInspector(Whoops\Exception\Inspector $inspector) #=> null // Sets the Exception for this handler to handle HandlerInterface::setException(Exception $exception) #=> null ``` ## `Whoops\Exception\Inspector` The `Inspector` class provides methods to inspect an exception instance, with particular focus on its frames/stack-trace. ### Methods ```php Inspector::__construct(Exception $exception) #=> null // Returns the Exception instance being inspected Inspector::getException() #=> Exception // Returns the string name of the Exception being inspected // A faster way of doing get_class($inspector->getException()) Inspector::getExceptionName() #=> string // Returns the string message for the Exception being inspected // A faster way of doing $inspector->getException()->getMessage() Inspector::getExceptionMessage() #=> string // Returns an iterator instance for all the frames in the stack // trace for the Exception being inspected. Inspector::getFrames() #=> Whoops\Exception\FrameIterator ``` ## `Whoops\Exception\FrameCollection` The `FrameCollection` class exposes a fluent interface to manipulate and examine a collection of `Frame` instances. `FrameCollection` objects are **serializable**. ### Methods ```php // Returns the number of frames in the collection // May also be called as count($frameCollection) FrameCollection::count() #=> int // Filter the Frames in the collection with a callable. // The callable must accept a Frame object, and return // true to keep it in the collection, or false not to. FrameCollection::filter(callable $callable) #=> FrameCollection // See: array_map // The callable must accept a Frame object, and return // a Frame object, doesn't matter if it's the same or not // - will throw an UnexpectedValueException if something // else is returned. FrameCollection::map(callable $callable) #=> FrameCollection ``` ## `Whoops\Exception\Frame` The `Frame` class models a single frame in an exception's stack trace. You can use it to retrieve info about things such as frame context, file, line number. Additionally, you have available functionality to add comments to a frame, which is made available to other handlers. `Frame` objects are **serializable**. ### Methods ```php // Returns the file path for the file where this frame occurred. // The optional $shortened argument allows you to retrieve a // shorter, human-readable file path for display. Frame::getFile(bool $shortened = false) #=> string | null (Some frames do not have a file path) // Returns the line number for this frame Frame::getLine() #=> int | null // Returns the class name for this frame, if it occurred // within a class/instance. Frame::getClass() #=> string | null // Returns the function name for this frame, if it occurred // within a function/method Frame::getFunction() #=> string | null // Returns an array of arguments for this frame. Empty if no // arguments were provided. Frame::getArgs() #=> array // Returns the full file contents for the file where this frame // occurred. Frame::getFileContents() #=> string | null // Returns an array of lines for a file, optionally scoped to a // given range of line numbers. i.e: Frame::getFileLines(0, 3) // returns the first 3 lines after line 0 (1) Frame::getFileLines(int $start = 0, int $length = null) #=> array | null // Adds a comment to this Frame instance. Comments are shared // with everything that can access the frame instance, obviously, // so they can be used for a variety of inter-operability purposes. // The context option can be used to improve comment filtering. // Additionally, if frames contain URIs, the PrettyPageHandler // will automagically convert them to clickable anchor elements. Frame::addComment(string $comment, string $context = 'global') #=> null // Returns all comments for this instance optionally filtered by // a string context identifier. Frame::getComments(string $filter = null) #=> array ``` # Core Handlers ## `Whoops\Handler\CallbackHandler` The `CallbackHandler` handler wraps regular PHP closures as valid handlers. Useful for quick prototypes or simple handlers. When you pass a closure to `Run::pushHandler`, it's automatically converted to a `CallbackHandler` instance. ```php pushHandler(function($exception, $inspector, $run) { var_dump($exception->getMessage()); return Handler::DONE; }); $run->popHandler() // #=> Whoops\Handler\CallbackHandler ``` ### Methods ```php // Accepts any valid callable // For example, a closure, a string function name, an array // in the format array($class, $method) CallbackHandler::__construct($callable) #=> null CallbackHandler::handle() #=> int | null ``` ## `Whoops\Handler\JsonResponseHandler` The `JsonResponseHandler`, upon receiving an exception to handle, simply constructs a `JSON` payload, and outputs it. Methods are available to control the detail of the output, and if it should only execute for AJAX requests - paired with another handler under it, such as the `PrettyPageHandler`, it allows you to have meaningful output for both regular and AJAX requests. Neat! The `JSON` body has the following format: ```json { "error": { "type": "RuntimeException", "message": "Something broke!", "file": "/var/project/foo/bar.php", "line": 22, # if JsonResponseHandler::addTraceToOutput(true): "trace": [ { "file": "/var/project/foo/index.php", "line": 157, "function": "handleStuffs", "class": "MyApplication\DoerOfThings", "args": [ true, 10, "yay method arguments" ] }, # ... more frames here ... ] } } ``` ### Methods ```php // Should detailed stack trace output also be added to the // JSON payload body? JsonResponseHandler::addTraceToOutput(bool $yes = null) #=> bool JsonResponseHandler::handle() #=> int | null ``` ## `Whoops\Handler\PrettyPageHandler` The `PrettyPageHandler` generates a fancy, detailed error page which includes code views for all frames in the stack trace, environment details, etc. Super neat. It produces a bundled response string that does not require any further HTTP requests, so it's fit to work on pretty much any environment and framework that speaks back to a browser, without you having to explicitly hook it up to your framework/project's routing mechanisms. ### Methods ```php // Adds a key=>value table of arbitrary data, labeled by $label, to // the output. Useful where you want to display contextual data along // with the error, about your application or project. PrettyPageHandler::addDataTable(string $label, array $data) #=> null // Similar to PrettyPageHandler::addDataTable, but accepts a callable // that will be called only when rendering an exception. This allows // you to gather additional data that may not be available very early // in the process. PrettyPageHandler::addDataTableCallback(string $label, callable $callback) #=> null // Returns all data tables registered with this handler. Optionally // accepts a string label, and will only return the data under that // label. PrettyPageHandler::getDataTables(string $label = null) #=> array | array[] // Sets the title for the error page PrettyPageHandler::setPageTitle(string $title) #=> null // Returns the title for the error page PrettyPageHandler::getPageTitle() #=> string // Returns a list of string paths where resources // used by this handler are searched for - the template and CSS // files. PrettyPageHandler::getResourcesPaths() #=> array // Adds a string path to the location of resources for the // handler. Useful if you want to roll your own template // file (pretty-template.php and pretty-page.css) while // still using the logic this handler provides PrettyPageHandler::addResourcePath(string $resourcesPath) #=> null // Sets an editor to use to open referenced files, either by // a string identifier, or as an arbitrary callable that returns // a string or an array that can be used as an href attribute. // Available built-in editors can be found here: https://github.com/filp/whoops/blob/master/docs/Open Files In An Editor.md PrettyPageHandler::setEditor(string $editor) PrettyPageHandler::setEditor(function ($file, $line) { return string }) // Additionally you may want that the link acts as an ajax request (e.g. Intellij platform) PrettyPageHandler::setEditor(function ($file, $line) { return array( 'url' => "http://localhost:63342/api/file/?file=$file&line=$line", 'ajax' => true ); } ) #=> null // Similar to PrettyPageHandler::setEditor, but allows you // to name your custom editor, thus sharing it with the // rest of the application. Useful if, for example, you integrate // Whoops into your framework or library, and want to share // support for extra editors with the end-user. // // $resolver may be a callable, like with ::setEditor, or a string // with placeholders %file and %line. // For example: // $handler->addEditor('whatevs', 'whatevs://open?file=file://%file&line=%line') PrettyPageHandler::addEditor(string $editor, $resolver) #=> null PrettyPageHandler::handle() #=> int | null ``` # Core Functions: ## `Whoops\Util\Misc::isAjaxRequest()` #=> boolean ```php // Use a certain handler only in AJAX triggered requests if (Whoops\Util\Misc::isAjaxRequest()){ $run->addHandler($myHandler); } ``` ## `Whoops\Util\Misc::isCommandLine()` #=> boolean ```php // Use a certain handler only in php cli if (Whoops\Util\Misc::isCommandLine()){ $run->addHandler($myHandler); } ``` ```php /* Output the error message only if using command line. else, output to logger if available. Allow to safely add this handler to web pages. */ $plainTextHandler = new PlainTextHandler(); if (!Whoops\isCommandLine()){ $plainTextHandler->loggerOnly(true); } $run->addHandler($myHandler); ``` ================================================ FILE: docs/Framework Integration.md ================================================ # Contributing an integration with a framework Lately we're preferring to keep integration libraries out of the Whoops core. If possible, consider managing an official Whoops-SomeFramework integration. The procedure is not hard at all. 1. Keep your integration classes and instructions in a repository of your own; 2. Create a `composer.json` file in your repository with contents similar to the following: ``` { "name": "username/whoops-someframework", "description": "Integrates the Whoops library into SomeFramework", "require": { "filp/whoops": "1.*" } } ``` 3. [Register it with Packagist](https://packagist.org/packages/submit). Once that is done, please create an issue and we will add a link to it in our README. SomeFramework users then would write this in their `composer.json`: ``` "require": { "username/whoops-someframework": "*" } ``` This would also install Whoops and you'd be able to release updates to your package as quickly as you wish them to. ================================================ FILE: docs/Open Files In An Editor.md ================================================ # Open Files In An Editor When using the pretty error page feature, whoops comes with the ability to open referenced files directly in your IDE or editor. This feature only works in case your php-source files are locally accessible to the machine on which the editor is installed. ```php setEditor('sublime'); ``` The following editors are currently supported by default. - `emacs` - Emacs - `idea` - IDEA - `macvim` - MacVim - `phpstorm` - PhpStorm (on Linux you might need to manually install a [handler](https://github.com/sanduhrs/phpstorm-url-handler)) - `sublime` - Sublime Text 2 and possibly 3 (on OS X you might need [a special handler](https://github.com/inopinatus/sublime_url)) - `textmate` - Textmate - `xdebug` - xdebug (uses [xdebug.file_link_format](http://xdebug.org/docs/all_settings#file_link_format)) - `vscode` - VSCode (ref [Opening VS Code with URLs](https://code.visualstudio.com/docs/editor/command-line#_opening-vs-code-with-urls)) - `atom` - Atom (ref [Add core URI handlers](https://github.com/atom/atom/pull/15935)) - `espresso` - Espresso - `netbeans` - Netbeans (ref [xdebug.file_link_format](http://xdebug.org/docs/all_settings#file_link_format)) Adding your own editor is simple: ```php $handler->setEditor(function($file, $line) { return "whatever://open?file=$file&line=$line"; }); ``` You can add [IntelliJ Platform](https://github.com/pinepain/PhpStormOpener#phpstormopener) support like this: ```php $handler->setEditor( function ($file, $line) { // if your development server is not local it's good to map remote files to local $translations = array('^' . __DIR__ => '~/Development/PhpStormOpener'); // change to your path foreach ($translations as $from => $to) { $file = preg_replace('#' . $from . '#', $to, $file, 1); } // IntelliJ platform requires that you send an Ajax request, else the browser will quit the page return array( 'url' => "http://localhost:63342/api/file/?file=$file&line=$line", 'ajax' => true ); } ); ``` ================================================ FILE: docs/Replay Errors.md ================================================ # Replay Errors You can replay Errors that happened in production if you serialize them and store them to later replay in a development Whoops: ```php $serialized_exception = serialize(new Exception('Something has happened!')); $whoops = new \Whoops\Run; $whoops->pushHandler(new \Whoops\Handler\PrettyPageHandler); $whoops->register(); $whoops->handleException(unserialize($serialized_exception)); ``` https://github.com/filp/whoops/issues/623 ================================================ FILE: examples/example-ajax-only.php ================================================ * * Run this example file with the PHP 5.4 web server with: * * $ cd project_dir * $ php -S localhost:8080 * * and access localhost:8080/examples/example-ajax-only.php through your browser * * Or just run it through apache/nginx/what-have-yous as usual. */ namespace Whoops\Example; use RuntimeException; use Whoops\Handler\JsonResponseHandler; use Whoops\Handler\PrettyPageHandler; use Whoops\Run; require __DIR__ . '/../vendor/autoload.php'; $run = new Run(); // We want the error page to be shown by default, if this is a // regular request, so that's the first thing to go into the stack: $run->pushHandler(new PrettyPageHandler()); // Now, we want a second handler that will run before the error page, // and immediately return an error message in JSON format, if something // goes awry. if (\Whoops\Util\Misc::isAjaxRequest()) { $jsonHandler = new JsonResponseHandler(); // You can also tell JsonResponseHandler to give you a full stack trace: // $jsonHandler->addTraceToOutput(true); // You can also return a result compliant to the json:api spec // re: http://jsonapi.org/examples/#error-objects // tl;dr: error[] becomes errors[[]] $jsonHandler->setJsonApi(true); // And push it into the stack: $run->pushHandler($jsonHandler); } // That's it! Register Whoops and throw a dummy exception: $run->register(); throw new RuntimeException("Oh fudge napkins!"); ================================================ FILE: examples/example.php ================================================ * * Run this example file with the PHP 5.4 web server with: * * $ cd project_dir * $ php -S localhost:8080 * * and access localhost:8080/examples/example.php through your browser * * Or just run it through apache/nginx/what-have-yous as usual. */ namespace Whoops\Example; use Exception as BaseException; use Whoops\Handler\PrettyPageHandler; use Whoops\Run; require __DIR__ . '/../vendor/autoload.php'; require __DIR__ . '/lib.php'; class Exception extends BaseException { } $run = new Run(); $handler = new PrettyPageHandler(); // Add a custom table to the layout: $handler->addDataTable('Ice-cream I like', [ 'Chocolate' => 'yes', 'Coffee & chocolate' => 'a lot', 'Strawberry & chocolate' => 'it\'s alright', 'Vanilla' => 'ew', ]); $handler->setApplicationPaths([__FILE__]); $handler->addDataTableCallback('Details', function(\Whoops\Exception\Inspector $inspector) { $data = array(); $exception = $inspector->getException(); if ($exception instanceof SomeSpecificException) { $data['Important exception data'] = $exception->getSomeSpecificData(); } $data['Exception class'] = get_class($exception); $data['Exception code'] = $exception->getCode(); return $data; }); $run->pushHandler($handler); // Example: tag all frames inside a function with their function name $run->pushHandler(function ($exception, $inspector, $run) { $inspector->getFrames()->map(function ($frame) { if ($function = $frame->getFunction()) { $frame->addComment("This frame is within function '$function'", 'cpt-obvious'); } return $frame; }); }); $run->register(); function fooBar() { throw new Exception("Something broke!"); } function bar() { whoops_add_stack_frame(function(){ fooBar(); }); } bar(); ================================================ FILE: examples/lib.php ================================================ tests/Whoops/ src/Whoops/ ./docs ./examples ./tests ./vendor ================================================ FILE: src/Whoops/Exception/ErrorException.php ================================================ */ namespace Whoops\Exception; use ErrorException as BaseErrorException; /** * Wraps ErrorException; mostly used for typing (at least now) * to easily cleanup the stack trace of redundant info. */ class ErrorException extends BaseErrorException { } ================================================ FILE: src/Whoops/Exception/Formatter.php ================================================ */ namespace Whoops\Exception; use Whoops\Inspector\InspectorInterface; class Formatter { /** * Returns all basic information about the exception in a simple array * for further convertion to other languages * @param InspectorInterface $inspector * @param bool $shouldAddTrace * @param array $frameFilters * @return array */ public static function formatExceptionAsDataArray(InspectorInterface $inspector, $shouldAddTrace, array $frameFilters = []) { $exception = $inspector->getException(); $response = [ 'type' => get_class($exception), 'message' => $exception->getMessage(), 'code' => $exception->getCode(), 'file' => $exception->getFile(), 'line' => $exception->getLine(), ]; if ($shouldAddTrace) { $frames = $inspector->getFrames($frameFilters); $frameData = []; foreach ($frames as $frame) { /** @var Frame $frame */ $frameData[] = [ 'file' => $frame->getFile(), 'line' => $frame->getLine(), 'function' => $frame->getFunction(), 'class' => $frame->getClass(), 'args' => $frame->getArgs(), ]; } $response['trace'] = $frameData; } return $response; } public static function formatExceptionPlain(InspectorInterface $inspector) { $message = $inspector->getException()->getMessage(); $frames = $inspector->getFrames(); $plain = $inspector->getExceptionName(); $plain .= ' thrown with message "'; $plain .= $message; $plain .= '"'."\n\n"; $plain .= "Stacktrace:\n"; foreach ($frames as $i => $frame) { $plain .= "#". (count($frames) - $i - 1). " "; $plain .= $frame->getClass() ?: ''; $plain .= $frame->getClass() && $frame->getFunction() ? ":" : ""; $plain .= $frame->getFunction() ?: ''; $plain .= ' in '; $plain .= ($frame->getFile() ?: '<#unknown>'); $plain .= ':'; $plain .= (int) $frame->getLine(). "\n"; } return $plain; } } ================================================ FILE: src/Whoops/Exception/Frame.php ================================================ */ namespace Whoops\Exception; use InvalidArgumentException; use Serializable; class Frame implements Serializable { /** * @var array */ protected $frame; /** * @var string */ protected $fileContentsCache; /** * @var array[] */ protected $comments = []; /** * @var bool */ protected $application; public function __construct(array $frame) { $this->frame = $frame; } /** * @param bool $shortened * @return string|null */ public function getFile($shortened = false) { if (empty($this->frame['file'])) { return null; } $file = $this->frame['file']; // Check if this frame occurred within an eval(). // @todo: This can be made more reliable by checking if we've entered // eval() in a previous trace, but will need some more work on the upper // trace collector(s). if (preg_match('/^(.*)\((\d+)\) : (?:eval\(\)\'d|assert) code$/', $file, $matches)) { $file = $this->frame['file'] = $matches[1]; $this->frame['line'] = (int) $matches[2]; } if ($shortened && is_string($file)) { // Replace the part of the path that all frames have in common, and add 'soft hyphens' for smoother line-breaks. $dirname = dirname(dirname(dirname(dirname(dirname(dirname(__DIR__)))))); if ($dirname !== '/') { $file = str_replace($dirname, "…", $file); } $file = str_replace("/", "/­", $file); } return $file; } /** * @return int|null */ public function getLine() { return isset($this->frame['line']) ? $this->frame['line'] : null; } /** * @return string|null */ public function getClass() { return isset($this->frame['class']) ? $this->frame['class'] : null; } /** * @return string|null */ public function getFunction() { return isset($this->frame['function']) ? $this->frame['function'] : null; } /** * @return array */ public function getArgs() { return isset($this->frame['args']) ? (array) $this->frame['args'] : []; } /** * Returns the full contents of the file for this frame, * if it's known. * @return string|null */ public function getFileContents() { if ($this->fileContentsCache === null && $filePath = $this->getFile()) { // Leave the stage early when 'Unknown' or '[internal]' is passed // this would otherwise raise an exception when // open_basedir is enabled. if ($filePath === "Unknown" || $filePath === '[internal]') { return null; } try { $this->fileContentsCache = file_get_contents($filePath); } catch (ErrorException $exception) { // Internal file paths of PHP extensions cannot be opened } } return $this->fileContentsCache; } /** * Adds a comment to this frame, that can be received and * used by other handlers. For example, the PrettyPage handler * can attach these comments under the code for each frame. * * An interesting use for this would be, for example, code analysis * & annotations. * * @param string $comment * @param string $context Optional string identifying the origin of the comment */ public function addComment($comment, $context = 'global') { $this->comments[] = [ 'comment' => $comment, 'context' => $context, ]; } /** * Returns all comments for this frame. Optionally allows * a filter to only retrieve comments from a specific * context. * * @param string $filter * @return array[] */ public function getComments($filter = null) { $comments = $this->comments; if ($filter !== null) { $comments = array_filter($comments, function ($c) use ($filter) { return $c['context'] == $filter; }); } return $comments; } /** * Returns the array containing the raw frame data from which * this Frame object was built * * @return array */ public function getRawFrame() { return $this->frame; } /** * Returns the contents of the file for this frame as an * array of lines, and optionally as a clamped range of lines. * * NOTE: lines are 0-indexed * * @example * Get all lines for this file * $frame->getFileLines(); // => array( 0 => ' '...', ...) * @example * Get one line for this file, starting at line 10 (zero-indexed, remember!) * $frame->getFileLines(9, 1); // array( 9 => '...' ) * * @throws InvalidArgumentException if $length is less than or equal to 0 * @param int $start * @param int $length * @return string[]|null */ public function getFileLines($start = 0, $length = null) { if (null !== ($contents = $this->getFileContents())) { $lines = explode("\n", $contents); // Get a subset of lines from $start to $end if ($length !== null) { $start = (int) $start; $length = (int) $length; if ($start < 0) { $start = 0; } if ($length <= 0) { throw new InvalidArgumentException( "\$length($length) cannot be lower or equal to 0" ); } $lines = array_slice($lines, $start, $length, true); } return $lines; } } /** * Implements the Serializable interface, with special * steps to also save the existing comments. * * @see Serializable::serialize * @return string */ public function serialize() { $frame = $this->frame; if (!empty($this->comments)) { $frame['_comments'] = $this->comments; } return serialize($frame); } public function __serialize() { $frame = $this->frame; if (!empty($this->comments)) { $frame['_comments'] = $this->comments; } return $frame; } /** * Unserializes the frame data, while also preserving * any existing comment data. * * @see Serializable::unserialize * @param string $serializedFrame */ public function unserialize($serializedFrame) { $frame = unserialize($serializedFrame); if (!empty($frame['_comments'])) { $this->comments = $frame['_comments']; unset($frame['_comments']); } $this->frame = $frame; } public function __unserialize($frame) { if (!empty($frame['_comments'])) { $this->comments = $frame['_comments']; unset($frame['_comments']); } $this->frame = $frame; } /** * Compares Frame against one another * @param Frame $frame * @return bool */ public function equals(Frame $frame) { if (!$this->getFile() || $this->getFile() === 'Unknown' || !$this->getLine()) { return false; } return $frame->getFile() === $this->getFile() && $frame->getLine() === $this->getLine(); } /** * Returns whether this frame belongs to the application or not. * * @return boolean */ public function isApplication() { return $this->application; } /** * Mark as an frame belonging to the application. * * @param boolean $application */ public function setApplication($application) { $this->application = $application; } } ================================================ FILE: src/Whoops/Exception/FrameCollection.php ================================================ */ namespace Whoops\Exception; use ArrayAccess; use ArrayIterator; use Countable; use IteratorAggregate; use ReturnTypeWillChange; use Serializable; use UnexpectedValueException; /** * Exposes a fluent interface for dealing with an ordered list * of stack-trace frames. */ class FrameCollection implements ArrayAccess, IteratorAggregate, Serializable, Countable { /** * @var array[] */ private $frames; public function __construct(array $frames) { $this->frames = array_map(function ($frame) { return new Frame($frame); }, $frames); } /** * Filters frames using a callable, returns the same FrameCollection * * @param callable $callable * @return FrameCollection */ public function filter($callable) { $this->frames = array_values(array_filter($this->frames, $callable)); return $this; } /** * Map the collection of frames * * @param callable $callable * @return FrameCollection */ public function map($callable) { // Contain the map within a higher-order callable // that enforces type-correctness for the $callable $this->frames = array_map(function ($frame) use ($callable) { $frame = call_user_func($callable, $frame); if (!$frame instanceof Frame) { throw new UnexpectedValueException( "Callable to " . __CLASS__ . "::map must return a Frame object" ); } return $frame; }, $this->frames); return $this; } /** * Returns an array with all frames, does not affect * the internal array. * * @todo If this gets any more complex than this, * have getIterator use this method. * @see FrameCollection::getIterator * @return array */ public function getArray() { return $this->frames; } /** * @see IteratorAggregate::getIterator * @return ArrayIterator */ #[ReturnTypeWillChange] public function getIterator() { return new ArrayIterator($this->frames); } /** * @see ArrayAccess::offsetExists * @param int $offset */ #[ReturnTypeWillChange] public function offsetExists($offset) { return isset($this->frames[$offset]); } /** * @see ArrayAccess::offsetGet * @param int $offset */ #[ReturnTypeWillChange] public function offsetGet($offset) { return $this->frames[$offset]; } /** * @see ArrayAccess::offsetSet * @param int $offset */ #[ReturnTypeWillChange] public function offsetSet($offset, $value) { throw new \Exception(__CLASS__ . ' is read only'); } /** * @see ArrayAccess::offsetUnset * @param int $offset */ #[ReturnTypeWillChange] public function offsetUnset($offset) { throw new \Exception(__CLASS__ . ' is read only'); } /** * @see Countable::count * @return int */ #[ReturnTypeWillChange] public function count() { return count($this->frames); } /** * Count the frames that belongs to the application. * * @return int */ public function countIsApplication() { return count(array_filter($this->frames, function (Frame $f) { return $f->isApplication(); })); } /** * @see Serializable::serialize * @return string */ #[ReturnTypeWillChange] public function serialize() { return serialize($this->frames); } /** * @see Serializable::unserialize * @param string $serializedFrames */ #[ReturnTypeWillChange] public function unserialize($serializedFrames) { $this->frames = unserialize($serializedFrames); } public function __serialize() { return $this->frames; } public function __unserialize(array $serializedFrames) { $this->frames = $serializedFrames; } /** * @param Frame[] $frames Array of Frame instances, usually from $e->getPrevious() */ public function prependFrames(array $frames) { $this->frames = array_merge($frames, $this->frames); } /** * Gets the innermost part of stack trace that is not the same as that of outer exception * * @param FrameCollection $parentFrames Outer exception frames to compare tail against * @return Frame[] */ public function topDiff(FrameCollection $parentFrames) { $diff = $this->frames; $parentFrames = $parentFrames->getArray(); $p = count($parentFrames)-1; for ($i = count($diff)-1; $i >= 0 && $p >= 0; $i--) { /** @var Frame $tailFrame */ $tailFrame = $diff[$i]; if ($tailFrame->equals($parentFrames[$p])) { unset($diff[$i]); } $p--; } return $diff; } } ================================================ FILE: src/Whoops/Exception/Inspector.php ================================================ */ namespace Whoops\Exception; use Whoops\Inspector\InspectorFactory; use Whoops\Inspector\InspectorInterface; use Whoops\Util\Misc; class Inspector implements InspectorInterface { /** * @var \Throwable */ private $exception; /** * @var \Whoops\Exception\FrameCollection */ private $frames; /** * @var \Whoops\Exception\Inspector */ private $previousExceptionInspector; /** * @var \Throwable[] */ private $previousExceptions; /** * @var \Whoops\Inspector\InspectorFactoryInterface|null */ protected $inspectorFactory; /** * @param \Throwable $exception The exception to inspect * @param \Whoops\Inspector\InspectorFactoryInterface $factory */ public function __construct($exception, $factory = null) { $this->exception = $exception; $this->inspectorFactory = $factory ?: new InspectorFactory(); } /** * @return \Throwable */ public function getException() { return $this->exception; } /** * @return string */ public function getExceptionName() { return get_class($this->exception); } /** * @return string */ public function getExceptionMessage() { return $this->extractDocrefUrl($this->exception->getMessage())['message']; } /** * @return string[] */ public function getPreviousExceptionMessages() { return array_map(function ($prev) { /** @var \Throwable $prev */ return $this->extractDocrefUrl($prev->getMessage())['message']; }, $this->getPreviousExceptions()); } /** * @return int[] */ public function getPreviousExceptionCodes() { return array_map(function ($prev) { /** @var \Throwable $prev */ return $prev->getCode(); }, $this->getPreviousExceptions()); } /** * Returns a url to the php-manual related to the underlying error - when available. * * @return string|null */ public function getExceptionDocrefUrl() { return $this->extractDocrefUrl($this->exception->getMessage())['url']; } private function extractDocrefUrl($message) { $docref = [ 'message' => $message, 'url' => null, ]; // php embbeds urls to the manual into the Exception message with the following ini-settings defined // http://php.net/manual/en/errorfunc.configuration.php#ini.docref-root if (!ini_get('html_errors') || !ini_get('docref_root')) { return $docref; } $pattern = "/\[(?:[^<]+)<\/a>\]/"; if (preg_match($pattern, $message, $matches)) { // -> strip those automatically generated links from the exception message $docref['message'] = preg_replace($pattern, '', $message, 1); $docref['url'] = $matches[1]; } return $docref; } /** * Does the wrapped Exception has a previous Exception? * @return bool */ public function hasPreviousException() { return $this->previousExceptionInspector || $this->exception->getPrevious(); } /** * Returns an Inspector for a previous Exception, if any. * @todo Clean this up a bit, cache stuff a bit better. * @return Inspector */ public function getPreviousExceptionInspector() { if ($this->previousExceptionInspector === null) { $previousException = $this->exception->getPrevious(); if ($previousException) { $this->previousExceptionInspector = $this->inspectorFactory->create($previousException); } } return $this->previousExceptionInspector; } /** * Returns an array of all previous exceptions for this inspector's exception * @return \Throwable[] */ public function getPreviousExceptions() { if ($this->previousExceptions === null) { $this->previousExceptions = []; $prev = $this->exception->getPrevious(); while ($prev !== null) { $this->previousExceptions[] = $prev; $prev = $prev->getPrevious(); } } return $this->previousExceptions; } /** * Returns an iterator for the inspected exception's * frames. * * @param array $frameFilters * * @return \Whoops\Exception\FrameCollection */ public function getFrames(array $frameFilters = []) { if ($this->frames === null) { $frames = $this->getTrace($this->exception); // Fill empty line/file info for call_user_func_array usages (PHP Bug #44428) foreach ($frames as $k => $frame) { if (empty($frame['file'])) { // Default values when file and line are missing $file = '[internal]'; $line = 0; $next_frame = !empty($frames[$k + 1]) ? $frames[$k + 1] : []; if ($this->isValidNextFrame($next_frame)) { $file = $next_frame['file']; $line = $next_frame['line']; } $frames[$k]['file'] = $file; $frames[$k]['line'] = $line; } } // Find latest non-error handling frame index ($i) used to remove error handling frames $i = 0; foreach ($frames as $k => $frame) { if ($frame['file'] == $this->exception->getFile() && $frame['line'] == $this->exception->getLine()) { $i = $k; } } // Remove error handling frames if ($i > 0) { array_splice($frames, 0, $i); } $firstFrame = $this->getFrameFromException($this->exception); array_unshift($frames, $firstFrame); $this->frames = new FrameCollection($frames); if ($previousInspector = $this->getPreviousExceptionInspector()) { // Keep outer frame on top of the inner one $outerFrames = $this->frames; $newFrames = clone $previousInspector->getFrames(); // I assume it will always be set, but let's be safe if (isset($newFrames[0])) { $newFrames[0]->addComment( $previousInspector->getExceptionMessage(), 'Exception message:' ); } $newFrames->prependFrames($outerFrames->topDiff($newFrames)); $this->frames = $newFrames; } // Apply frame filters callbacks on the frames stack if (!empty($frameFilters)) { foreach ($frameFilters as $filterCallback) { $this->frames->filter($filterCallback); } } } return $this->frames; } /** * Gets the backtrace from an exception. * * If xdebug is installed * * @param \Throwable $e * @return array */ protected function getTrace($e) { $traces = $e->getTrace(); // Get trace from xdebug if enabled, failure exceptions only trace to the shutdown handler by default if (!$e instanceof \ErrorException) { return $traces; } if (!Misc::isLevelFatal($e->getSeverity())) { return $traces; } if (!extension_loaded('xdebug') || !function_exists('xdebug_is_enabled') || !xdebug_is_enabled()) { return $traces; } // Use xdebug to get the full stack trace and remove the shutdown handler stack trace $stack = array_reverse(xdebug_get_function_stack()); $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); $traces = array_diff_key($stack, $trace); return $traces; } /** * Given an exception, generates an array in the format * generated by Exception::getTrace() * @param \Throwable $exception * @return array */ protected function getFrameFromException($exception) { return [ 'file' => $exception->getFile(), 'line' => $exception->getLine(), 'class' => get_class($exception), 'args' => [ $exception->getMessage(), ], ]; } /** * Given an error, generates an array in the format * generated by ErrorException * @param ErrorException $exception * @return array */ protected function getFrameFromError(ErrorException $exception) { return [ 'file' => $exception->getFile(), 'line' => $exception->getLine(), 'class' => null, 'args' => [], ]; } /** * Determine if the frame can be used to fill in previous frame's missing info * happens for call_user_func and call_user_func_array usages (PHP Bug #44428) * * @return bool */ protected function isValidNextFrame(array $frame) { if (empty($frame['file'])) { return false; } if (empty($frame['line'])) { return false; } if (empty($frame['function']) || !stristr($frame['function'], 'call_user_func')) { return false; } return true; } } ================================================ FILE: src/Whoops/Handler/CallbackHandler.php ================================================ */ namespace Whoops\Handler; use InvalidArgumentException; /** * Wrapper for Closures passed as handlers. Can be used * directly, or will be instantiated automagically by Whoops\Run * if passed to Run::pushHandler */ class CallbackHandler extends Handler { /** * @var callable */ protected $callable; /** * @throws InvalidArgumentException If argument is not callable * @param callable $callable */ public function __construct($callable) { if (!is_callable($callable)) { throw new InvalidArgumentException( 'Argument to ' . __METHOD__ . ' must be valid callable' ); } $this->callable = $callable; } /** * @return int|null */ public function handle() { $exception = $this->getException(); $inspector = $this->getInspector(); $run = $this->getRun(); $callable = $this->callable; // invoke the callable directly, to get simpler stacktraces (in comparison to call_user_func). // this assumes that $callable is a properly typed php-callable, which we check in __construct(). return $callable($exception, $inspector, $run); } } ================================================ FILE: src/Whoops/Handler/Handler.php ================================================ */ namespace Whoops\Handler; use Whoops\Inspector\InspectorInterface; use Whoops\RunInterface; /** * Abstract implementation of a Handler. */ abstract class Handler implements HandlerInterface { /* Return constants that can be returned from Handler::handle to message the handler walker. */ const DONE = 0x10; // returning this is optional, only exists for // semantic purposes /** * The Handler has handled the Throwable in some way, and wishes to skip any other Handler. * Execution will continue. */ const LAST_HANDLER = 0x20; /** * The Handler has handled the Throwable in some way, and wishes to quit/stop execution */ const QUIT = 0x30; /** * @var RunInterface */ private $run; /** * @var InspectorInterface $inspector */ private $inspector; /** * @var \Throwable $exception */ private $exception; /** * @param RunInterface $run */ public function setRun(RunInterface $run) { $this->run = $run; } /** * @return RunInterface */ protected function getRun() { return $this->run; } /** * @param InspectorInterface $inspector */ public function setInspector(InspectorInterface $inspector) { $this->inspector = $inspector; } /** * @return InspectorInterface */ protected function getInspector() { return $this->inspector; } /** * @param \Throwable $exception */ public function setException($exception) { $this->exception = $exception; } /** * @return \Throwable */ protected function getException() { return $this->exception; } } ================================================ FILE: src/Whoops/Handler/HandlerInterface.php ================================================ */ namespace Whoops\Handler; use Whoops\Inspector\InspectorInterface; use Whoops\RunInterface; interface HandlerInterface { /** * @return int|null A handler may return nothing, or a Handler::HANDLE_* constant */ public function handle(); /** * @param RunInterface $run * @return void */ public function setRun(RunInterface $run); /** * @param \Throwable $exception * @return void */ public function setException($exception); /** * @param InspectorInterface $inspector * @return void */ public function setInspector(InspectorInterface $inspector); } ================================================ FILE: src/Whoops/Handler/JsonResponseHandler.php ================================================ */ namespace Whoops\Handler; use Whoops\Exception\Formatter; /** * Catches an exception and converts it to a JSON * response. Additionally can also return exception * frames for consumption by an API. */ class JsonResponseHandler extends Handler { /** * @var bool */ private $returnFrames = false; /** * @var bool */ private $jsonApi = false; /** * Returns errors[[]] instead of error[] to be in compliance with the json:api spec * @param bool $jsonApi Default is false * @return static */ public function setJsonApi($jsonApi = false) { $this->jsonApi = (bool) $jsonApi; return $this; } /** * @param bool|null $returnFrames * @return bool|static */ public function addTraceToOutput($returnFrames = null) { if (func_num_args() == 0) { return $this->returnFrames; } $this->returnFrames = (bool) $returnFrames; return $this; } /** * @return int */ public function handle() { if ($this->jsonApi === true) { $response = [ 'errors' => [ Formatter::formatExceptionAsDataArray( $this->getInspector(), $this->addTraceToOutput(), $this->getRun()->getFrameFilters() ), ] ]; } else { $response = [ 'error' => Formatter::formatExceptionAsDataArray( $this->getInspector(), $this->addTraceToOutput(), $this->getRun()->getFrameFilters() ), ]; } echo json_encode($response, defined('JSON_PARTIAL_OUTPUT_ON_ERROR') ? JSON_PARTIAL_OUTPUT_ON_ERROR : 0); return Handler::QUIT; } /** * @return string */ public function contentType() { return 'application/json'; } } ================================================ FILE: src/Whoops/Handler/PlainTextHandler.php ================================================ * Plaintext handler for command line and logs. * @author Pierre-Yves Landuré */ namespace Whoops\Handler; use InvalidArgumentException; use Psr\Log\LoggerInterface; use Whoops\Exception\Frame; /** * Handler outputing plaintext error messages. Can be used * directly, or will be instantiated automagically by Whoops\Run * if passed to Run::pushHandler */ class PlainTextHandler extends Handler { const VAR_DUMP_PREFIX = ' | '; /** * @var \Psr\Log\LoggerInterface */ protected $logger; /** * @var callable */ protected $dumper; /** * @var bool */ private $addTraceToOutput = true; /** * @var bool|integer */ private $addTraceFunctionArgsToOutput = false; /** * @var integer */ private $traceFunctionArgsOutputLimit = 1024; /** * @var bool */ private $addPreviousToOutput = true; /** * @var bool */ private $loggerOnly = false; /** * Constructor. * @throws InvalidArgumentException If argument is not null or a LoggerInterface * @param \Psr\Log\LoggerInterface|null $logger */ public function __construct($logger = null) { $this->setLogger($logger); } /** * Set the output logger interface. * @throws InvalidArgumentException If argument is not null or a LoggerInterface * @param \Psr\Log\LoggerInterface|null $logger */ public function setLogger($logger = null) { if (! (is_null($logger) || $logger instanceof LoggerInterface)) { throw new InvalidArgumentException( 'Argument to ' . __METHOD__ . " must be a valid Logger Interface (aka. Monolog), " . get_class($logger) . ' given.' ); } $this->logger = $logger; } /** * @return \Psr\Log\LoggerInterface|null */ public function getLogger() { return $this->logger; } /** * Set var dumper callback function. * * @param callable $dumper * @return static */ public function setDumper(callable $dumper) { $this->dumper = $dumper; return $this; } /** * Add error trace to output. * @param bool|null $addTraceToOutput * @return bool|static */ public function addTraceToOutput($addTraceToOutput = null) { if (func_num_args() == 0) { return $this->addTraceToOutput; } $this->addTraceToOutput = (bool) $addTraceToOutput; return $this; } /** * Add previous exceptions to output. * @param bool|null $addPreviousToOutput * @return bool|static */ public function addPreviousToOutput($addPreviousToOutput = null) { if (func_num_args() == 0) { return $this->addPreviousToOutput; } $this->addPreviousToOutput = (bool) $addPreviousToOutput; return $this; } /** * Add error trace function arguments to output. * Set to True for all frame args, or integer for the n first frame args. * @param bool|integer|null $addTraceFunctionArgsToOutput * @return static|bool|integer */ public function addTraceFunctionArgsToOutput($addTraceFunctionArgsToOutput = null) { if (func_num_args() == 0) { return $this->addTraceFunctionArgsToOutput; } if (! is_integer($addTraceFunctionArgsToOutput)) { $this->addTraceFunctionArgsToOutput = (bool) $addTraceFunctionArgsToOutput; } else { $this->addTraceFunctionArgsToOutput = $addTraceFunctionArgsToOutput; } return $this; } /** * Set the size limit in bytes of frame arguments var_dump output. * If the limit is reached, the var_dump output is discarded. * Prevent memory limit errors. * @param int $traceFunctionArgsOutputLimit * @return static */ public function setTraceFunctionArgsOutputLimit($traceFunctionArgsOutputLimit) { $this->traceFunctionArgsOutputLimit = (int) $traceFunctionArgsOutputLimit; return $this; } /** * Create plain text response and return it as a string * @return string */ public function generateResponse() { $exception = $this->getException(); $message = $this->getExceptionOutput($exception); if ($this->addPreviousToOutput) { $previous = $exception->getPrevious(); while ($previous) { $message .= "\n\nCaused by\n" . $this->getExceptionOutput($previous); $previous = $previous->getPrevious(); } } return $message . $this->getTraceOutput() . "\n"; } /** * Get the size limit in bytes of frame arguments var_dump output. * If the limit is reached, the var_dump output is discarded. * Prevent memory limit errors. * @return integer */ public function getTraceFunctionArgsOutputLimit() { return $this->traceFunctionArgsOutputLimit; } /** * Only output to logger. * @param bool|null $loggerOnly * @return static|bool */ public function loggerOnly($loggerOnly = null) { if (func_num_args() == 0) { return $this->loggerOnly; } $this->loggerOnly = (bool) $loggerOnly; return $this; } /** * Test if handler can output to stdout. * @return bool */ private function canOutput() { return !$this->loggerOnly(); } /** * Get the frame args var_dump. * @param \Whoops\Exception\Frame $frame [description] * @param integer $line [description] * @return string */ private function getFrameArgsOutput(Frame $frame, $line) { if ($this->addTraceFunctionArgsToOutput() === false || $this->addTraceFunctionArgsToOutput() < $line) { return ''; } // Dump the arguments: ob_start(); $this->dump($frame->getArgs()); if (ob_get_length() > $this->getTraceFunctionArgsOutputLimit()) { // The argument var_dump is to big. // Discarded to limit memory usage. ob_clean(); return sprintf( "\n%sArguments dump length greater than %d Bytes. Discarded.", self::VAR_DUMP_PREFIX, $this->getTraceFunctionArgsOutputLimit() ); } return sprintf( "\n%s", preg_replace('/^/m', self::VAR_DUMP_PREFIX, ob_get_clean()) ); } /** * Dump variable. * * @param mixed $var * @return void */ protected function dump($var) { if ($this->dumper) { call_user_func($this->dumper, $var); } else { var_dump($var); } } /** * Get the exception trace as plain text. * @return string */ private function getTraceOutput() { if (! $this->addTraceToOutput()) { return ''; } $inspector = $this->getInspector(); $frames = $inspector->getFrames($this->getRun()->getFrameFilters()); $response = "\nStack trace:"; $line = 1; foreach ($frames as $frame) { /** @var Frame $frame */ $class = $frame->getClass(); $template = "\n%3d. %s->%s() %s:%d%s"; if (! $class) { // Remove method arrow (->) from output. $template = "\n%3d. %s%s() %s:%d%s"; } $response .= sprintf( $template, $line, $class, $frame->getFunction(), $frame->getFile(), $frame->getLine(), $this->getFrameArgsOutput($frame, $line) ); $line++; } return $response; } /** * Get the exception as plain text. * @param \Throwable $exception * @return string */ private function getExceptionOutput($exception) { return sprintf( "%s: %s in file %s on line %d", get_class($exception), $exception->getMessage(), $exception->getFile(), $exception->getLine() ); } /** * @return int */ public function handle() { $response = $this->generateResponse(); if ($this->getLogger()) { $this->getLogger()->error($response); } if (! $this->canOutput()) { return Handler::DONE; } echo $response; return Handler::QUIT; } /** * @return string */ public function contentType() { return 'text/plain'; } } ================================================ FILE: src/Whoops/Handler/PrettyPageHandler.php ================================================ */ namespace Whoops\Handler; use InvalidArgumentException; use RuntimeException; use Symfony\Component\VarDumper\Cloner\AbstractCloner; use Symfony\Component\VarDumper\Cloner\VarCloner; use UnexpectedValueException; use Whoops\Exception\Formatter; use Whoops\Util\Misc; use Whoops\Util\TemplateHelper; class PrettyPageHandler extends Handler { const EDITOR_SUBLIME = "sublime"; const EDITOR_TEXTMATE = "textmate"; const EDITOR_EMACS = "emacs"; const EDITOR_MACVIM = "macvim"; const EDITOR_PHPSTORM = "phpstorm"; const EDITOR_IDEA = "idea"; const EDITOR_VSCODE = "vscode"; const EDITOR_ATOM = "atom"; const EDITOR_ESPRESSO = "espresso"; const EDITOR_XDEBUG = "xdebug"; const EDITOR_NETBEANS = "netbeans"; const EDITOR_CURSOR = "cursor"; /** * Search paths to be scanned for resources. * * Stored in the reverse order they're declared. * * @var array */ private $searchPaths = []; /** * Fast lookup cache for known resource locations. * * @var array */ private $resourceCache = []; /** * The name of the custom css file. * * @var string|null */ private $customCss = null; /** * The name of the custom js file. * * @var string|null */ private $customJs = null; /** * @var array[] */ private $extraTables = []; /** * @var bool */ private $handleUnconditionally = false; /** * @var string */ private $pageTitle = "Whoops! There was an error."; /** * @var array[] */ private $applicationPaths; /** * @var array[] */ private $blacklist = [ '_GET' => [], '_POST' => [], '_FILES' => [], '_COOKIE' => [], '_SESSION' => [], '_SERVER' => [], '_ENV' => [], ]; /** * An identifier for a known IDE/text editor. * * Either a string, or a calalble that resolves a string, that can be used * to open a given file in an editor. If the string contains the special * substrings %file or %line, they will be replaced with the correct data. * * @example * "txmt://open?url=%file&line=%line" * * @var callable|string $editor */ protected $editor; /** * A list of known editor strings. * * @var array */ protected $editors = [ "sublime" => "subl://open?url=file://%file&line=%line", "textmate" => "txmt://open?url=file://%file&line=%line", "emacs" => "emacs://open?url=file://%file&line=%line", "macvim" => "mvim://open/?url=file://%file&line=%line", "phpstorm" => "phpstorm://open?file=%file&line=%line", "idea" => "idea://open?file=%file&line=%line", "vscode" => "vscode://file/%file:%line", "atom" => "atom://core/open/file?filename=%file&line=%line", "espresso" => "x-espresso://open?filepath=%file&lines=%line", "netbeans" => "netbeans://open/?f=%file:%line", "cursor" => "cursor://file/%file:%line", ]; /** * @var TemplateHelper */ protected $templateHelper; /** * Constructor. * * @return void */ public function __construct() { if (ini_get('xdebug.file_link_format') || get_cfg_var('xdebug.file_link_format')) { // Register editor using xdebug's file_link_format option. $this->editors['xdebug'] = function ($file, $line) { return str_replace(['%f', '%l'], [$file, $line], ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format')); }; // If xdebug is available, use it as default editor. $this->setEditor('xdebug'); } // Add the default, local resource search path: $this->searchPaths[] = __DIR__ . "/../Resources"; // blacklist php provided auth based values $this->blacklist('_SERVER', 'PHP_AUTH_PW'); $this->templateHelper = new TemplateHelper(); if (class_exists('Symfony\Component\VarDumper\Cloner\VarCloner')) { $cloner = new VarCloner(); // Only dump object internals if a custom caster exists for performance reasons // https://github.com/filp/whoops/pull/404 $cloner->addCasters(['*' => function ($obj, $a, $stub, $isNested, $filter = 0) { $class = $stub->class; $classes = [$class => $class] + class_parents($obj) + class_implements($obj); foreach ($classes as $class) { if (isset(AbstractCloner::$defaultCasters[$class])) { return $a; } } // Remove all internals return []; }]); $this->templateHelper->setCloner($cloner); } } /** * @return int|null * * @throws \Exception */ public function handle() { if (!$this->handleUnconditionally()) { // Check conditions for outputting HTML: // @todo: Make this more robust if (PHP_SAPI === 'cli') { // Help users who have been relying on an internal test value // fix their code to the proper method if (isset($_ENV['whoops-test'])) { throw new \Exception( 'Use handleUnconditionally instead of whoops-test' .' environment variable' ); } return Handler::DONE; } } $templateFile = $this->getResource("views/layout.html.php"); $cssFile = $this->getResource("css/whoops.base.css"); $zeptoFile = $this->getResource("js/zepto.min.js"); $prismJs = $this->getResource("js/prism.js"); $prismCss = $this->getResource("css/prism.css"); $clipboard = $this->getResource("js/clipboard.min.js"); $jsFile = $this->getResource("js/whoops.base.js"); if ($this->customCss) { $customCssFile = $this->getResource($this->customCss); } if ($this->customJs) { $customJsFile = $this->getResource($this->customJs); } $inspector = $this->getInspector(); $frames = $this->getExceptionFrames(); $code = $this->getExceptionCode(); // List of variables that will be passed to the layout template. $vars = [ "page_title" => $this->getPageTitle(), // @todo: Asset compiler "stylesheet" => file_get_contents($cssFile), "zepto" => file_get_contents($zeptoFile), "prismJs" => file_get_contents($prismJs), "prismCss" => file_get_contents($prismCss), "clipboard" => file_get_contents($clipboard), "javascript" => file_get_contents($jsFile), // Template paths: "header" => $this->getResource("views/header.html.php"), "header_outer" => $this->getResource("views/header_outer.html.php"), "frame_list" => $this->getResource("views/frame_list.html.php"), "frames_description" => $this->getResource("views/frames_description.html.php"), "frames_container" => $this->getResource("views/frames_container.html.php"), "panel_details" => $this->getResource("views/panel_details.html.php"), "panel_details_outer" => $this->getResource("views/panel_details_outer.html.php"), "panel_left" => $this->getResource("views/panel_left.html.php"), "panel_left_outer" => $this->getResource("views/panel_left_outer.html.php"), "frame_code" => $this->getResource("views/frame_code.html.php"), "env_details" => $this->getResource("views/env_details.html.php"), "title" => $this->getPageTitle(), "name" => explode("\\", $inspector->getExceptionName()), "message" => $inspector->getExceptionMessage(), "previousMessages" => $inspector->getPreviousExceptionMessages(), "docref_url" => $inspector->getExceptionDocrefUrl(), "code" => $code, "previousCodes" => $inspector->getPreviousExceptionCodes(), "plain_exception" => Formatter::formatExceptionPlain($inspector), "frames" => $frames, "has_frames" => !!count($frames), "handler" => $this, "handlers" => $this->getRun()->getHandlers(), "active_frames_tab" => count($frames) && $frames->offsetGet(0)->isApplication() ? 'application' : 'all', "has_frames_tabs" => $this->getApplicationPaths(), "tables" => [ "GET Data" => $this->masked($_GET, '_GET'), "POST Data" => $this->masked($_POST, '_POST'), "Files" => isset($_FILES) ? $this->masked($_FILES, '_FILES') : [], "Cookies" => $this->masked($_COOKIE, '_COOKIE'), "Session" => isset($_SESSION) ? $this->masked($_SESSION, '_SESSION') : [], "Server/Request Data" => $this->masked($_SERVER, '_SERVER'), "Environment Variables" => $this->masked($_ENV, '_ENV'), ], ]; if (isset($customCssFile)) { $vars["stylesheet"] .= file_get_contents($customCssFile); } if (isset($customJsFile)) { $vars["javascript"] .= file_get_contents($customJsFile); } // Add extra entries list of data tables: // @todo: Consolidate addDataTable and addDataTableCallback $extraTables = array_map(function ($table) use ($inspector) { return $table instanceof \Closure ? $table($inspector) : $table; }, $this->getDataTables()); $vars["tables"] = array_merge($extraTables, $vars["tables"]); $plainTextHandler = new PlainTextHandler(); $plainTextHandler->setRun($this->getRun()); $plainTextHandler->setException($this->getException()); $plainTextHandler->setInspector($this->getInspector()); $vars["preface"] = ""; $this->templateHelper->setVariables($vars); $this->templateHelper->render($templateFile); return Handler::QUIT; } /** * Get the stack trace frames of the exception currently being handled. * * @return \Whoops\Exception\FrameCollection */ protected function getExceptionFrames() { $frames = $this->getInspector()->getFrames($this->getRun()->getFrameFilters()); if ($this->getApplicationPaths()) { foreach ($frames as $frame) { foreach ($this->getApplicationPaths() as $path) { if (strpos($frame->getFile(), $path) === 0) { $frame->setApplication(true); break; } } } } return $frames; } /** * Get the code of the exception currently being handled. * * @return string */ protected function getExceptionCode() { $exception = $this->getException(); $code = $exception->getCode(); if ($exception instanceof \ErrorException) { // ErrorExceptions wrap the php-error types within the 'severity' property $code = Misc::translateErrorCode($exception->getSeverity()); } return (string) $code; } /** * @return string */ public function contentType() { return 'text/html'; } /** * Adds an entry to the list of tables displayed in the template. * * The expected data is a simple associative array. Any nested arrays * will be flattened with `print_r`. * * @param string $label * * @return static */ public function addDataTable($label, array $data) { $this->extraTables[$label] = $data; return $this; } /** * Lazily adds an entry to the list of tables displayed in the table. * * The supplied callback argument will be called when the error is * rendered, it should produce a simple associative array. Any nested * arrays will be flattened with `print_r`. * * @param string $label * @param callable $callback Callable returning an associative array * * @throws InvalidArgumentException If $callback is not callable * * @return static */ public function addDataTableCallback($label, /* callable */ $callback) { if (!is_callable($callback)) { throw new InvalidArgumentException('Expecting callback argument to be callable'); } $this->extraTables[$label] = function (?\Whoops\Inspector\InspectorInterface $inspector = null) use ($callback) { try { $result = call_user_func($callback, $inspector); // Only return the result if it can be iterated over by foreach(). return is_array($result) || $result instanceof \Traversable ? $result : []; } catch (\Exception $e) { // Don't allow failure to break the rendering of the original exception. return []; } }; return $this; } /** * Returns all the extra data tables registered with this handler. * * Optionally accepts a 'label' parameter, to only return the data table * under that label. * * @param string|null $label * * @return array[]|callable */ public function getDataTables($label = null) { if ($label !== null) { return isset($this->extraTables[$label]) ? $this->extraTables[$label] : []; } return $this->extraTables; } /** * Set whether to handle unconditionally. * * Allows to disable all attempts to dynamically decide whether to handle * or return prematurely. Set this to ensure that the handler will perform, * no matter what. * * @param bool|null $value * * @return bool|static */ public function handleUnconditionally($value = null) { if (func_num_args() == 0) { return $this->handleUnconditionally; } $this->handleUnconditionally = (bool) $value; return $this; } /** * Adds an editor resolver. * * Either a string, or a closure that resolves a string, that can be used * to open a given file in an editor. If the string contains the special * substrings %file or %line, they will be replaced with the correct data. * * @example * $run->addEditor('macvim', "mvim://open?url=file://%file&line=%line") * @example * $run->addEditor('remove-it', function($file, $line) { * unlink($file); * return "http://stackoverflow.com"; * }); * * @param string $identifier * @param string|callable $resolver * * @return static */ public function addEditor($identifier, $resolver) { $this->editors[$identifier] = $resolver; return $this; } /** * Set the editor to use to open referenced files. * * Pass either the name of a configured editor, or a closure that directly * resolves an editor string. * * @example * $run->setEditor(function($file, $line) { return "file:///{$file}"; }); * @example * $run->setEditor('sublime'); * * @param string|callable $editor * * @throws InvalidArgumentException If invalid argument identifier provided * * @return static */ public function setEditor($editor) { if (!is_callable($editor) && !isset($this->editors[$editor])) { throw new InvalidArgumentException( "Unknown editor identifier: $editor. Known editors:" . implode(",", array_keys($this->editors)) ); } $this->editor = $editor; return $this; } /** * Get the editor href for a given file and line, if available. * * @param string $filePath * @param int $line * * @throws InvalidArgumentException If editor resolver does not return a string * * @return string|bool */ public function getEditorHref($filePath, $line) { $editor = $this->getEditor($filePath, $line); if (empty($editor)) { return false; } // Check that the editor is a string, and replace the // %line and %file placeholders: if (!isset($editor['url']) || !is_string($editor['url'])) { throw new UnexpectedValueException( __METHOD__ . " should always resolve to a string or a valid editor array; got something else instead." ); } $editor['url'] = str_replace("%line", rawurlencode($line), $editor['url']); $editor['url'] = str_replace("%file", rawurlencode($filePath), $editor['url']); return $editor['url']; } /** * Determine if the editor link should act as an Ajax request. * * @param string $filePath * @param int $line * * @throws UnexpectedValueException If editor resolver does not return a boolean * * @return bool */ public function getEditorAjax($filePath, $line) { $editor = $this->getEditor($filePath, $line); // Check that the ajax is a bool if (!isset($editor['ajax']) || !is_bool($editor['ajax'])) { throw new UnexpectedValueException( __METHOD__ . " should always resolve to a bool; got something else instead." ); } return $editor['ajax']; } /** * Determines both the editor and if ajax should be used. * * @param string $filePath * @param int $line * * @return array */ protected function getEditor($filePath, $line) { if (!$this->editor || (!is_string($this->editor) && !is_callable($this->editor))) { return []; } if (is_string($this->editor) && isset($this->editors[$this->editor]) && !is_callable($this->editors[$this->editor])) { return [ 'ajax' => false, 'url' => $this->editors[$this->editor], ]; } if (is_callable($this->editor) || (isset($this->editors[$this->editor]) && is_callable($this->editors[$this->editor]))) { if (is_callable($this->editor)) { $callback = call_user_func($this->editor, $filePath, $line); } else { $callback = call_user_func($this->editors[$this->editor], $filePath, $line); } if (empty($callback)) { return []; } if (is_string($callback)) { return [ 'ajax' => false, 'url' => $callback, ]; } return [ 'ajax' => isset($callback['ajax']) ? $callback['ajax'] : false, 'url' => isset($callback['url']) ? $callback['url'] : $callback, ]; } return []; } /** * Set the page title. * * @param string $title * * @return static */ public function setPageTitle($title) { $this->pageTitle = (string) $title; return $this; } /** * Get the page title. * * @return string */ public function getPageTitle() { return $this->pageTitle; } /** * Adds a path to the list of paths to be searched for resources. * * @param string $path * * @throws InvalidArgumentException If $path is not a valid directory * * @return static */ public function addResourcePath($path) { if (!is_dir($path)) { throw new InvalidArgumentException( "'$path' is not a valid directory" ); } array_unshift($this->searchPaths, $path); return $this; } /** * Adds a custom css file to be loaded. * * @param string|null $name * * @return static */ public function addCustomCss($name) { $this->customCss = $name; return $this; } /** * Adds a custom js file to be loaded. * * @param string|null $name * * @return static */ public function addCustomJs($name) { $this->customJs = $name; return $this; } /** * @return array */ public function getResourcePaths() { return $this->searchPaths; } /** * Finds a resource, by its relative path, in all available search paths. * * The search is performed starting at the last search path, and all the * way back to the first, enabling a cascading-type system of overrides for * all resources. * * @param string $resource * * @throws RuntimeException If resource cannot be found in any of the available paths * * @return string */ protected function getResource($resource) { // If the resource was found before, we can speed things up // by caching its absolute, resolved path: if (isset($this->resourceCache[$resource])) { return $this->resourceCache[$resource]; } // Search through available search paths, until we find the // resource we're after: foreach ($this->searchPaths as $path) { $fullPath = $path . "/$resource"; if (is_file($fullPath)) { // Cache the result: $this->resourceCache[$resource] = $fullPath; return $fullPath; } } // If we got this far, nothing was found. throw new RuntimeException( "Could not find resource '$resource' in any resource paths." . "(searched: " . join(", ", $this->searchPaths). ")" ); } /** * @deprecated * * @return string */ public function getResourcesPath() { $allPaths = $this->getResourcePaths(); // Compat: return only the first path added return end($allPaths) ?: null; } /** * @deprecated * * @param string $resourcesPath * * @return static */ public function setResourcesPath($resourcesPath) { $this->addResourcePath($resourcesPath); return $this; } /** * Return the application paths. * * @return array */ public function getApplicationPaths() { return $this->applicationPaths; } /** * Set the application paths. * * @return void */ public function setApplicationPaths(array $applicationPaths) { $this->applicationPaths = $applicationPaths; } /** * Set the application root path. * * @param string $applicationRootPath * * @return void */ public function setApplicationRootPath($applicationRootPath) { $this->templateHelper->setApplicationRootPath($applicationRootPath); } /** * blacklist a sensitive value within one of the superglobal arrays. * Alias for the hideSuperglobalKey method. * * @param string $superGlobalName The name of the superglobal array, e.g. '_GET' * @param string $key The key within the superglobal * @see hideSuperglobalKey * * @return static */ public function blacklist($superGlobalName, $key) { $this->blacklist[$superGlobalName][] = $key; return $this; } /** * Hide a sensitive value within one of the superglobal arrays. * * @param string $superGlobalName The name of the superglobal array, e.g. '_GET' * @param string $key The key within the superglobal * @return static */ public function hideSuperglobalKey($superGlobalName, $key) { return $this->blacklist($superGlobalName, $key); } /** * Checks all values within the given superGlobal array. * * Blacklisted values will be replaced by a equal length string containing * only '*' characters for string values. * Non-string values will be replaced with a fixed asterisk count. * We intentionally dont rely on $GLOBALS as it depends on the 'auto_globals_jit' php.ini setting. * * @param array|\ArrayAccess $superGlobal One of the superglobal arrays * @param string $superGlobalName The name of the superglobal array, e.g. '_GET' * * @return array $values without sensitive data */ private function masked($superGlobal, $superGlobalName) { $blacklisted = $this->blacklist[$superGlobalName]; $values = $superGlobal; foreach ($blacklisted as $key) { if (isset($superGlobal[$key])) { $values[$key] = str_repeat('*', is_string($superGlobal[$key]) ? strlen($superGlobal[$key]) : 3); } } return $values; } } ================================================ FILE: src/Whoops/Handler/XmlResponseHandler.php ================================================ */ namespace Whoops\Handler; use SimpleXMLElement; use Whoops\Exception\Formatter; /** * Catches an exception and converts it to an XML * response. Additionally can also return exception * frames for consumption by an API. */ class XmlResponseHandler extends Handler { /** * @var bool */ private $returnFrames = false; /** * @param bool|null $returnFrames * @return bool|static */ public function addTraceToOutput($returnFrames = null) { if (func_num_args() == 0) { return $this->returnFrames; } $this->returnFrames = (bool) $returnFrames; return $this; } /** * @return int */ public function handle() { $response = [ 'error' => Formatter::formatExceptionAsDataArray( $this->getInspector(), $this->addTraceToOutput(), $this->getRun()->getFrameFilters() ), ]; echo self::toXml($response); return Handler::QUIT; } /** * @return string */ public function contentType() { return 'application/xml'; } /** * @param SimpleXMLElement $node Node to append data to, will be modified in place * @param array|\Traversable $data * @return SimpleXMLElement The modified node, for chaining */ private static function addDataToNode(\SimpleXMLElement $node, $data) { assert(is_array($data) || $data instanceof Traversable); foreach ($data as $key => $value) { if (is_numeric($key)) { // Convert the key to a valid string $key = "unknownNode_". (string) $key; } // Delete any char not allowed in XML element names $key = preg_replace('/[^a-z0-9\-\_\.\:]/i', '', $key); if (is_array($value)) { $child = $node->addChild($key); self::addDataToNode($child, $value); } else { $value = str_replace('&', '&', print_r($value, true)); $node->addChild($key, $value); } } return $node; } /** * The main function for converting to an XML document. * * @param array|\Traversable $data * @return string XML */ private static function toXml($data) { assert(is_array($data) || $data instanceof Traversable); $node = simplexml_load_string(""); return self::addDataToNode($node, $data)->asXML(); } } ================================================ FILE: src/Whoops/Inspector/InspectorFactory.php ================================================ */ namespace Whoops\Inspector; use Whoops\Exception\Inspector; class InspectorFactory implements InspectorFactoryInterface { /** * @param \Throwable $exception * @return InspectorInterface */ public function create($exception) { return new Inspector($exception, $this); } } ================================================ FILE: src/Whoops/Inspector/InspectorFactoryInterface.php ================================================ */ namespace Whoops\Inspector; interface InspectorFactoryInterface { /** * @param \Throwable $exception * @return InspectorInterface */ public function create($exception); } ================================================ FILE: src/Whoops/Inspector/InspectorInterface.php ================================================ */ namespace Whoops\Inspector; interface InspectorInterface { /** * @return \Throwable */ public function getException(); /** * @return string */ public function getExceptionName(); /** * @return string */ public function getExceptionMessage(); /** * @return string[] */ public function getPreviousExceptionMessages(); /** * @return int[] */ public function getPreviousExceptionCodes(); /** * Returns a url to the php-manual related to the underlying error - when available. * * @return string|null */ public function getExceptionDocrefUrl(); /** * Does the wrapped Exception has a previous Exception? * @return bool */ public function hasPreviousException(); /** * Returns an Inspector for a previous Exception, if any. * @todo Clean this up a bit, cache stuff a bit better. * @return InspectorInterface */ public function getPreviousExceptionInspector(); /** * Returns an array of all previous exceptions for this inspector's exception * @return \Throwable[] */ public function getPreviousExceptions(); /** * Returns an iterator for the inspected exception's * frames. * * @param array $frameFilters * * @return \Whoops\Exception\FrameCollection */ public function getFrames(array $frameFilters = []); } ================================================ FILE: src/Whoops/Resources/css/prism.css ================================================ /* PrismJS 1.30.0 https://prismjs.com/download.html#themes=prism-tomorrow&languages=markup+markup-templating+php&plugins=line-highlight+line-numbers */ code[class*=language-],pre[class*=language-]{color:#ccc;background:0 0;font-family:Consolas,Monaco,'Andale Mono','Ubuntu Mono',monospace;font-size:1em;text-align:left;white-space:pre;word-spacing:normal;word-break:normal;word-wrap:normal;line-height:1.5;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-hyphens:none;-moz-hyphens:none;-ms-hyphens:none;hyphens:none}pre[class*=language-]{padding:1em;margin:.5em 0;overflow:auto}:not(pre)>code[class*=language-],pre[class*=language-]{background:#2d2d2d}:not(pre)>code[class*=language-]{padding:.1em;border-radius:.3em;white-space:normal}.token.block-comment,.token.cdata,.token.comment,.token.doctype,.token.prolog{color:#999}.token.punctuation{color:#ccc}.token.attr-name,.token.deleted,.token.namespace,.token.tag{color:#e2777a}.token.function-name{color:#6196cc}.token.boolean,.token.function,.token.number{color:#f08d49}.token.class-name,.token.constant,.token.property,.token.symbol{color:#f8c555}.token.atrule,.token.builtin,.token.important,.token.keyword,.token.selector{color:#cc99cd}.token.attr-value,.token.char,.token.regex,.token.string,.token.variable{color:#7ec699}.token.entity,.token.operator,.token.url{color:#67cdcc}.token.bold,.token.important{font-weight:700}.token.italic{font-style:italic}.token.entity{cursor:help}.token.inserted{color:green} pre[data-line]{position:relative;padding:1em 0 1em 3em}.line-highlight{position:absolute;left:0;right:0;padding:inherit 0;margin-top:1em;background:hsla(24,20%,50%,.08);background:linear-gradient(to right,hsla(24,20%,50%,.1) 70%,hsla(24,20%,50%,0));pointer-events:none;line-height:inherit;white-space:pre}@media print{.line-highlight{-webkit-print-color-adjust:exact;color-adjust:exact}}.line-highlight:before,.line-highlight[data-end]:after{content:attr(data-start);position:absolute;top:.4em;left:.6em;min-width:1em;padding:0 .5em;background-color:hsla(24,20%,50%,.4);color:#f4f1ef;font:bold 65%/1.5 sans-serif;text-align:center;vertical-align:.3em;border-radius:999px;text-shadow:none;box-shadow:0 1px #fff}.line-highlight[data-end]:after{content:attr(data-end);top:auto;bottom:.4em}.line-numbers .line-highlight:after,.line-numbers .line-highlight:before{content:none}pre[id].linkable-line-numbers span.line-numbers-rows{pointer-events:all}pre[id].linkable-line-numbers span.line-numbers-rows>span:before{cursor:pointer}pre[id].linkable-line-numbers span.line-numbers-rows>span:hover:before{background-color:rgba(128,128,128,.2)} pre[class*=language-].line-numbers{position:relative;padding-left:3.8em;counter-reset:linenumber}pre[class*=language-].line-numbers>code{position:relative;white-space:inherit}.line-numbers .line-numbers-rows{position:absolute;pointer-events:none;top:0;font-size:100%;left:-3.8em;width:3em;letter-spacing:-1px;border-right:1px solid #999;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.line-numbers-rows>span{display:block;counter-increment:linenumber}.line-numbers-rows>span:before{content:counter(linenumber);color:#999;display:block;padding-right:.8em;text-align:right} ================================================ FILE: src/Whoops/Resources/css/whoops.base.css ================================================ body { font: 12px "Helvetica Neue", helvetica, arial, sans-serif; color: #131313; background: #eeeeee; padding:0; margin: 0; max-height: 100%; text-rendering: optimizeLegibility; } a { text-decoration: none; } .Whoops.container { position: relative; z-index: 9999999999; } .panel { overflow-y: scroll; height: 100%; position: fixed; margin: 0; left: 0; top: 0; } .branding { position: absolute; top: 10px; right: 20px; color: #777777; font-size: 10px; z-index: 100; } .branding a { color: #e95353; } header { color: white; box-sizing: border-box; background-color: #2a2a2a; padding: 35px 40px; max-height: 180px; overflow: hidden; transition: 0.5s; } header.header-expand { max-height: 1000px; } .exc-title { margin: 0; color: #bebebe; font-size: 14px; } .exc-title-primary, .exc-title-secondary { color: #e95353; } .exc-message { font-size: 20px; word-wrap: break-word; margin: 4px 0 0 0; color: white; } .exc-message span { display: block; } .exc-message-empty-notice { color: #a29d9d; font-weight: 300; } .prev-exc-title { margin: 10px 0; } .prev-exc-title + ul { margin: 0; padding: 0 0 0 20px; line-height: 12px; } .prev-exc-title + ul li { font: 12px "Helvetica Neue", helvetica, arial, sans-serif; } .prev-exc-title + ul li .prev-exc-code { display: inline-block; color: #bebebe; } .details-container { left: 30%; width: 70%; background: #fafafa; } .details { padding: 5px; } .details-heading { color: #4288CE; font-weight: 300; padding-bottom: 10px; margin-bottom: 10px; border-bottom: 1px solid rgba(0, 0, 0, .1); } .details pre.sf-dump { white-space: pre; word-wrap: inherit; } .details pre.sf-dump, .details pre.sf-dump .sf-dump-num, .details pre.sf-dump .sf-dump-const, .details pre.sf-dump .sf-dump-str, .details pre.sf-dump .sf-dump-note, .details pre.sf-dump .sf-dump-ref, .details pre.sf-dump .sf-dump-public, .details pre.sf-dump .sf-dump-protected, .details pre.sf-dump .sf-dump-private, .details pre.sf-dump .sf-dump-meta, .details pre.sf-dump .sf-dump-key, .details pre.sf-dump .sf-dump-index { color: #463C54; } .left-panel { width: 30%; background: #ded8d8; } .frames-description { background: rgba(0, 0, 0, .05); padding: 8px 15px; color: #a29d9d; font-size: 11px; } .frames-description.frames-description-application { text-align: center; font-size: 12px; } .frames-container.frames-container-application .frame:not(.frame-application) { display: none; } .frames-tab { color: #a29d9d; display: inline-block; padding: 4px 8px; margin: 0 2px; border-radius: 3px; } .frames-tab.frames-tab-active { background-color: #2a2a2a; color: #bebebe; } .frame { padding: 14px; cursor: pointer; transition: all 0.1s ease; background: #eeeeee; } .frame:not(:last-child) { border-bottom: 1px solid rgba(0, 0, 0, .05); } .frame.active { box-shadow: inset -5px 0 0 0 #4288CE; color: #4288CE; } .frame:not(.active):hover { background: #BEE9EA; } .frame-method-info { margin-bottom: 10px; } .frame-class, .frame-function, .frame-index { font-size: 14px; } .frame-index { float: left; } .frame-method-info { margin-left: 24px; } .frame-index { font-size: 11px; color: #a29d9d; background-color: rgba(0, 0, 0, .05); height: 18px; width: 18px; line-height: 18px; border-radius: 5px; padding: 0 1px 0 1px; text-align: center; display: inline-block; } .frame-application .frame-index { background-color: #2a2a2a; color: #bebebe; } .frame-file { font-family: "Inconsolata", "Fira Mono", "Source Code Pro", Monaco, Consolas, "Lucida Console", monospace; color: #a29d9d; } .frame-file .editor-link { color: #a29d9d; } .frame-line { font-weight: bold; } .frame-code { padding: 5px; background: #303030; display: none; } .frame-code.active { display: block; } .frame-code .frame-file { color: #a29d9d; padding: 12px 6px; border-bottom: none; } .code-block { padding: 10px; margin: 0; border-radius: 6px; box-shadow: 0 3px 0 rgba(0, 0, 0, .05), 0 10px 30px rgba(0, 0, 0, .05), inset 0 0 1px 0 rgba(255, 255, 255, .07); -moz-tab-size: 4; -o-tab-size: 4; tab-size: 4; } .linenums { margin: 0; margin-left: 10px; } .frame-comments { border-top: none; margin-top: 15px; font-size: 12px; } .frame-comments.empty { } .frame-comments.empty:before { content: "No comments for this stack frame."; font-weight: 300; color: #a29d9d; } .frame-comment { padding: 10px; color: #e3e3e3; border-radius: 6px; background-color: rgba(255, 255, 255, .05); } .frame-comment a { font-weight: bold; text-decoration: underline; color: #c6c6c6; } .frame-comment:not(:last-child) { border-bottom: 1px dotted rgba(0, 0, 0, .3); } .frame-comment-context { font-size: 10px; color: white; } .delimiter { display: inline-block; } .data-table-container label { font-size: 16px; color: #303030; font-weight: bold; margin: 10px 0; display: block; margin-bottom: 5px; padding-bottom: 5px; } .data-table { width: 100%; margin-bottom: 10px; } .data-table tbody { font: 13px "Inconsolata", "Fira Mono", "Source Code Pro", Monaco, Consolas, "Lucida Console", monospace; } .data-table thead { display: none; } .data-table tr { padding: 5px 0; } .data-table td:first-child { width: 20%; min-width: 130px; overflow: hidden; font-weight: bold; color: #463C54; padding-right: 5px; } .data-table td:last-child { width: 80%; -ms-word-break: break-all; word-break: break-all; word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; } .data-table span.empty { color: rgba(0, 0, 0, .3); font-weight: 300; } .data-table label.empty { display: inline; } .handler { padding: 4px 0; font: 14px "Inconsolata", "Fira Mono", "Source Code Pro", Monaco, Consolas, "Lucida Console", monospace; } #plain-exception { display: none; } .rightButton { cursor: pointer; border: 0; opacity: .8; background: none; color: rgba(255, 255, 255, 0.1); box-shadow: inset 0 0 0 2px rgba(255, 255, 255, 0.1); border-radius: 3px; outline: none !important; } .rightButton:hover { box-shadow: inset 0 0 0 2px rgba(255, 255, 255, 0.3); color: rgba(255, 255, 255, 0.3); } /* inspired by githubs kbd styles */ kbd { -moz-border-bottom-colors: none; -moz-border-left-colors: none; -moz-border-right-colors: none; -moz-border-top-colors: none; background-color: #fcfcfc; border-color: #ccc #ccc #bbb; border-image: none; border-style: solid; border-width: 1px; color: #555; display: inline-block; font-size: 11px; line-height: 10px; padding: 3px 5px; vertical-align: middle; } /* == Media queries */ /* Expand the spacing in the details section */ @media (min-width: 1000px) { .details, .frame-code { padding: 20px 40px; } .details-container { left: 32%; width: 68%; } .frames-container { margin: 5px; } .left-panel { width: 32%; } } /* Stack panels */ @media (max-width: 600px) { .panel { position: static; width: 100%; } } /* Stack details tables */ @media (max-width: 400px) { .data-table, .data-table tbody, .data-table tbody tr, .data-table tbody td { display: block; width: 100%; } .data-table tbody tr:first-child { padding-top: 0; } .data-table tbody td:first-child, .data-table tbody td:last-child { padding-left: 0; padding-right: 0; } .data-table tbody td:last-child { padding-top: 3px; } } .tooltipped { position: relative } .tooltipped:after { position: absolute; z-index: 1000000; display: none; padding: 5px 8px; color: #fff; text-align: center; text-decoration: none; text-shadow: none; text-transform: none; letter-spacing: normal; word-wrap: break-word; white-space: pre; pointer-events: none; content: attr(aria-label); background: rgba(0, 0, 0, 0.8); border-radius: 3px; -webkit-font-smoothing: subpixel-antialiased } .tooltipped:before { position: absolute; z-index: 1000001; display: none; width: 0; height: 0; color: rgba(0, 0, 0, 0.8); pointer-events: none; content: ""; border: 5px solid transparent } .tooltipped:hover:before, .tooltipped:hover:after, .tooltipped:active:before, .tooltipped:active:after, .tooltipped:focus:before, .tooltipped:focus:after { display: inline-block; text-decoration: none } .tooltipped-s:after { top: 100%; right: 50%; margin-top: 5px } .tooltipped-s:before { top: auto; right: 50%; bottom: -5px; margin-right: -5px; border-bottom-color: rgba(0, 0, 0, 0.8) } pre.sf-dump { padding: 0px !important; margin: 0px !important; } .search-for-help { width: 85%; padding: 0; margin: 10px 0; list-style-type: none; display: inline-block; } .search-for-help li { display: inline-block; margin-right: 5px; } .search-for-help li:last-child { margin-right: 0; } .search-for-help li a { } .search-for-help li a i { width: 16px; height: 16px; overflow: hidden; display: block; } .search-for-help li a svg { fill: #fff; } .search-for-help li a svg path { background-size: contain; } .line-numbers-rows span { pointer-events: auto; cursor: pointer; } .line-numbers-rows span:hover { text-decoration: underline; } ================================================ FILE: src/Whoops/Resources/js/prism.js ================================================ /* PrismJS 1.30.0 https://prismjs.com/download.html#themes=prism-tomorrow&languages=markup+markup-templating+php&plugins=line-highlight+line-numbers */ var _self="undefined"!=typeof window?window:"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?self:{},Prism=function(e){var n=/(?:^|\s)lang(?:uage)?-([\w-]+)(?=\s|$)/i,t=0,r={},a={manual:e.Prism&&e.Prism.manual,disableWorkerMessageHandler:e.Prism&&e.Prism.disableWorkerMessageHandler,util:{encode:function e(n){return n instanceof i?new i(n.type,e(n.content),n.alias):Array.isArray(n)?n.map(e):n.replace(/&/g,"&").replace(/=g.reach);A+=w.value.length,w=w.next){var P=w.value;if(n.length>e.length)return;if(!(P instanceof i)){var E,S=1;if(y){if(!(E=l(b,A,e,m))||E.index>=e.length)break;var L=E.index,O=E.index+E[0].length,C=A;for(C+=w.value.length;L>=C;)C+=(w=w.next).value.length;if(A=C-=w.value.length,w.value instanceof i)continue;for(var j=w;j!==n.tail&&(Cg.reach&&(g.reach=W);var I=w.prev;if(_&&(I=u(n,I,_),A+=_.length),c(n,I,S),w=u(n,I,new i(f,p?a.tokenize(N,p):N,k,N)),M&&u(n,w,M),S>1){var T={cause:f+","+d,reach:W};o(e,n,t,w.prev,A,T),g&&T.reach>g.reach&&(g.reach=T.reach)}}}}}}function s(){var e={value:null,prev:null,next:null},n={value:null,prev:e,next:null};e.next=n,this.head=e,this.tail=n,this.length=0}function u(e,n,t){var r=n.next,a={value:t,prev:n,next:r};return n.next=a,r.prev=a,e.length++,a}function c(e,n,t){for(var r=n.next,a=0;a"+i.content+""},!e.document)return e.addEventListener?(a.disableWorkerMessageHandler||e.addEventListener("message",(function(n){var t=JSON.parse(n.data),r=t.language,i=t.code,l=t.immediateClose;e.postMessage(a.highlight(i,a.languages[r],r)),l&&e.close()}),!1),a):a;var g=a.util.currentScript();function f(){a.manual||a.highlightAll()}if(g&&(a.filename=g.src,g.hasAttribute("data-manual")&&(a.manual=!0)),!a.manual){var h=document.readyState;"loading"===h||"interactive"===h&&g&&g.defer?document.addEventListener("DOMContentLoaded",f):window.requestAnimationFrame?window.requestAnimationFrame(f):window.setTimeout(f,16)}return a}(_self);"undefined"!=typeof module&&module.exports&&(module.exports=Prism),"undefined"!=typeof global&&(global.Prism=Prism); Prism.languages.markup={comment:{pattern://,greedy:!0},prolog:{pattern:/<\?[\s\S]+?\?>/,greedy:!0},doctype:{pattern:/"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]|"[^"]*"|'[^']*'|<(?!!--)|)*\]\s*)?>/i,greedy:!0,inside:{"internal-subset":{pattern:/(^[^\[]*\[)[\s\S]+(?=\]>$)/,lookbehind:!0,greedy:!0,inside:null},string:{pattern:/"[^"]*"|'[^']*'/,greedy:!0},punctuation:/^$|[[\]]/,"doctype-tag":/^DOCTYPE/i,name:/[^\s<>'"]+/}},cdata:{pattern://i,greedy:!0},tag:{pattern:/<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,greedy:!0,inside:{tag:{pattern:/^<\/?[^\s>\/]+/,inside:{punctuation:/^<\/?/,namespace:/^[^\s>\/:]+:/}},"special-attr":[],"attr-value":{pattern:/=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,inside:{punctuation:[{pattern:/^=/,alias:"attr-equals"},{pattern:/^(\s*)["']|["']$/,lookbehind:!0}]}},punctuation:/\/?>/,"attr-name":{pattern:/[^\s>\/]+/,inside:{namespace:/^[^\s>\/:]+:/}}}},entity:[{pattern:/&[\da-z]{1,8};/i,alias:"named-entity"},/&#x?[\da-f]{1,8};/i]},Prism.languages.markup.tag.inside["attr-value"].inside.entity=Prism.languages.markup.entity,Prism.languages.markup.doctype.inside["internal-subset"].inside=Prism.languages.markup,Prism.hooks.add("wrap",(function(a){"entity"===a.type&&(a.attributes.title=a.content.replace(/&/,"&"))})),Object.defineProperty(Prism.languages.markup.tag,"addInlined",{value:function(a,e){var s={};s["language-"+e]={pattern:/(^$)/i,lookbehind:!0,inside:Prism.languages[e]},s.cdata=/^$/i;var t={"included-cdata":{pattern://i,inside:s}};t["language-"+e]={pattern:/[\s\S]+/,inside:Prism.languages[e]};var n={};n[a]={pattern:RegExp("(<__[^>]*>)(?:))*\\]\\]>|(?!)".replace(/__/g,(function(){return a})),"i"),lookbehind:!0,greedy:!0,inside:t},Prism.languages.insertBefore("markup","cdata",n)}}),Object.defineProperty(Prism.languages.markup.tag,"addAttribute",{value:function(a,e){Prism.languages.markup.tag.inside["special-attr"].push({pattern:RegExp("(^|[\"'\\s])(?:"+a+")\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s'\">=]+(?=[\\s>]))","i"),lookbehind:!0,inside:{"attr-name":/^[^\s=]+/,"attr-value":{pattern:/=[\s\S]+/,inside:{value:{pattern:/(^=\s*(["']|(?!["'])))\S[\s\S]*(?=\2$)/,lookbehind:!0,alias:[e,"language-"+e],inside:Prism.languages[e]},punctuation:[{pattern:/^=/,alias:"attr-equals"},/"|'/]}}}})}}),Prism.languages.html=Prism.languages.markup,Prism.languages.mathml=Prism.languages.markup,Prism.languages.svg=Prism.languages.markup,Prism.languages.xml=Prism.languages.extend("markup",{}),Prism.languages.ssml=Prism.languages.xml,Prism.languages.atom=Prism.languages.xml,Prism.languages.rss=Prism.languages.xml; !function(e){function n(e,n){return"___"+e.toUpperCase()+n+"___"}Object.defineProperties(e.languages["markup-templating"]={},{buildPlaceholders:{value:function(t,a,r,o){if(t.language===a){var c=t.tokenStack=[];t.code=t.code.replace(r,(function(e){if("function"==typeof o&&!o(e))return e;for(var r,i=c.length;-1!==t.code.indexOf(r=n(a,i));)++i;return c[i]=e,r})),t.grammar=e.languages.markup}}},tokenizePlaceholders:{value:function(t,a){if(t.language===a&&t.tokenStack){t.grammar=e.languages[a];var r=0,o=Object.keys(t.tokenStack);!function c(i){for(var u=0;u=o.length);u++){var g=i[u];if("string"==typeof g||g.content&&"string"==typeof g.content){var l=o[r],s=t.tokenStack[l],f="string"==typeof g?g:g.content,p=n(a,l),k=f.indexOf(p);if(k>-1){++r;var m=f.substring(0,k),d=new e.Token(a,e.tokenize(s,t.grammar),"language-"+a,s),h=f.substring(k+p.length),v=[];m&&v.push.apply(v,c([m])),v.push(d),h&&v.push.apply(v,c([h])),"string"==typeof g?i.splice.apply(i,[u,1].concat(v)):g.content=v}}else g.content&&c(g.content)}return i}(t.tokens)}}}})}(Prism); !function(e){var a=/\/\*[\s\S]*?\*\/|\/\/.*|#(?!\[).*/,t=[{pattern:/\b(?:false|true)\b/i,alias:"boolean"},{pattern:/(::\s*)\b[a-z_]\w*\b(?!\s*\()/i,greedy:!0,lookbehind:!0},{pattern:/(\b(?:case|const)\s+)\b[a-z_]\w*(?=\s*[;=])/i,greedy:!0,lookbehind:!0},/\b(?:null)\b/i,/\b[A-Z_][A-Z0-9_]*\b(?!\s*\()/],i=/\b0b[01]+(?:_[01]+)*\b|\b0o[0-7]+(?:_[0-7]+)*\b|\b0x[\da-f]+(?:_[\da-f]+)*\b|(?:\b\d+(?:_\d+)*\.?(?:\d+(?:_\d+)*)?|\B\.\d+)(?:e[+-]?\d+)?/i,n=/|\?\?=?|\.{3}|\??->|[!=]=?=?|::|\*\*=?|--|\+\+|&&|\|\||<<|>>|[?~]|[/^|%*&<>.+-]=?/,s=/[{}\[\](),:;]/;e.languages.php={delimiter:{pattern:/\?>$|^<\?(?:php(?=\s)|=)?/i,alias:"important"},comment:a,variable:/\$+(?:\w+\b|(?=\{))/,package:{pattern:/(namespace\s+|use\s+(?:function\s+)?)(?:\\?\b[a-z_]\w*)+\b(?!\\)/i,lookbehind:!0,inside:{punctuation:/\\/}},"class-name-definition":{pattern:/(\b(?:class|enum|interface|trait)\s+)\b[a-z_]\w*(?!\\)\b/i,lookbehind:!0,alias:"class-name"},"function-definition":{pattern:/(\bfunction\s+)[a-z_]\w*(?=\s*\()/i,lookbehind:!0,alias:"function"},keyword:[{pattern:/(\(\s*)\b(?:array|bool|boolean|float|int|integer|object|string)\b(?=\s*\))/i,alias:"type-casting",greedy:!0,lookbehind:!0},{pattern:/([(,?]\s*)\b(?:array(?!\s*\()|bool|callable|(?:false|null)(?=\s*\|)|float|int|iterable|mixed|object|self|static|string)\b(?=\s*\$)/i,alias:"type-hint",greedy:!0,lookbehind:!0},{pattern:/(\)\s*:\s*(?:\?\s*)?)\b(?:array(?!\s*\()|bool|callable|(?:false|null)(?=\s*\|)|float|int|iterable|mixed|never|object|self|static|string|void)\b/i,alias:"return-type",greedy:!0,lookbehind:!0},{pattern:/\b(?:array(?!\s*\()|bool|float|int|iterable|mixed|object|string|void)\b/i,alias:"type-declaration",greedy:!0},{pattern:/(\|\s*)(?:false|null)\b|\b(?:false|null)(?=\s*\|)/i,alias:"type-declaration",greedy:!0,lookbehind:!0},{pattern:/\b(?:parent|self|static)(?=\s*::)/i,alias:"static-context",greedy:!0},{pattern:/(\byield\s+)from\b/i,lookbehind:!0},/\bclass\b/i,{pattern:/((?:^|[^\s>:]|(?:^|[^-])>|(?:^|[^:]):)\s*)\b(?:abstract|and|array|as|break|callable|case|catch|clone|const|continue|declare|default|die|do|echo|else|elseif|empty|enddeclare|endfor|endforeach|endif|endswitch|endwhile|enum|eval|exit|extends|final|finally|fn|for|foreach|function|global|goto|if|implements|include|include_once|instanceof|insteadof|interface|isset|list|match|namespace|never|new|or|parent|print|private|protected|public|readonly|require|require_once|return|self|static|switch|throw|trait|try|unset|use|var|while|xor|yield|__halt_compiler)\b/i,lookbehind:!0}],"argument-name":{pattern:/([(,]\s*)\b[a-z_]\w*(?=\s*:(?!:))/i,lookbehind:!0},"class-name":[{pattern:/(\b(?:extends|implements|instanceof|new(?!\s+self|\s+static))\s+|\bcatch\s*\()\b[a-z_]\w*(?!\\)\b/i,greedy:!0,lookbehind:!0},{pattern:/(\|\s*)\b[a-z_]\w*(?!\\)\b/i,greedy:!0,lookbehind:!0},{pattern:/\b[a-z_]\w*(?!\\)\b(?=\s*\|)/i,greedy:!0},{pattern:/(\|\s*)(?:\\?\b[a-z_]\w*)+\b/i,alias:"class-name-fully-qualified",greedy:!0,lookbehind:!0,inside:{punctuation:/\\/}},{pattern:/(?:\\?\b[a-z_]\w*)+\b(?=\s*\|)/i,alias:"class-name-fully-qualified",greedy:!0,inside:{punctuation:/\\/}},{pattern:/(\b(?:extends|implements|instanceof|new(?!\s+self\b|\s+static\b))\s+|\bcatch\s*\()(?:\\?\b[a-z_]\w*)+\b(?!\\)/i,alias:"class-name-fully-qualified",greedy:!0,lookbehind:!0,inside:{punctuation:/\\/}},{pattern:/\b[a-z_]\w*(?=\s*\$)/i,alias:"type-declaration",greedy:!0},{pattern:/(?:\\?\b[a-z_]\w*)+(?=\s*\$)/i,alias:["class-name-fully-qualified","type-declaration"],greedy:!0,inside:{punctuation:/\\/}},{pattern:/\b[a-z_]\w*(?=\s*::)/i,alias:"static-context",greedy:!0},{pattern:/(?:\\?\b[a-z_]\w*)+(?=\s*::)/i,alias:["class-name-fully-qualified","static-context"],greedy:!0,inside:{punctuation:/\\/}},{pattern:/([(,?]\s*)[a-z_]\w*(?=\s*\$)/i,alias:"type-hint",greedy:!0,lookbehind:!0},{pattern:/([(,?]\s*)(?:\\?\b[a-z_]\w*)+(?=\s*\$)/i,alias:["class-name-fully-qualified","type-hint"],greedy:!0,lookbehind:!0,inside:{punctuation:/\\/}},{pattern:/(\)\s*:\s*(?:\?\s*)?)\b[a-z_]\w*(?!\\)\b/i,alias:"return-type",greedy:!0,lookbehind:!0},{pattern:/(\)\s*:\s*(?:\?\s*)?)(?:\\?\b[a-z_]\w*)+\b(?!\\)/i,alias:["class-name-fully-qualified","return-type"],greedy:!0,lookbehind:!0,inside:{punctuation:/\\/}}],constant:t,function:{pattern:/(^|[^\\\w])\\?[a-z_](?:[\w\\]*\w)?(?=\s*\()/i,lookbehind:!0,inside:{punctuation:/\\/}},property:{pattern:/(->\s*)\w+/,lookbehind:!0},number:i,operator:n,punctuation:s};var l={pattern:/\{\$(?:\{(?:\{[^{}]+\}|[^{}]+)\}|[^{}])+\}|(^|[^\\{])\$+(?:\w+(?:\[[^\r\n\[\]]+\]|->\w+)?)/,lookbehind:!0,inside:e.languages.php},r=[{pattern:/<<<'([^']+)'[\r\n](?:.*[\r\n])*?\1;/,alias:"nowdoc-string",greedy:!0,inside:{delimiter:{pattern:/^<<<'[^']+'|[a-z_]\w*;$/i,alias:"symbol",inside:{punctuation:/^<<<'?|[';]$/}}}},{pattern:/<<<(?:"([^"]+)"[\r\n](?:.*[\r\n])*?\1;|([a-z_]\w*)[\r\n](?:.*[\r\n])*?\2;)/i,alias:"heredoc-string",greedy:!0,inside:{delimiter:{pattern:/^<<<(?:"[^"]+"|[a-z_]\w*)|[a-z_]\w*;$/i,alias:"symbol",inside:{punctuation:/^<<<"?|[";]$/}},interpolation:l}},{pattern:/`(?:\\[\s\S]|[^\\`])*`/,alias:"backtick-quoted-string",greedy:!0},{pattern:/'(?:\\[\s\S]|[^\\'])*'/,alias:"single-quoted-string",greedy:!0},{pattern:/"(?:\\[\s\S]|[^\\"])*"/,alias:"double-quoted-string",greedy:!0,inside:{interpolation:l}}];e.languages.insertBefore("php","variable",{string:r,attribute:{pattern:/#\[(?:[^"'\/#]|\/(?![*/])|\/\/.*$|#(?!\[).*$|\/\*(?:[^*]|\*(?!\/))*\*\/|"(?:\\[\s\S]|[^\\"])*"|'(?:\\[\s\S]|[^\\'])*')+\](?=\s*[a-z$#])/im,greedy:!0,inside:{"attribute-content":{pattern:/^(#\[)[\s\S]+(?=\]$)/,lookbehind:!0,inside:{comment:a,string:r,"attribute-class-name":[{pattern:/([^:]|^)\b[a-z_]\w*(?!\\)\b/i,alias:"class-name",greedy:!0,lookbehind:!0},{pattern:/([^:]|^)(?:\\?\b[a-z_]\w*)+/i,alias:["class-name","class-name-fully-qualified"],greedy:!0,lookbehind:!0,inside:{punctuation:/\\/}}],constant:t,number:i,operator:n,punctuation:s}},delimiter:{pattern:/^#\[|\]$/,alias:"punctuation"}}}}),e.hooks.add("before-tokenize",(function(a){/<\?/.test(a.code)&&e.languages["markup-templating"].buildPlaceholders(a,"php",/<\?(?:[^"'/#]|\/(?![*/])|("|')(?:\\[\s\S]|(?!\1)[^\\])*\1|(?:\/\/|#(?!\[))(?:[^?\n\r]|\?(?!>))*(?=$|\?>|[\r\n])|#\[|\/\*(?:[^*]|\*(?!\/))*(?:\*\/|$))*?(?:\?>|$)/g)})),e.hooks.add("after-tokenize",(function(a){e.languages["markup-templating"].tokenizePlaceholders(a,"php")}))}(Prism); !function(){if("undefined"!=typeof Prism&&"undefined"!=typeof document&&document.querySelector){var e,t="line-numbers",i="linkable-line-numbers",n=/\n(?!$)/g,r=!0;Prism.plugins.lineHighlight={highlightLines:function(o,u,c){var h=(u="string"==typeof u?u:o.getAttribute("data-line")||"").replace(/\s+/g,"").split(",").filter(Boolean),d=+o.getAttribute("data-line-offset")||0,f=(function(){if(void 0===e){var t=document.createElement("div");t.style.fontSize="13px",t.style.lineHeight="1.5",t.style.padding="0",t.style.border="0",t.innerHTML=" 
 ",document.body.appendChild(t),e=38===t.offsetHeight,document.body.removeChild(t)}return e}()?parseInt:parseFloat)(getComputedStyle(o).lineHeight),p=Prism.util.isActive(o,t),g=o.querySelector("code"),m=p?o:g||o,v=[],y=g.textContent.match(n),b=y?y.length+1:1,A=g&&m!=g?function(e,t){var i=getComputedStyle(e),n=getComputedStyle(t);function r(e){return+e.substr(0,e.length-2)}return t.offsetTop+r(n.borderTopWidth)+r(n.paddingTop)-r(i.paddingTop)}(o,g):0;h.forEach((function(e){var t=e.split("-"),i=+t[0],n=+t[1]||i;if(!((n=Math.min(b+d,n))i&&r.setAttribute("data-end",String(n)),r.style.top=(i-d-1)*f+A+"px",r.textContent=new Array(n-i+2).join(" \n")}));v.push((function(){r.style.width=o.scrollWidth+"px"})),v.push((function(){m.appendChild(r)}))}}));var P=o.id;if(p&&Prism.util.isActive(o,i)&&P){l(o,i)||v.push((function(){o.classList.add(i)}));var E=parseInt(o.getAttribute("data-start")||"1");s(".line-numbers-rows > span",o).forEach((function(e,t){var i=t+E;e.onclick=function(){var e=P+"."+i;r=!1,location.hash=e,setTimeout((function(){r=!0}),1)}}))}return function(){v.forEach(a)}}};var o=0;Prism.hooks.add("before-sanity-check",(function(e){var t=e.element.parentElement;if(u(t)){var i=0;s(".line-highlight",t).forEach((function(e){i+=e.textContent.length,e.parentNode.removeChild(e)})),i&&/^(?: \n)+$/.test(e.code.slice(-i))&&(e.code=e.code.slice(0,-i))}})),Prism.hooks.add("complete",(function e(i){var n=i.element.parentElement;if(u(n)){clearTimeout(o);var r=Prism.plugins.lineNumbers,s=i.plugins&&i.plugins.lineNumbers;l(n,t)&&r&&!s?Prism.hooks.add("line-numbers",e):(Prism.plugins.lineHighlight.highlightLines(n)(),o=setTimeout(c,1))}})),window.addEventListener("hashchange",c),window.addEventListener("resize",(function(){s("pre").filter(u).map((function(e){return Prism.plugins.lineHighlight.highlightLines(e)})).forEach(a)}))}function s(e,t){return Array.prototype.slice.call((t||document).querySelectorAll(e))}function l(e,t){return e.classList.contains(t)}function a(e){e()}function u(e){return!!(e&&/pre/i.test(e.nodeName)&&(e.hasAttribute("data-line")||e.id&&Prism.util.isActive(e,i)))}function c(){var e=location.hash.slice(1);s(".temporary.line-highlight").forEach((function(e){e.parentNode.removeChild(e)}));var t=(e.match(/\.([\d,-]+)$/)||[,""])[1];if(t&&!document.getElementById(e)){var i=e.slice(0,e.lastIndexOf(".")),n=document.getElementById(i);n&&(n.hasAttribute("data-line")||n.setAttribute("data-line",""),Prism.plugins.lineHighlight.highlightLines(n,t,"temporary ")(),r&&document.querySelector(".temporary.line-highlight").scrollIntoView())}}}(); !function(){if("undefined"!=typeof Prism&&"undefined"!=typeof document){var e="line-numbers",n=/\n(?!$)/g,t=Prism.plugins.lineNumbers={getLine:function(n,t){if("PRE"===n.tagName&&n.classList.contains(e)){var i=n.querySelector(".line-numbers-rows");if(i){var r=parseInt(n.getAttribute("data-start"),10)||1,s=r+(i.children.length-1);ts&&(t=s);var l=t-r;return i.children[l]}}},resize:function(e){r([e])},assumeViewportIndependence:!0},i=void 0;window.addEventListener("resize",(function(){t.assumeViewportIndependence&&i===window.innerWidth||(i=window.innerWidth,r(Array.prototype.slice.call(document.querySelectorAll("pre.line-numbers"))))})),Prism.hooks.add("complete",(function(t){if(t.code){var i=t.element,s=i.parentNode;if(s&&/pre/i.test(s.nodeName)&&!i.querySelector(".line-numbers-rows")&&Prism.util.isActive(i,e)){i.classList.remove(e),s.classList.add(e);var l,o=t.code.match(n),a=o?o.length+1:1,u=new Array(a+1).join("");(l=document.createElement("span")).setAttribute("aria-hidden","true"),l.className="line-numbers-rows",l.innerHTML=u,s.hasAttribute("data-start")&&(s.style.counterReset="linenumber "+(parseInt(s.getAttribute("data-start"),10)-1)),t.element.appendChild(l),r([s]),Prism.hooks.run("line-numbers",t)}}})),Prism.hooks.add("line-numbers",(function(e){e.plugins=e.plugins||{},e.plugins.lineNumbers=!0}))}function r(e){if(0!=(e=e.filter((function(e){var n,t=(n=e,n?window.getComputedStyle?getComputedStyle(n):n.currentStyle||null:null)["white-space"];return"pre-wrap"===t||"pre-line"===t}))).length){var t=e.map((function(e){var t=e.querySelector("code"),i=e.querySelector(".line-numbers-rows");if(t&&i){var r=e.querySelector(".line-numbers-sizer"),s=t.textContent.split(n);r||((r=document.createElement("span")).className="line-numbers-sizer",t.appendChild(r)),r.innerHTML="0",r.style.display="block";var l=r.getBoundingClientRect().height;return r.innerHTML="",{element:e,lines:s,lineHeights:[],oneLinerHeight:l,sizer:r}}})).filter(Boolean);t.forEach((function(e){var n=e.sizer,t=e.lines,i=e.lineHeights,r=e.oneLinerHeight;i[t.length-1]=void 0,t.forEach((function(e,t){if(e&&e.length>1){var s=n.appendChild(document.createElement("span"));s.style.display="block",s.textContent=e}else i[t]=r}))})),t.forEach((function(e){for(var n=e.sizer,t=e.lineHeights,i=0,r=0;r= 145) { $header.addClass('header-expand'); } }); $header.on('mouseleave', function () { $header.removeClass('header-expand'); }); /* * add prettyprint classes to our current active codeblock * run prettyPrint() to highlight the active code * scroll to the line when prettyprint is done * highlight the current line */ var renderCurrentCodeblock = function(id) { Prism.highlightAllUnder(document.querySelector('.frame-code-container .frame-code.active')); highlightCurrentLine(); } /* * Highlight the active and neighboring lines for the current frame * Adjust the offset to make sure that line is veritcally centered */ var highlightCurrentLine = function() { // We show more code than needed, purely for proper syntax highlighting // Let’s hide a big chunk of that code and then scroll the remaining block $activeFrame.find('.code-block').first().css({ maxHeight: 345, overflow: 'hidden', }); var line = $activeFrame.find('.code-block .line-highlight').first()[0]; // [internal] frames might not contain a code-block if (line) { line.scrollIntoView(); line.parentElement.scrollTop -= 180; } $container.scrollTop(0); } /* * click handler for loading codeblocks */ $frameContainer.on('click', '.frame', function() { var $this = $(this); var id = /frame\-line\-([\d]*)/.exec($this.attr('id'))[1]; var $codeFrame = $('#frame-code-' + id); if ($codeFrame) { $activeLine.removeClass('active'); $activeFrame.removeClass('active'); $this.addClass('active'); $codeFrame.addClass('active'); $activeLine = $this; $activeFrame = $codeFrame; renderCurrentCodeblock(id); } }); var clipboard = new ClipboardJS('.clipboard'); var showTooltip = function(elem, msg) { elem.classList.add('tooltipped', 'tooltipped-s'); elem.setAttribute('aria-label', msg); }; clipboard.on('success', function(e) { e.clearSelection(); showTooltip(e.trigger, 'Copied!'); }); clipboard.on('error', function(e) { showTooltip(e.trigger, fallbackMessage(e.action)); }); var btn = document.querySelector('.clipboard'); btn.addEventListener('mouseleave', function(e) { e.currentTarget.classList.remove('tooltipped', 'tooltipped-s'); e.currentTarget.removeAttribute('aria-label'); }); function fallbackMessage(action) { var actionMsg = ''; var actionKey = (action === 'cut' ? 'X' : 'C'); if (/Mac/i.test(navigator.userAgent)) { actionMsg = 'Press ⌘-' + actionKey + ' to ' + action; } else { actionMsg = 'Press Ctrl-' + actionKey + ' to ' + action; } return actionMsg; } function scrollIntoView($node, $parent) { var nodeOffset = $node.offset(); var nodeTop = nodeOffset.top; var nodeBottom = nodeTop + nodeOffset.height; var parentScrollTop = $parent.scrollTop(); var parentHeight = $parent.height(); if (nodeTop < 0) { $parent.scrollTop(parentScrollTop + nodeTop); } else if (nodeBottom > parentHeight) { $parent.scrollTop(parentScrollTop + nodeBottom - parentHeight); } } $(document).on('keydown', function(e) { var applicationFrames = $frameContainer.hasClass('frames-container-application'), frameClass = applicationFrames ? '.frame.frame-application' : '.frame'; if(e.ctrlKey || e.which === 74 || e.which === 75) { // CTRL+Arrow-UP/k and Arrow-Down/j support: // 1) select the next/prev element // 2) make sure the newly selected element is within the view-scope // 3) focus the (right) container, so arrow-up/down (without ctrl) scroll the details if (e.which === 38 /* arrow up */ || e.which === 75 /* k */) { $activeLine.prev(frameClass).click(); scrollIntoView($activeLine, $leftPanel); $container.focus(); e.preventDefault(); } else if (e.which === 40 /* arrow down */ || e.which === 74 /* j */) { $activeLine.next(frameClass).click(); scrollIntoView($activeLine, $leftPanel); $container.focus(); e.preventDefault(); } } else if (e.which == 78 /* n */) { if ($appFramesTab.length) { setActiveFramesTab($('.frames-tab:not(.frames-tab-active)')); } } }); // Avoid to quit the page with some protocol (e.g. IntelliJ Platform REST API) $ajaxEditors.on('click', function(e){ e.preventDefault(); $.get(this.href); }); // Symfony VarDumper: Close the by default expanded objects $('.sf-dump-expanded') .removeClass('sf-dump-expanded') .addClass('sf-dump-compact'); $('.sf-dump-toggle span').html('▶'); // Make the given frames-tab active function setActiveFramesTab($tab) { $tab.addClass('frames-tab-active'); if ($tab.attr('id') == 'application-frames-tab') { $frameContainer.addClass('frames-container-application'); $allFramesTab.removeClass('frames-tab-active'); } else { $frameContainer.removeClass('frames-container-application'); $appFramesTab.removeClass('frames-tab-active'); } } $('a.frames-tab').on('click', function(e) { e.preventDefault(); setActiveFramesTab($(this)); }); // Open editor from code block rows number $(document).delegate('.line-numbers-rows > span', 'click', function(e) { var linkTag = $(this).closest('.frame-code').find('.editor-link'); if (!linkTag) return; var editorUrl = linkTag.attr('href'); var requiresAjax = linkTag.data('ajax'); var lineOffset = $(this).closest('[data-line-offset]').data('line-offset'); var lineNumber = lineOffset + $(this).index(); var realLine = $(this).closest('[data-line]').data('line'); if (!realLine) return; var fileUrl = editorUrl.replace( new RegExp('([:=])' + realLine), '$1' + lineNumber ); if (requiresAjax) { $.get(fileUrl); } else { $('
').attr('href', fileUrl).trigger('click'); } }); // Render late enough for highlightCurrentLine to be ready renderCurrentCodeblock(); }); ================================================ FILE: src/Whoops/Resources/views/env_details.html.php ================================================

Environment & details:

$data): ?>
$value): ?>
Key Value
escape($k) ?> dump($value) ?>
empty
$h): ?>
. escape(get_class($h)) ?>
================================================ FILE: src/Whoops/Resources/views/frame_code.html.php ================================================
$frame): ?> getLine(); ?>
getFileLines($line - 20, 40); // getFileLines can return null if there is no source code if ($range): $range = array_map(function ($line) { return empty($line) ? ' ' : $line;}, $range); $start = key($range) + 1; $code = join("\n", $range); ?>
escape($code) ?>
dumpArgs($frame); ?>
Arguments
getComments(); ?>
$comment): ?>
escape($context) ?> escapeButPreserveUris($comment) ?>
================================================ FILE: src/Whoops/Resources/views/frame_list.html.php ================================================ $frame): ?>
breakOnDelimiter('\\', $tpl->escape($frame->getClass() ?: '')) ?> breakOnDelimiter('\\', $tpl->escape($frame->getFunction() ?: '')) ?>
getFile() ? $tpl->breakOnDelimiter('/', $tpl->shorten($tpl->escape($frame->getFile()))) : '<#unknown>' ?>:getLine() ?>
"> render($frame_list) ?> ================================================ FILE: src/Whoops/Resources/views/frames_description.html.php ================================================ ================================================ FILE: src/Whoops/Resources/views/header.html.php ================================================
$nameSection): ?> escape($nameSection) ?> escape($nameSection) . ' \\' ?> (escape($code) ?>)
escape($message) ?>
Previous exceptions
    $previousMessage): ?>
  • escape($previousMessage) ?> ()
No message escape($plain_exception) ?>
================================================ FILE: src/Whoops/Resources/views/header_outer.html.php ================================================
render($header) ?>
================================================ FILE: src/Whoops/Resources/views/layout.html.php ================================================ <?php echo $tpl->escape($page_title) ?>
render($panel_left_outer) ?> render($panel_details_outer) ?>
================================================ FILE: src/Whoops/Resources/views/panel_details.html.php ================================================ render($frame_code) ?> render($env_details) ?> ================================================ FILE: src/Whoops/Resources/views/panel_details_outer.html.php ================================================
render($panel_details) ?>
================================================ FILE: src/Whoops/Resources/views/panel_left.html.php ================================================ render($header_outer); $tpl->render($frames_description); $tpl->render($frames_container); ================================================ FILE: src/Whoops/Resources/views/panel_left_outer.html.php ================================================
render($panel_left) ?>
================================================ FILE: src/Whoops/Run.php ================================================ */ namespace Whoops; use InvalidArgumentException; use Throwable; use Whoops\Exception\ErrorException; use Whoops\Handler\CallbackHandler; use Whoops\Handler\Handler; use Whoops\Handler\HandlerInterface; use Whoops\Inspector\CallableInspectorFactory; use Whoops\Inspector\InspectorFactory; use Whoops\Inspector\InspectorFactoryInterface; use Whoops\Inspector\InspectorInterface; use Whoops\Util\Misc; use Whoops\Util\SystemFacade; final class Run implements RunInterface { /** * @var bool */ private $isRegistered; /** * @var bool */ private $allowQuit = true; /** * @var bool */ private $sendOutput = true; /** * @var integer|false */ private $sendHttpCode = 500; /** * @var integer|false */ private $sendExitCode = 1; /** * @var HandlerInterface[] */ private $handlerStack = []; /** * @var array * @psalm-var list */ private $silencedPatterns = []; /** * @var SystemFacade */ private $system; /** * In certain scenarios, like in shutdown handler, we can not throw exceptions. * * @var bool */ private $canThrowExceptions = true; /** * The inspector factory to create inspectors. * * @var InspectorFactoryInterface */ private $inspectorFactory; /** * @var array */ private $frameFilters = []; public function __construct(?SystemFacade $system = null) { $this->system = $system ?: new SystemFacade; $this->inspectorFactory = new InspectorFactory(); } public function __destruct() { $this->unregister(); } /** * Explicitly request your handler runs as the last of all currently registered handlers. * * @param callable|HandlerInterface $handler * * @return Run */ public function appendHandler($handler) { array_unshift($this->handlerStack, $this->resolveHandler($handler)); return $this; } /** * Explicitly request your handler runs as the first of all currently registered handlers. * * @param callable|HandlerInterface $handler * * @return Run */ public function prependHandler($handler) { return $this->pushHandler($handler); } /** * Register your handler as the last of all currently registered handlers (to be executed first). * Prefer using appendHandler and prependHandler for clarity. * * @param callable|HandlerInterface $handler * * @return Run * * @throws InvalidArgumentException If argument is not callable or instance of HandlerInterface. */ public function pushHandler($handler) { $this->handlerStack[] = $this->resolveHandler($handler); return $this; } /** * Removes and returns the last handler pushed to the handler stack. * * @see Run::removeFirstHandler(), Run::removeLastHandler() * * @return HandlerInterface|null */ public function popHandler() { return array_pop($this->handlerStack); } /** * Removes the first handler. * * @return void */ public function removeFirstHandler() { array_pop($this->handlerStack); } /** * Removes the last handler. * * @return void */ public function removeLastHandler() { array_shift($this->handlerStack); } /** * Returns an array with all handlers, in the order they were added to the stack. * * @return array */ public function getHandlers() { return $this->handlerStack; } /** * Clears all handlers in the handlerStack, including the default PrettyPage handler. * * @return Run */ public function clearHandlers() { $this->handlerStack = []; return $this; } public function getFrameFilters() { return $this->frameFilters; } public function clearFrameFilters() { $this->frameFilters = []; return $this; } /** * Registers this instance as an error handler. * * @return Run */ public function register() { if (!$this->isRegistered) { // Workaround PHP bug 42098 // https://bugs.php.net/bug.php?id=42098 class_exists("\\Whoops\\Exception\\ErrorException"); class_exists("\\Whoops\\Exception\\FrameCollection"); class_exists("\\Whoops\\Exception\\Frame"); class_exists("\\Whoops\\Exception\\Inspector"); class_exists("\\Whoops\\Inspector\\InspectorFactory"); $this->system->setErrorHandler([$this, self::ERROR_HANDLER]); $this->system->setExceptionHandler([$this, self::EXCEPTION_HANDLER]); $this->system->registerShutdownFunction([$this, self::SHUTDOWN_HANDLER]); $this->isRegistered = true; } return $this; } /** * Unregisters all handlers registered by this Whoops\Run instance. * * @return Run */ public function unregister() { if ($this->isRegistered) { $this->system->restoreExceptionHandler(); $this->system->restoreErrorHandler(); $this->isRegistered = false; } return $this; } /** * Should Whoops allow Handlers to force the script to quit? * * @param bool|int $exit * * @return bool */ public function allowQuit($exit = null) { if (func_num_args() == 0) { return $this->allowQuit; } return $this->allowQuit = (bool) $exit; } /** * Silence particular errors in particular files. * * @param array|string $patterns List or a single regex pattern to match. * @param int $levels Defaults to E_STRICT | E_DEPRECATED. * * @return Run */ public function silenceErrorsInPaths($patterns, $levels = 10240) { $this->silencedPatterns = array_merge( $this->silencedPatterns, array_map( function ($pattern) use ($levels) { return [ "pattern" => $pattern, "levels" => $levels, ]; }, (array) $patterns ) ); return $this; } /** * Returns an array with silent errors in path configuration. * * @return array */ public function getSilenceErrorsInPaths() { return $this->silencedPatterns; } /** * Should Whoops send HTTP error code to the browser if possible? * Whoops will by default send HTTP code 500, but you may wish to * use 502, 503, or another 5xx family code. * * @param bool|int $code * * @return int|false * * @throws InvalidArgumentException */ public function sendHttpCode($code = null) { if (func_num_args() == 0) { return $this->sendHttpCode; } if (!$code) { return $this->sendHttpCode = false; } if ($code === true) { $code = 500; } if ($code < 400 || 600 <= $code) { throw new InvalidArgumentException( "Invalid status code '$code', must be 4xx or 5xx" ); } return $this->sendHttpCode = $code; } /** * Should Whoops exit with a specific code on the CLI if possible? * Whoops will exit with 1 by default, but you can specify something else. * * @param int $code * * @return int * * @throws InvalidArgumentException */ public function sendExitCode($code = null) { if (func_num_args() == 0) { return $this->sendExitCode; } if ($code < 0 || 255 <= $code) { throw new InvalidArgumentException( "Invalid status code '$code', must be between 0 and 254" ); } return $this->sendExitCode = (int) $code; } /** * Should Whoops push output directly to the client? * If this is false, output will be returned by handleException. * * @param bool|int $send * * @return bool */ public function writeToOutput($send = null) { if (func_num_args() == 0) { return $this->sendOutput; } return $this->sendOutput = (bool) $send; } /** * Handles an exception, ultimately generating a Whoops error page. * * @param Throwable $exception * * @return string Output generated by handlers. */ public function handleException($exception) { // Walk the registered handlers in the reverse order // they were registered, and pass off the exception $inspector = $this->getInspector($exception); // Capture output produced while handling the exception, // we might want to send it straight away to the client, // or return it silently. $this->system->startOutputBuffering(); // Just in case there are no handlers: $handlerResponse = null; $handlerContentType = null; try { foreach (array_reverse($this->handlerStack) as $handler) { $handler->setRun($this); $handler->setInspector($inspector); $handler->setException($exception); // The HandlerInterface does not require an Exception passed to handle() // and neither of our bundled handlers use it. // However, 3rd party handlers may have already relied on this parameter, // and removing it would be possibly breaking for users. $handlerResponse = $handler->handle($exception); // Collect the content type for possible sending in the headers. $handlerContentType = method_exists($handler, 'contentType') ? $handler->contentType() : null; if (in_array($handlerResponse, [Handler::LAST_HANDLER, Handler::QUIT])) { // The Handler has handled the exception in some way, and // wishes to quit execution (Handler::QUIT), or skip any // other handlers (Handler::LAST_HANDLER). If $this->allowQuit // is false, Handler::QUIT behaves like Handler::LAST_HANDLER break; } } $willQuit = $handlerResponse == Handler::QUIT && $this->allowQuit(); } finally { $output = $this->system->cleanOutputBuffer(); } // If we're allowed to, send output generated by handlers directly // to the output, otherwise, and if the script doesn't quit, return // it so that it may be used by the caller if ($this->writeToOutput()) { // @todo Might be able to clean this up a bit better if ($willQuit) { // Cleanup all other output buffers before sending our output: while ($this->system->getOutputBufferLevel() > 0) { $this->system->endOutputBuffering(); } // Send any headers if needed: if (Misc::canSendHeaders() && $handlerContentType) { header("Content-Type: {$handlerContentType}"); } } $this->writeToOutputNow($output); } if ($willQuit) { // HHVM fix for https://github.com/facebook/hhvm/issues/4055 $this->system->flushOutputBuffer(); $this->system->stopExecution( $this->sendExitCode() ); } return $output; } /** * Converts generic PHP errors to \ErrorException instances, before passing them off to be handled. * * This method MUST be compatible with set_error_handler. * * @param int $level * @param string $message * @param string|null $file * @param int|null $line * * @return bool * * @throws ErrorException */ public function handleError($level, $message, $file = null, $line = null) { if ($level & $this->system->getErrorReportingLevel()) { foreach ($this->silencedPatterns as $entry) { $pathMatches = (bool) preg_match($entry["pattern"], $file); $levelMatches = $level & $entry["levels"]; if ($pathMatches && $levelMatches) { // Ignore the error, abort handling // See https://github.com/filp/whoops/issues/418 return true; } } // XXX we pass $level for the "code" param only for BC reasons. // see https://github.com/filp/whoops/issues/267 $exception = new ErrorException($message, /*code*/ $level, /*severity*/ $level, $file, $line); if ($this->canThrowExceptions) { throw $exception; } else { $this->handleException($exception); } // Do not propagate errors which were already handled by Whoops. return true; } // Propagate error to the next handler, allows error_get_last() to // work on silenced errors. return false; } /** * Special case to deal with Fatal errors and the like. * * @return void */ public function handleShutdown() { // If we reached this step, we are in shutdown handler. // An exception thrown in a shutdown handler will not be propagated // to the exception handler. Pass that information along. $this->canThrowExceptions = false; // If we are not currently registered, we should not do anything if (!$this->isRegistered) { return; } $error = $this->system->getLastError(); if ($error && Misc::isLevelFatal($error['type'])) { // If there was a fatal error, // it was not handled in handleError yet. $this->allowQuit = false; $this->handleError( $error['type'], $error['message'], $error['file'], $error['line'] ); } } /** * @param InspectorFactoryInterface $factory * * @return void */ public function setInspectorFactory(InspectorFactoryInterface $factory) { $this->inspectorFactory = $factory; } public function addFrameFilter($filterCallback) { if (!is_callable($filterCallback)) { throw new \InvalidArgumentException(sprintf( "A frame filter must be of type callable, %s type given.", gettype($filterCallback) )); } $this->frameFilters[] = $filterCallback; return $this; } /** * @param Throwable $exception * * @return InspectorInterface */ private function getInspector($exception) { return $this->inspectorFactory->create($exception); } /** * Resolves the giving handler. * * @param callable|HandlerInterface $handler * * @return HandlerInterface * * @throws InvalidArgumentException */ private function resolveHandler($handler) { if (is_callable($handler)) { $handler = new CallbackHandler($handler); } if (!$handler instanceof HandlerInterface) { throw new InvalidArgumentException( "Handler must be a callable, or instance of " . "Whoops\\Handler\\HandlerInterface" ); } return $handler; } /** * Echo something to the browser. * * @param string $output * * @return Run */ private function writeToOutputNow($output) { if ($this->sendHttpCode() && Misc::canSendHeaders()) { $this->system->setHttpResponseCode( $this->sendHttpCode() ); } echo $output; return $this; } } ================================================ FILE: src/Whoops/RunInterface.php ================================================ */ namespace Whoops; use InvalidArgumentException; use Whoops\Exception\ErrorException; use Whoops\Handler\HandlerInterface; interface RunInterface { const EXCEPTION_HANDLER = "handleException"; const ERROR_HANDLER = "handleError"; const SHUTDOWN_HANDLER = "handleShutdown"; /** * Pushes a handler to the end of the stack * * @throws InvalidArgumentException If argument is not callable or instance of HandlerInterface * @param Callable|HandlerInterface $handler * @return Run */ public function pushHandler($handler); /** * Removes the last handler in the stack and returns it. * Returns null if there"s nothing else to pop. * * @return null|HandlerInterface */ public function popHandler(); /** * Returns an array with all handlers, in the * order they were added to the stack. * * @return array */ public function getHandlers(); /** * Clears all handlers in the handlerStack, including * the default PrettyPage handler. * * @return Run */ public function clearHandlers(); /** * @return array */ public function getFrameFilters(); /** * @return Run */ public function clearFrameFilters(); /** * Registers this instance as an error handler. * * @return Run */ public function register(); /** * Unregisters all handlers registered by this Whoops\Run instance * * @return Run */ public function unregister(); /** * Should Whoops allow Handlers to force the script to quit? * * @param bool|int $exit * @return bool */ public function allowQuit($exit = null); /** * Silence particular errors in particular files * * @param array|string $patterns List or a single regex pattern to match * @param int $levels Defaults to E_STRICT | E_DEPRECATED * @return \Whoops\Run */ public function silenceErrorsInPaths($patterns, $levels = 10240); /** * Should Whoops send HTTP error code to the browser if possible? * Whoops will by default send HTTP code 500, but you may wish to * use 502, 503, or another 5xx family code. * * @param bool|int $code * @return int|false */ public function sendHttpCode($code = null); /** * Should Whoops exit with a specific code on the CLI if possible? * Whoops will exit with 1 by default, but you can specify something else. * * @param int $code * @return int */ public function sendExitCode($code = null); /** * Should Whoops push output directly to the client? * If this is false, output will be returned by handleException * * @param bool|int $send * @return bool */ public function writeToOutput($send = null); /** * Handles an exception, ultimately generating a Whoops error * page. * * @param \Throwable $exception * @return string Output generated by handlers */ public function handleException($exception); /** * Converts generic PHP errors to \ErrorException * instances, before passing them off to be handled. * * This method MUST be compatible with set_error_handler. * * @param int $level * @param string $message * @param string $file * @param int $line * * @return bool * @throws ErrorException */ public function handleError($level, $message, $file = null, $line = null); /** * Special case to deal with Fatal errors and the like. */ public function handleShutdown(); /** * Registers a filter callback in the frame filters stack. * * @param callable $filterCallback * @return \Whoops\Run */ public function addFrameFilter($filterCallback); } ================================================ FILE: src/Whoops/Util/HtmlDumperOutput.php ================================================ */ namespace Whoops\Util; /** * Used as output callable for Symfony\Component\VarDumper\Dumper\HtmlDumper::dump() * * @see TemplateHelper::dump() */ class HtmlDumperOutput { private $output; public function __invoke($line, $depth) { // A negative depth means "end of dump" if ($depth >= 0) { // Adds a two spaces indentation to the line $this->output .= str_repeat(' ', $depth) . $line . "\n"; } } public function getOutput() { return $this->output; } public function clear() { $this->output = null; } } ================================================ FILE: src/Whoops/Util/Misc.php ================================================ */ namespace Whoops\Util; class Misc { /** * Can we at this point in time send HTTP headers? * * Currently this checks if we are even serving an HTTP request, * as opposed to running from a command line. * * If we are serving an HTTP request, we check if it's not too late. * * @return bool */ public static function canSendHeaders() { return isset($_SERVER["REQUEST_URI"]) && !headers_sent(); } public static function isAjaxRequest() { return ( !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'); } /** * Check, if possible, that this execution was triggered by a command line. * @return bool */ public static function isCommandLine() { return PHP_SAPI == 'cli'; } /** * Translate ErrorException code into the represented constant. * * @param int $error_code * @return string */ public static function translateErrorCode($error_code) { $constants = get_defined_constants(true); if (array_key_exists('Core', $constants)) { foreach ($constants['Core'] as $constant => $value) { if (substr($constant, 0, 2) == 'E_' && $value == $error_code) { return $constant; } } } return "E_UNKNOWN"; } /** * Determine if an error level is fatal (halts execution) * * @param int $level * @return bool */ public static function isLevelFatal($level) { $errors = E_ERROR; $errors |= E_PARSE; $errors |= E_CORE_ERROR; $errors |= E_CORE_WARNING; $errors |= E_COMPILE_ERROR; $errors |= E_COMPILE_WARNING; return ($level & $errors) > 0; } } ================================================ FILE: src/Whoops/Util/SystemFacade.php ================================================ */ namespace Whoops\Util; class SystemFacade { /** * Turns on output buffering. * * @return bool */ public function startOutputBuffering() { return ob_start(); } /** * @param callable $handler * @param int $types * * @return callable|null */ public function setErrorHandler(callable $handler, $types = 'use-php-defaults') { // Since PHP 5.4 the constant E_ALL contains all errors (even E_STRICT) if ($types === 'use-php-defaults') { $types = E_ALL; } return set_error_handler($handler, $types); } /** * @param callable $handler * * @return callable|null */ public function setExceptionHandler(callable $handler) { return set_exception_handler($handler); } /** * @return void */ public function restoreExceptionHandler() { restore_exception_handler(); } /** * @return void */ public function restoreErrorHandler() { restore_error_handler(); } /** * @param callable $function * * @return void */ public function registerShutdownFunction(callable $function) { register_shutdown_function($function); } /** * @return string|false */ public function cleanOutputBuffer() { return ob_get_clean(); } /** * @return int */ public function getOutputBufferLevel() { return ob_get_level(); } /** * @return bool */ public function endOutputBuffering() { return ob_end_clean(); } /** * @return void */ public function flushOutputBuffer() { flush(); } /** * @return int */ public function getErrorReportingLevel() { return error_reporting(); } /** * @return array|null */ public function getLastError() { return error_get_last(); } /** * @param int $httpCode * * @return int */ public function setHttpResponseCode($httpCode) { if (!headers_sent()) { // Ensure that no 'location' header is present as otherwise this // will override the HTTP code being set here, and mask the // expected error page. header_remove('location'); } return http_response_code($httpCode); } /** * @param int $exitStatus */ public function stopExecution($exitStatus) { exit($exitStatus); } } ================================================ FILE: src/Whoops/Util/TemplateHelper.php ================================================ */ namespace Whoops\Util; use Symfony\Component\VarDumper\Caster\Caster; use Symfony\Component\VarDumper\Cloner\AbstractCloner; use Symfony\Component\VarDumper\Cloner\VarCloner; use Symfony\Component\VarDumper\Dumper\HtmlDumper; use Whoops\Exception\Frame; /** * Exposes useful tools for working with/in templates */ class TemplateHelper { /** * An array of variables to be passed to all templates * @var array */ private $variables = []; /** * @var HtmlDumper */ private $htmlDumper; /** * @var HtmlDumperOutput */ private $htmlDumperOutput; /** * @var AbstractCloner */ private $cloner; /** * @var string */ private $applicationRootPath; public function __construct() { // root path for ordinary composer projects $this->applicationRootPath = dirname(dirname(dirname(dirname(dirname(dirname(__DIR__)))))); } /** * Escapes a string for output in an HTML document * * @param string $raw * @return string */ public function escape($raw) { $flags = ENT_QUOTES; // HHVM has all constants defined, but only ENT_IGNORE // works at the moment if (defined("ENT_SUBSTITUTE") && !defined("HHVM_VERSION")) { $flags |= ENT_SUBSTITUTE; } else { // This is for 5.3. // The documentation warns of a potential security issue, // but it seems it does not apply in our case, because // we do not blacklist anything anywhere. $flags |= ENT_IGNORE; } $raw = str_replace(chr(9), ' ', $raw); return htmlspecialchars($raw, $flags, "UTF-8"); } /** * Escapes a string for output in an HTML document, but preserves * URIs within it, and converts them to clickable anchor elements. * * @param string $raw * @return string */ public function escapeButPreserveUris($raw) { $escaped = $this->escape($raw); return preg_replace( "@([A-z]+?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@", "$1", $escaped ); } /** * Makes sure that the given string breaks on the delimiter. * * @param string $delimiter * @param string $s * @return string */ public function breakOnDelimiter($delimiter, $s) { $parts = explode($delimiter, $s); foreach ($parts as &$part) { $part = '' . $part . ''; } return implode($delimiter, $parts); } /** * Replace the part of the path that all files have in common. * * @param string $path * @return string */ public function shorten($path) { if ($this->applicationRootPath != "/") { $path = str_replace($this->applicationRootPath, '…', $path); } return $path; } private function getDumper() { if (!$this->htmlDumper && class_exists('Symfony\Component\VarDumper\Cloner\VarCloner')) { $this->htmlDumperOutput = new HtmlDumperOutput(); // re-use the same var-dumper instance, so it won't re-render the global styles/scripts on each dump. $this->htmlDumper = new HtmlDumper($this->htmlDumperOutput); $styles = [ 'default' => 'color:#FFFFFF; line-height:normal; font:12px "Inconsolata", "Fira Mono", "Source Code Pro", Monaco, Consolas, "Lucida Console", monospace !important; word-wrap: break-word; white-space: pre-wrap; position:relative; z-index:99999; word-break: normal', 'num' => 'color:#BCD42A', 'const' => 'color: #4bb1b1;', 'str' => 'color:#BCD42A', 'note' => 'color:#ef7c61', 'ref' => 'color:#A0A0A0', 'public' => 'color:#FFFFFF', 'protected' => 'color:#FFFFFF', 'private' => 'color:#FFFFFF', 'meta' => 'color:#FFFFFF', 'key' => 'color:#BCD42A', 'index' => 'color:#ef7c61', ]; $this->htmlDumper->setStyles($styles); } return $this->htmlDumper; } /** * Format the given value into a human readable string. * * @param mixed $value * @return string */ public function dump($value) { $dumper = $this->getDumper(); if ($dumper) { // re-use the same DumpOutput instance, so it won't re-render the global styles/scripts on each dump. // exclude verbose information (e.g. exception stack traces) if (class_exists('Symfony\Component\VarDumper\Caster\Caster')) { $cloneVar = $this->getCloner()->cloneVar($value, Caster::EXCLUDE_VERBOSE); // Symfony VarDumper 2.6 Caster class dont exist. } else { $cloneVar = $this->getCloner()->cloneVar($value); } $dumper->dump( $cloneVar, $this->htmlDumperOutput ); $output = $this->htmlDumperOutput->getOutput(); $this->htmlDumperOutput->clear(); return $output; } return htmlspecialchars(print_r($value, true)); } /** * Format the args of the given Frame as a human readable html string * * @param Frame $frame * @return string the rendered html */ public function dumpArgs(Frame $frame) { // we support frame args only when the optional dumper is available if (!$this->getDumper()) { return ''; } $html = ''; $numFrames = count($frame->getArgs()); if ($numFrames > 0) { $html = '
    '; foreach ($frame->getArgs() as $j => $frameArg) { $html .= '
  1. '. $this->dump($frameArg) .'
  2. '; } $html .= '
'; } return $html; } /** * Convert a string to a slug version of itself * * @param string $original * @return string */ public function slug($original) { $slug = str_replace(" ", "-", $original); $slug = preg_replace('/[^\w\d\-\_]/i', '', $slug); return strtolower($slug); } /** * Given a template path, render it within its own scope. This * method also accepts an array of additional variables to be * passed to the template. * * @param string $template */ public function render($template, ?array $additionalVariables = null) { $variables = $this->getVariables(); // Pass the helper to the template: $variables["tpl"] = $this; if ($additionalVariables !== null) { $variables = array_replace($variables, $additionalVariables); } call_user_func(function () { extract(func_get_arg(1)); require func_get_arg(0); }, $template, $variables); } /** * Sets the variables to be passed to all templates rendered * by this template helper. */ public function setVariables(array $variables) { $this->variables = $variables; } /** * Sets a single template variable, by its name: * * @param string $variableName * @param mixed $variableValue */ public function setVariable($variableName, $variableValue) { $this->variables[$variableName] = $variableValue; } /** * Gets a single template variable, by its name, or * $defaultValue if the variable does not exist * * @param string $variableName * @param mixed $defaultValue * @return mixed */ public function getVariable($variableName, $defaultValue = null) { return isset($this->variables[$variableName]) ? $this->variables[$variableName] : $defaultValue; } /** * Unsets a single template variable, by its name * * @param string $variableName */ public function delVariable($variableName) { unset($this->variables[$variableName]); } /** * Returns all variables for this helper * * @return array */ public function getVariables() { return $this->variables; } /** * Set the cloner used for dumping variables. * * @param AbstractCloner $cloner */ public function setCloner($cloner) { $this->cloner = $cloner; } /** * Get the cloner used for dumping variables. * * @return AbstractCloner */ public function getCloner() { if (!$this->cloner) { $this->cloner = new VarCloner(); } return $this->cloner; } /** * Set the application root path. * * @param string $applicationRootPath */ public function setApplicationRootPath($applicationRootPath) { $this->applicationRootPath = $applicationRootPath; } /** * Return the application root path. * * @return string */ public function getApplicationRootPath() { return $this->applicationRootPath; } } ================================================ FILE: tests/Whoops/Exception/FormatterTest.php ================================================ */ namespace Whoops\Exception; use Whoops\TestCase; class FormatterTest extends TestCase { public function testPlain() { $msg = 'Sample exception message foo'; $output = Formatter::formatExceptionPlain(new Inspector(new \Exception($msg))); $this->assertStringContains($msg, $output); $this->assertStringContains('Stacktrace', $output); } } ================================================ FILE: tests/Whoops/Exception/FrameCollectionTest.php ================================================ */ namespace Whoops\Exception; use Whoops\TestCase; class FrameCollectionTest extends TestCase { /** * Stupid little counter for tagging frames * with a unique but predictable id * @var int */ private $frameIdCounter = 0; /** * @return array */ public function getFrameData() { $id = ++$this->frameIdCounter; return [ 'file' => __DIR__ . '/../../fixtures/frame.lines-test.php', 'line' => $id, 'function' => 'test-' . $id, 'class' => 'MyClass', 'args' => [true, 'hello'], ]; } /** * @param int $total * @return array */ public function getFrameDataList($total) { $total = max((int) $total, 1); $self = $this; $frames = array_map(function () use ($self) { return $self->getFrameData(); }, range(1, $total)); return $frames; } /** * @param array $frames * @return \Whoops\Exception\FrameCollection */ private function getFrameCollectionInstance($frames = null) { if ($frames === null) { $frames = $this->getFrameDataList(10); } return new FrameCollection($frames); } /** * @covers Whoops\Exception\FrameCollection::offsetExists */ public function testArrayAccessExists() { $collection = $this->getFrameCollectionInstance(); $this->assertArrayHasKey(0, $collection); } /** * @covers Whoops\Exception\FrameCollection::offsetGet */ public function testArrayAccessGet() { $collection = $this->getFrameCollectionInstance(); $this->assertInstanceOf('Whoops\\Exception\\Frame', $collection[0]); } /** * @covers Whoops\Exception\FrameCollection::offsetSet */ public function testArrayAccessSet() { $collection = $this->getFrameCollectionInstance(); $this->expectExceptionOfType('Exception'); $collection[0] = 'foo'; } /** * @covers Whoops\Exception\FrameCollection::offsetUnset */ public function testArrayAccessUnset() { $collection = $this->getFrameCollectionInstance(); $this->expectExceptionOfType('Exception'); unset($collection[0]); } /** * @covers Whoops\Exception\FrameCollection::filter * @covers Whoops\Exception\FrameCollection::count */ public function testFilterFrames() { $frames = $this->getFrameCollectionInstance(); // Filter out all frames with a line number under 6 $frames->filter(function ($frame) { return $frame->getLine() <= 5; }); $this->assertCount(5, $frames); } /** * @covers Whoops\Exception\FrameCollection::map */ public function testMapFrames() { $frames = $this->getFrameCollectionInstance(); // Filter out all frames with a line number under 6 $frames->map(function ($frame) { $frame->addComment("This is cool", "test"); return $frame; }); $this->assertCount(10, $frames); } /** * @covers Whoops\Exception\FrameCollection::map */ public function testMapFramesEnforceType() { $frames = $this->getFrameCollectionInstance(); $this->expectExceptionOfType('UnexpectedValueException'); // Filter out all frames with a line number under 6 $frames->map(function ($frame) { return "bajango"; }); } /** * @covers Whoops\Exception\FrameCollection::getArray */ public function testGetArray() { $frames = $this->getFrameCollectionInstance(); $frames = $frames->getArray(); $this->assertCount(10, $frames); foreach ($frames as $frame) { $this->assertInstanceOf('Whoops\\Exception\\Frame', $frame); } } /** * @covers Whoops\Exception\FrameCollection::getArray */ public function testGetArrayImmutable() { $frames = $this->getFrameCollectionInstance(); $arr = $frames->getArray(); $arr[0] = 'foobar'; $newCopy = $frames->getArray(); $this->assertNotSame($arr[0], $newCopy); } /** * @covers Whoops\Exception\FrameCollection::getIterator */ public function testCollectionIsIterable() { $frames = $this->getFrameCollectionInstance(); foreach ($frames as $frame) { $this->assertInstanceOf('Whoops\\Exception\\Frame', $frame); } } /** * @covers Whoops\Exception\FrameCollection::serialize * @covers Whoops\Exception\FrameCollection::unserialize */ public function testCollectionIsSerializable() { $frames = $this->getFrameCollectionInstance(); $serializedFrames = serialize($frames); $newFrames = unserialize($serializedFrames); foreach ($newFrames as $frame) { $this->assertInstanceOf('Whoops\\Exception\\Frame', $frame); } } /** * @covers Whoops\Exception\FrameCollection::topDiff */ public function testTopDiff() { $commonFrameTail = $this->getFrameDataList(3); $diffFrame = ['line' => $this->frameIdCounter] + $this->getFrameData(); $frameCollection1 = new FrameCollection(array_merge([ $diffFrame, ], $commonFrameTail)); $frameCollection2 = new FrameCollection(array_merge([ $this->getFrameData(), ], $commonFrameTail)); $diff = $frameCollection1->topDiff($frameCollection2); $this->assertCount(1, $diff); } } ================================================ FILE: tests/Whoops/Exception/FrameTest.php ================================================ */ namespace Whoops\Exception; use Whoops\TestCase; class FrameTest extends TestCase { /** * @return array */ private function getFrameData() { return [ 'file' => __DIR__ . '/../../fixtures/frame.lines-test.php', 'line' => 0, 'function' => 'test', 'class' => 'MyClass', 'args' => [true, 'hello'], ]; } /** * @param array $data * @return Frame */ private function getFrameInstance($data = null) { if ($data === null) { $data = $this->getFrameData(); } return new Frame($data); } /** * @covers Whoops\Exception\Frame::getFile */ public function testGetFile() { $data = $this->getFrameData(); $frame = $this->getFrameInstance($data); $this->assertEquals($frame->getFile(), $data['file']); } /** * @covers Whoops\Exception\Frame::getLine */ public function testGetLine() { $data = $this->getFrameData(); $frame = $this->getFrameInstance($data); $this->assertEquals($frame->getLine(), $data['line']); } /** * @covers Whoops\Exception\Frame::getClass */ public function testGetClass() { $data = $this->getFrameData(); $frame = $this->getFrameInstance($data); $this->assertEquals($frame->getClass(), $data['class']); } /** * @covers Whoops\Exception\Frame::getFunction */ public function testGetFunction() { $data = $this->getFrameData(); $frame = $this->getFrameInstance($data); $this->assertEquals($frame->getFunction(), $data['function']); } /** * @covers Whoops\Exception\Frame::getArgs */ public function testGetArgs() { $data = $this->getFrameData(); $frame = $this->getFrameInstance($data); $this->assertEquals($frame->getArgs(), $data['args']); } /** * @covers Whoops\Exception\Frame::getFileContents */ public function testGetFileContents() { $data = $this->getFrameData(); $frame = $this->getFrameInstance($data); $this->assertStringEqualsFile($data['file'], $frame->getFileContents()); } /** * @covers Whoops\Exception\Frame::getFileContents * @testWith ["[internal]"] * ["Unknown"] * @see https://github.com/filp/whoops/pull/599 */ public function testGetFileContentsWhenFrameIsNotRelatedToSpecificFile($fakeFilename) { $data = array_merge($this->getFrameData(), ['file' => $fakeFilename]); $frame = $this->getFrameInstance($data); $this->assertNull($frame->getFileContents()); } /** * @covers Whoops\Exception\Frame::getFileLines */ public function testGetFileLines() { $data = $this->getFrameData(); $frame = $this->getFrameInstance($data); $lines = explode("\n", $frame->getFileContents()); $this->assertEquals($frame->getFileLines(), $lines); } /** * @covers Whoops\Exception\Frame::getFileLines */ public function testGetFileLinesRange() { $data = $this->getFrameData(); $frame = $this->getFrameInstance($data); $lines = $frame->getFileLines(0, 3); $this->assertEquals($lines[0], 'assertEquals($lines[1], '// Line 2'); $this->assertEquals($lines[2], '// Line 3'); } /** * @covers Whoops\Exception\Frame::addComment * @covers Whoops\Exception\Frame::getComments */ public function testGetComments() { $frame = $this->getFrameInstance(); $testComments = [ 'Dang, yo!', 'Errthangs broken!', 'Dayumm!', ]; $frame->addComment($testComments[0]); $frame->addComment($testComments[1]); $frame->addComment($testComments[2]); $comments = $frame->getComments(); $this->assertCount(3, $comments); $this->assertEquals($comments[0]['comment'], $testComments[0]); $this->assertEquals($comments[1]['comment'], $testComments[1]); $this->assertEquals($comments[2]['comment'], $testComments[2]); } /** * @covers Whoops\Exception\Frame::addComment * @covers Whoops\Exception\Frame::getComments */ public function testGetFilteredComments() { $frame = $this->getFrameInstance(); $testComments = [ ['Dang, yo!', 'test'], ['Errthangs broken!', 'test'], 'Dayumm!', ]; $frame->addComment($testComments[0][0], $testComments[0][1]); $frame->addComment($testComments[1][0], $testComments[1][1]); $frame->addComment($testComments[2][0], $testComments[2][1]); $comments = $frame->getComments('test'); $this->assertCount(2, $comments); $this->assertEquals($comments[0]['comment'], $testComments[0][0]); $this->assertEquals($comments[1]['comment'], $testComments[1][0]); } /** * @covers Whoops\Exception\Frame::serialize * @covers Whoops\Exception\Frame::unserialize */ public function testFrameIsSerializable() { $data = $this->getFrameData(); $frame = $this->getFrameInstance(); $commentText = "Gee I hope this works"; $commentContext = "test"; $frame->addComment($commentText, $commentContext); $serializedFrame = serialize($frame); $newFrame = unserialize($serializedFrame); $this->assertInstanceOf('Whoops\\Exception\\Frame', $newFrame); $this->assertEquals($newFrame->getFile(), $data['file']); $this->assertEquals($newFrame->getLine(), $data['line']); $comments = $newFrame->getComments(); $this->assertCount(1, $comments); $this->assertEquals($comments[0]["comment"], $commentText); $this->assertEquals($comments[0]["context"], $commentContext); } /** * @covers Whoops\Exception\Frame::equals */ public function testEquals() { $frame1 = $this->getFrameInstance(['line' => 1, 'file' => 'test-file.php']); $frame2 = $this->getFrameInstance(['line' => 1, 'file' => 'test-file.php']); $this->assertTrue ($frame1->equals($frame2)); } } ================================================ FILE: tests/Whoops/Exception/InspectorTest.php ================================================ */ namespace Whoops\Exception; use Exception; use Whoops\TestCase; class InspectorTest extends TestCase { /** * @param string $message * @param int $code * @param Exception $previous * @return Exception */ protected function getException($message = "", $code = 0, $previous = null) { return new Exception($message, $code, $previous); } /** * @param Exception $exception|null * @return \Whoops\Exception\Inspector */ protected function getInspectorInstance($exception = null) { return new Inspector($exception); } /** * @covers Whoops\Exception\Inspector::getFrames */ public function testCorrectNestedFrames($value = '') { // Create manually to have a different line number from the outer $inner = new Exception('inner'); $outer = $this->getException('outer', 0, $inner); $inspector = $this->getInspectorInstance($outer); $frames = $inspector->getFrames(); $this->assertSame($outer->getLine(), $frames[0]->getLine()); } /** * @covers Whoops\Exception\Inspector::getFrames */ public function testDoesNotFailOnPHP7ErrorObject() { if (!class_exists('Error')) { $this->markTestSkipped( 'PHP 5.x, the Error class is not available.' ); } $inner = new \Error('inner'); $outer = $this->getException('outer', 0, $inner); $inspector = $this->getInspectorInstance($outer); $frames = $inspector->getFrames(); $this->assertSame($outer->getLine(), $frames[0]->getLine()); } /** * @covers Whoops\Exception\Inspector::getExceptionName */ public function testReturnsCorrectExceptionName() { $exception = $this->getException(); $inspector = $this->getInspectorInstance($exception); $this->assertEquals(get_class($exception), $inspector->getExceptionName()); } /** * @covers Whoops\Exception\Inspector::__construct * @covers Whoops\Exception\Inspector::getException */ public function testExceptionIsStoredAndReturned() { $exception = $this->getException(); $inspector = $this->getInspectorInstance($exception); $this->assertSame($exception, $inspector->getException()); } /** * @covers Whoops\Exception\Inspector::getFrames */ public function testGetFramesReturnsCollection() { $exception = $this->getException(); $inspector = $this->getInspectorInstance($exception); $this->assertInstanceOf('Whoops\\Exception\\FrameCollection', $inspector->getFrames()); } /** * @covers Whoops\Exception\Inspector::getFrames */ public function testGetFramesWithFiltersReturnsCollection() { $exception = $this->getException(); $inspector = $this->getInspectorInstance($exception); $frames = $inspector->getFrames([ function(Frame $frame) { return true; }, ]); $this->assertInstanceOf('Whoops\\Exception\\FrameCollection', $frames); $this->assertNotEmpty($frames); } /** * @covers Whoops\Exception\Inspector::getFrames */ public function testGetFramesWithFiltersReturnsEmptyCollection() { $exception = $this->getException(); $inspector = $this->getInspectorInstance($exception); $frames = $inspector->getFrames([ function(Frame $frame) { return false; }, ]); $this->assertInstanceOf('Whoops\\Exception\\FrameCollection', $frames); $this->assertEmpty($frames); } /** * @covers Whoops\Exception\Inspector::hasPreviousException * @covers Whoops\Exception\Inspector::getPreviousExceptionInspector */ public function testPreviousException() { $previousException = $this->getException("I'm here first!"); $exception = $this->getException("Oh boy", 0, $previousException); $inspector = $this->getInspectorInstance($exception); $this->assertTrue($inspector->hasPreviousException()); $this->assertEquals($previousException, $inspector->getPreviousExceptionInspector()->getException()); } /** * @covers Whoops\Exception\Inspector::hasPreviousException */ public function testNegativeHasPreviousException() { $exception = $this->getException("Oh boy"); $inspector = $this->getInspectorInstance($exception); $this->assertFalse($inspector->hasPreviousException()); } /** * @covers Whoops\Exception\Inspector::getPreviousExceptions */ public function testGetPreviousExceptionsReturnsListOfExceptions() { $exception1 = $this->getException('My first exception'); $exception2 = $this->getException('My second exception', 0, $exception1); $exception3 = $this->getException('And the third one', 0, $exception2); $inspector = $this->getInspectorInstance($exception3); $previousExceptions = $inspector->getPreviousExceptions(); $this->assertCount(2, $previousExceptions); $this->assertEquals($exception2, $previousExceptions[0]); $this->assertEquals($exception1, $previousExceptions[1]); } /** * @covers Whoops\Exception\Inspector::getPreviousExceptions */ public function testGetPreviousExceptionsReturnsEmptyListIfThereAreNoPreviousExceptions() { $exception = $this->getException('My exception'); $inspector = $this->getInspectorInstance($exception); $previousExceptions = $inspector->getPreviousExceptions(); $this->assertCount(0, $previousExceptions); } /** * @covers Whoops\Exception\Inspector::getPreviousExceptionMessages */ public function testGetPreviousExceptionMessages() { $exception1 = $this->getException('My first exception'); $exception2 = $this->getException('My second exception', 0, $exception1); $exception3 = $this->getException('And the third one', 0, $exception2); $inspector = $this->getInspectorInstance($exception3); $previousExceptions = $inspector->getPreviousExceptionMessages(); $this->assertEquals($exception2->getMessage(), $previousExceptions[0]); $this->assertEquals($exception1->getMessage(), $previousExceptions[1]); } /** * @covers Whoops\Exception\Inspector::getPreviousExceptionCodes */ public function testGetPreviousExceptionCodes() { $exception1 = $this->getException('My first exception', 99); $exception2 = $this->getException('My second exception', 20, $exception1); $exception3 = $this->getException('And the third one', 10, $exception2); $inspector = $this->getInspectorInstance($exception3); $previousExceptions = $inspector->getPreviousExceptionCodes(); $this->assertEquals($exception2->getCode(), $previousExceptions[0]); $this->assertEquals($exception1->getCode(), $previousExceptions[1]); } } ================================================ FILE: tests/Whoops/Handler/CallbackHandlerTest.php ================================================ handle(); foreach ($backtrace as $frame) { $this->assertStringNotContains('call_user_func', $frame['function']); } } } ================================================ FILE: tests/Whoops/Handler/JsonResponseHandlerTest.php ================================================ */ namespace Whoops\Handler; use RuntimeException; use Whoops\TestCase; class JsonResponseHandlerTest extends TestCase { /** * @return \Whoops\Handler\JsonResponseHandler */ private function getHandler() { return new JsonResponseHandler(); } /** * @return RuntimeException */ public function getException($message = 'test message') { return new RuntimeException($message); } /** * @param bool $withTrace * @return array */ private function getJsonResponseFromHandler($withTrace = false, $jsonApi = false) { $handler = $this->getHandler(); $handler->setJsonApi($jsonApi); $handler->addTraceToOutput($withTrace); $run = $this->getRunInstance(); $run->pushHandler($handler); $run->register(); $exception = $this->getException(); ob_start(); $run->handleException($exception); $json = json_decode(ob_get_clean(), true); // Check that the json response is parse-able: $this->assertEquals(json_last_error(), JSON_ERROR_NONE); return $json; } /** * @covers Whoops\Handler\JsonResponseHandler::addTraceToOutput * @covers Whoops\Handler\JsonResponseHandler::handle */ public function testReturnsWithoutFrames() { $json = $this->getJsonResponseFromHandler($withTrace = false,$jsonApi = false); // Check that the response has the expected keys: $this->assertArrayHasKey('error', $json); $this->assertArrayHasKey('type', $json['error']); $this->assertArrayHasKey('file', $json['error']); $this->assertArrayHasKey('line', $json['error']); // Check the field values: $this->assertEquals($json['error']['file'], __FILE__); $this->assertEquals($json['error']['message'], 'test message'); $this->assertEquals($json['error']['type'], get_class($this->getException())); // Check that the trace is NOT returned: $this->assertArrayNotHasKey('trace', $json['error']); } /** * @covers Whoops\Handler\JsonResponseHandler::addTraceToOutput * @covers Whoops\Handler\JsonResponseHandler::handle */ public function testReturnsWithFrames() { $json = $this->getJsonResponseFromHandler($withTrace = true,$jsonApi = false); // Check that the trace is returned: $this->assertArrayHasKey('trace', $json['error']); // Check that a random frame has the expected fields $traceFrame = reset($json['error']['trace']); $this->assertArrayHasKey('file', $traceFrame); $this->assertArrayHasKey('line', $traceFrame); $this->assertArrayHasKey('function', $traceFrame); $this->assertArrayHasKey('class', $traceFrame); $this->assertArrayHasKey('args', $traceFrame); } /** * @covers Whoops\Handler\JsonResponseHandler::addTraceToOutput * @covers Whoops\Handler\JsonResponseHandler::handle */ public function testReturnsJsonApi() { $json = $this->getJsonResponseFromHandler($withTrace = false,$jsonApi = true); // Check that the response has the expected keys: $this->assertArrayHasKey('errors', $json); $this->assertArrayHasKey('type', $json['errors'][0]); $this->assertArrayHasKey('file', $json['errors'][0]); $this->assertArrayHasKey('line', $json['errors'][0]); // Check the field values: $this->assertEquals($json['errors'][0]['file'], __FILE__); $this->assertEquals($json['errors'][0]['message'], 'test message'); $this->assertEquals($json['errors'][0]['type'], get_class($this->getException())); // Check that the trace is NOT returned: $this->assertArrayNotHasKey('trace', $json['errors']); } } ================================================ FILE: tests/Whoops/Handler/PlainTextHandlerTest.php ================================================ */ namespace Whoops\Handler; use RuntimeException; use StdClass; use Whoops\TestCase; use Whoops\Exception\Frame; class PlainTextHandlerTest extends TestCase { const DEFAULT_EXCEPTION_LINE = 34; const DEFAULT_LINE_OF_CALLER = 65; /** * @throws \InvalidArgumentException If argument is not null or a LoggerInterface * @param \Psr\Log\LoggerInterface|null $logger * @return \Whoops\Handler\PlainTextHandler */ private function getHandler($logger = null) { return new PlainTextHandler($logger); } /** * @return RuntimeException */ public function getException($message = 'test message') { return new RuntimeException($message); } /** * @param bool $withTrace * @param bool $withTraceArgs * @param int $traceFunctionArgsOutputLimit * @param bool $loggerOnly * @param bool $previousOutput * @param null $exception * @return array */ private function getPlainTextFromHandler( $withTrace = false, $withTraceArgs = false, $traceFunctionArgsOutputLimit = 1024, $loggerOnly = false, $previousOutput = false, $exception = null ) { $handler = $this->getHandler(); $handler->addTraceToOutput($withTrace); $handler->addTraceFunctionArgsToOutput($withTraceArgs); $handler->setTraceFunctionArgsOutputLimit($traceFunctionArgsOutputLimit); $handler->addPreviousToOutput($previousOutput); $handler->loggerOnly($loggerOnly); $run = $this->getRunInstance(); $run->pushHandler($handler); $run->register(); $exception = $exception ?: $this->getException(); try { ob_start(); $run->handleException($exception); } finally { return ob_get_clean(); } } /** * @covers Whoops\Handler\PlainTextHandler::__construct * @covers Whoops\Handler\PlainTextHandler::setLogger */ public function testConstructor() { $this->expectExceptionOfType('InvalidArgumentException'); $this->getHandler(new StdClass()); } /** * @covers Whoops\Handler\PlainTextHandler::setLogger */ public function testSetLogger() { $this->expectExceptionOfType('InvalidArgumentException'); $this->getHandler()->setLogger(new StdClass()); } /** * @covers Whoops\Handler\PlainTextHandler::addTraceToOutput */ public function testAddTraceToOutput() { $handler = $this->getHandler(); $this->assertEquals($handler, $handler->addTraceToOutput(true)); $this->assertTrue($handler->addTraceToOutput()); $handler->addTraceToOutput(false); $this->assertFalse($handler->addTraceToOutput()); $handler->addTraceToOutput(null); $this->assertEquals(null, $handler->addTraceToOutput()); $handler->addTraceToOutput(1); $this->assertTrue($handler->addTraceToOutput()); $handler->addTraceToOutput(0); $this->assertFalse($handler->addTraceToOutput()); $handler->addTraceToOutput(''); $this->assertFalse($handler->addTraceToOutput()); $handler->addTraceToOutput('false'); $this->assertTrue($handler->addTraceToOutput()); } /** * @covers Whoops\Handler\PlainTextHandler::addTraceFunctionArgsToOutput */ public function testAddTraceFunctionArgsToOutput() { $handler = $this->getHandler(); $this->assertEquals($handler, $handler->addTraceFunctionArgsToOutput(true)); $this->assertTrue($handler->addTraceFunctionArgsToOutput()); $handler->addTraceFunctionArgsToOutput(false); $this->assertFalse($handler->addTraceFunctionArgsToOutput()); $handler->addTraceFunctionArgsToOutput(null); $this->assertEquals(null, $handler->addTraceFunctionArgsToOutput()); $handler->addTraceFunctionArgsToOutput(1); $this->assertEquals(1, $handler->addTraceFunctionArgsToOutput()); $handler->addTraceFunctionArgsToOutput(0); $this->assertEquals(0, $handler->addTraceFunctionArgsToOutput()); $handler->addTraceFunctionArgsToOutput(''); $this->assertFalse($handler->addTraceFunctionArgsToOutput()); $handler->addTraceFunctionArgsToOutput('false'); $this->assertTrue($handler->addTraceFunctionArgsToOutput()); } /** * @covers Whoops\Handler\PlainTextHandler::setTraceFunctionArgsOutputLimit * @covers Whoops\Handler\PlainTextHandler::getTraceFunctionArgsOutputLimit */ public function testGetSetTraceFunctionArgsOutputLimit() { $addTraceFunctionArgsToOutput = 10240; $handler = $this->getHandler(); $handler->setTraceFunctionArgsOutputLimit($addTraceFunctionArgsToOutput); $this->assertEquals($addTraceFunctionArgsToOutput, $handler->getTraceFunctionArgsOutputLimit()); $handler->setTraceFunctionArgsOutputLimit('1024kB'); $this->assertEquals(1024, $handler->getTraceFunctionArgsOutputLimit()); $handler->setTraceFunctionArgsOutputLimit('true'); $this->assertEquals(0, $handler->getTraceFunctionArgsOutputLimit()); } /** * @covers Whoops\Handler\PlainTextHandler::loggerOnly */ public function testLoggerOnly() { $handler = $this->getHandler(); $this->assertEquals($handler, $handler->loggerOnly(true)); $this->assertTrue($handler->loggerOnly()); $handler->loggerOnly(false); $this->assertFalse($handler->loggerOnly()); $handler->loggerOnly(null); $this->assertEquals(null, $handler->loggerOnly()); $handler->loggerOnly(1); $this->assertTrue($handler->loggerOnly()); $handler->loggerOnly(0); $this->assertFalse($handler->loggerOnly()); $handler->loggerOnly(''); $this->assertFalse($handler->loggerOnly()); $handler->loggerOnly('false'); $this->assertTrue($handler->loggerOnly()); } /** * @covers Whoops\Handler\PlainTextHandler::addTraceToOutput * @covers Whoops\Handler\PlainTextHandler::handle */ public function testReturnsWithoutFramesOutput() { $text = $this->getPlainTextFromHandler( $withTrace = false, $withTraceArgs = true, $traceFunctionArgsOutputLimit = 1024, $loggerOnly = false ); // Check that the response has the correct value: // Check that the trace is NOT returned: $this->assertEquals( sprintf( "%s: %s in file %s on line %d\n", get_class($this->getException()), 'test message', __FILE__, self::DEFAULT_EXCEPTION_LINE ), $text ); } public function testReturnsWithoutPreviousExceptions() { $text = $this->getPlainTextFromHandler( $withTrace = false, $withTraceArgs = true, $traceFunctionArgsOutputLimit = 1024, $loggerOnly = false, $previousOutput = false, new RuntimeException('Outer exception message', 0, new RuntimeException('Inner exception message')) ); // Check that the response does not contain Inner exception message: $this->assertStringNotContains( sprintf( "%s: %s in file %s", RuntimeException::class, 'Inner exception message', __FILE__ ), $text ); } public function testReturnsWithPreviousExceptions() { $text = $this->getPlainTextFromHandler( $withTrace = false, $withTraceArgs = true, $traceFunctionArgsOutputLimit = 1024, $loggerOnly = false, $previousOutput = true, new RuntimeException('Outer exception message', 0, new RuntimeException('Inner exception message')) ); // Check that the response has the correct message: $this->assertEquals( sprintf( "%s: %s in file %s on line %d\n" . "%s: %s in file %s on line %d\n", RuntimeException::class, 'Outer exception message', __FILE__, 261, "\nCaused by\n" . RuntimeException::class, 'Inner exception message', __FILE__, 261 ), $text ); } /** * @covers Whoops\Handler\PlainTextHandler::addTraceToOutput * @covers Whoops\Handler\PlainTextHandler::getTraceOutput * @covers Whoops\Handler\PlainTextHandler::canOutput * @covers Whoops\Handler\PlainTextHandler::handle */ public function testReturnsWithFramesOutput() { $text = $this->getPlainTextFromHandler( $withTrace = true, $withTraceArgs = false, $traceFunctionArgsOutputLimit = 1024, $loggerOnly = false ); // Check that the response has the correct value: $this->assertStringContains('Stack trace:', $text); // Check that the trace is returned: $this->assertStringContains( sprintf( '%3d. %s->%s() %s:%d', 2, __CLASS__, 'getException', __FILE__, self::DEFAULT_LINE_OF_CALLER ), $text ); } /** * @covers Whoops\Handler\PlainTextHandler::addTraceToOutput * @covers Whoops\Handler\PlainTextHandler::addTraceFunctionArgsToOutput * @covers Whoops\Handler\PlainTextHandler::getTraceOutput * @covers Whoops\Handler\PlainTextHandler::getFrameArgsOutput * @covers Whoops\Handler\PlainTextHandler::canOutput * @covers Whoops\Handler\PlainTextHandler::handle */ public function testReturnsWithFramesAndArgsOutput() { $text = $this->getPlainTextFromHandler( $withTrace = true, $withTraceArgs = true, $traceFunctionArgsOutputLimit = 2048, $loggerOnly = false ); $lines = explode("\n", $text); // Check that the trace is returned with all arguments: $this->assertGreaterThan(60, count($lines)); // Check that the response has the correct value: $this->assertStringContains('Stack trace:', $text); // Check that the trace is returned: $this->assertStringContains( sprintf( '%3d. %s->%s() %s:%d', 2, 'Whoops\Handler\PlainTextHandlerTest', 'getException', __FILE__, self::DEFAULT_LINE_OF_CALLER ), $text ); // Check that the trace arguments are returned: $this->assertStringContains(sprintf( '%s string(%d) "%s"', PlainTextHandler::VAR_DUMP_PREFIX, strlen('test message'), 'test message' ), $text ); } /** * @covers Whoops\Handler\PlainTextHandler::addTraceToOutput * @covers Whoops\Handler\PlainTextHandler::addTraceFunctionArgsToOutput * @covers Whoops\Handler\PlainTextHandler::getTraceOutput * @covers Whoops\Handler\PlainTextHandler::getFrameArgsOutput * @covers Whoops\Handler\PlainTextHandler::canOutput * @covers Whoops\Handler\PlainTextHandler::handle */ public function testReturnsWithFramesAndLimitedArgsOutput() { $text = $this->getPlainTextFromHandler( $withTrace = true, $withTraceArgs = 3, $traceFunctionArgsOutputLimit = 1024, $loggerOnly = false ); // Check that the response has the correct value: $this->assertStringContains('Stack trace:', $text); // Check that the trace is returned: $this->assertStringContains( sprintf( '%3d. %s->%s() %s:%d', 2, 'Whoops\Handler\PlainTextHandlerTest', 'getException', __FILE__, self::DEFAULT_LINE_OF_CALLER ), $text ); // Check that the trace arguments are returned: $this->assertStringContains(sprintf( '%s string(%d) "%s"', PlainTextHandler::VAR_DUMP_PREFIX, strlen('test message'), 'test message' ), $text ); } /** * @covers Whoops\Handler\PlainTextHandler::loggerOnly * @covers Whoops\Handler\PlainTextHandler::handle */ public function testReturnsWithLoggerOnlyOutput() { $text = $this->getPlainTextFromHandler( $withTrace = true, $withTraceArgs = true, $traceFunctionArgsOutputLimit = 1024, $loggerOnly = true ); // Check that the response has the correct value: $this->assertEquals('', $text); } /** * @covers Whoops\Handler\PlainTextHandler::loggerOnly * @covers Whoops\Handler\PlainTextHandler::handle */ public function testGetFrameArgsOutputUsesDumper() { $values = []; $dumper = function ($var) use (&$values) { $values[] = $var; }; $handler = $this->getHandler(); $handler->setDumper($dumper); $args = [ ['foo', 'bar', 'buz'], [1, 2, 'Fizz', 4, 'Buzz'], ]; $actual = self::callPrivateMethod($handler, 'dump', [new Frame(['args' => $args[0]])]); $this->assertEquals('', $actual); $this->assertCount(1, $values); $this->assertEquals($args[0], $values[0]->getArgs()); $actual = self::callPrivateMethod($handler, 'dump', [new Frame(['args' => $args[1]])]); $this->assertEquals('', $actual); $this->assertCount(2, $values); $this->assertEquals($args[1], $values[1]->getArgs()); } } ================================================ FILE: tests/Whoops/Handler/PrettyPageHandlerTest.php ================================================ */ namespace Whoops\Handler; use InvalidArgumentException; use RuntimeException; use Whoops\TestCase; class PrettyPageHandlerTest extends TestCase { /** * @return \Whoops\Handler\PrettyPageHandler */ private function getHandler() { $handler = new PrettyPageHandler(); $handler->handleUnconditionally(); return $handler; } /** * @return RuntimeException */ public function getException() { return new RuntimeException(); } /** * Test that PrettyPageHandle handles the template without * any errors. * @covers Whoops\Handler\PrettyPageHandler::handle */ public function testHandleWithoutErrors() { $run = $this->getRunInstance(); $handler = $this->getHandler(); $run->pushHandler($handler); ob_start(); $run->handleException($this->getException()); ob_get_clean(); // Reached the end without errors $this->assertTrue(true); } /** * @covers Whoops\Handler\PrettyPageHandler::setPageTitle * @covers Whoops\Handler\PrettyPageHandler::getPageTitle */ public function testGetSetPageTitle() { $title = 'My Cool Error Handler'; $handler = $this->getHandler(); $this->assertEquals($handler, $handler->setPageTitle($title)); $this->assertEquals($title, $handler->getPagetitle()); } /** * @covers Whoops\Handler\PrettyPageHandler::addResourcePath * @covers Whoops\Handler\PrettyPageHandler::getResourcePaths */ public function testGetSetResourcePaths() { $path = __DIR__; // guaranteed to be valid! $handler = $this->getHandler(); $this->assertEquals($handler, $handler->addResourcePath($path)); $allPaths = $handler->getResourcePaths(); $this->assertCount(2, $allPaths); $this->assertEquals($allPaths[0], $path); } /** * @covers Whoops\Handler\PrettyPageHandler::addResourcePath */ public function testSetInvalidResourcesPath() { $this->expectExceptionOfType('InvalidArgumentException'); $this->getHandler()->addResourcePath(__DIR__ . '/ZIMBABWE'); } /** * @covers Whoops\Handler\PrettyPageHandler::getDataTables * @covers Whoops\Handler\PrettyPageHandler::addDataTable */ public function testGetSetDataTables() { $handler = $this->getHandler(); // should have no tables by default: $this->assertEmpty($handler->getDataTables()); $tableOne = [ 'ice' => 'cream', 'ice-ice' => 'baby', ]; $tableTwo = [ 'dolan' => 'pls', 'time' => time(), ]; $this->assertEquals($handler, $handler->addDataTable('table 1', $tableOne)); $this->assertEquals($handler, $handler->addDataTable('table 2', $tableTwo)); // should contain both tables: $tables = $handler->getDataTables(); $this->assertCount(2, $tables); $this->assertEquals($tableOne, $tables['table 1']); $this->assertEquals($tableTwo, $tables['table 2']); // should contain only table 1 $this->assertEquals($tableOne, $handler->getDataTables('table 1')); // should return an empty table: $this->assertEmpty($handler->getDataTables('ZIMBABWE!')); } /** * @covers Whoops\Handler\PrettyPageHandler::getDataTables * @covers Whoops\Handler\PrettyPageHandler::addDataTableCallback */ public function testSetCallbackDataTables() { $handler = $this->getHandler(); $this->assertEmpty($handler->getDataTables()); $table1 = function () { return [ 'hammer' => 'time', 'foo' => 'bar', ]; }; $expected1 = ['hammer' => 'time', 'foo' => 'bar']; $table2 = function () use ($expected1) { return [ 'another' => 'table', 'this' => $expected1, ]; }; $expected2 = ['another' => 'table', 'this' => $expected1]; $table3 = function() { return array("oh my" => "how times have changed!"); }; $expected3 = ['oh my' => 'how times have changed!']; // Test inspector parameter in data table callback $table4 = function (\Whoops\Exception\Inspector $inspector) { return array( 'Exception class' => get_class($inspector->getException()), 'Exception message' => $inspector->getExceptionMessage(), ); }; $expected4 = array( 'Exception class' => 'InvalidArgumentException', 'Exception message' => 'Test exception message', ); $inspectorForTable4 = new \Whoops\Exception\Inspector( new \InvalidArgumentException('Test exception message') ); // Sanity check, make sure expected values really are correct. $this->assertSame($expected1, $table1()); $this->assertSame($expected2, $table2()); $this->assertSame($expected3, $table3()); $this->assertSame($expected4, $table4($inspectorForTable4)); $this->assertEquals($handler, $handler->addDataTableCallback('table1', $table1)); $this->assertEquals($handler, $handler->addDataTableCallback('table2', $table2)); $this->assertEquals($handler, $handler->addDataTableCallback('table3', $table3)); $this->assertEquals($handler, $handler->addDataTableCallback('table4', $table4)); $tables = $handler->getDataTables(); $this->assertCount(4, $tables); // Supplied callable is wrapped in a closure $this->assertInstanceOf('Closure', $tables['table1']); $this->assertInstanceOf('Closure', $tables['table2']); $this->assertInstanceOf('Closure', $tables['table3']); $this->assertInstanceOf('Closure', $tables['table4']); // Run each wrapped callable and check results against expected output. $this->assertEquals($expected1, $tables['table1']()); $this->assertEquals($expected2, $tables['table2']()); $this->assertEquals($expected3, $tables['table3']()); $this->assertEquals($expected4, $tables['table4']($inspectorForTable4)); $this->assertSame($tables['table1'], $handler->getDataTables('table1')); $this->assertSame($expected1, call_user_func($handler->getDataTables('table1'))); } /** * @covers Whoops\Handler\PrettyPageHandler::setEditor * @covers Whoops\Handler\PrettyPageHandler::getEditorHref */ public function testSetEditorSimple() { $handler = $this->getHandler(); $this->assertEquals($handler, $handler->setEditor('sublime')); $this->assertEquals( $handler->getEditorHref('/foo/bar.php', 10), 'subl://open?url=file://%2Ffoo%2Fbar.php&line=10' ); $this->assertEquals( $handler->getEditorHref('/foo/with space?.php', 2324), 'subl://open?url=file://%2Ffoo%2Fwith%20space%3F.php&line=2324' ); $this->assertEquals( $handler->getEditorHref('/foo/bar/with-dash.php', 0), 'subl://open?url=file://%2Ffoo%2Fbar%2Fwith-dash.php&line=0' ); } /** * @covers Whoops\Handler\PrettyPageHandler::setEditor * @covers Whoops\Handler\PrettyPageHandler::getEditorHref * @covers Whoops\Handler\PrettyPageHandler::getEditorAjax */ public function testSetEditorCallable() { $handler = $this->getHandler(); // Test Callable editor with String return $this->assertEquals($handler, $handler->setEditor(function ($file, $line) { $file = rawurlencode($file); $line = rawurlencode($line); return "http://google.com/search/?q=$file:$line"; })); $this->assertEquals( $handler->getEditorHref('/foo/bar.php', 10), 'http://google.com/search/?q=%2Ffoo%2Fbar.php:10' ); // Then test Callable editor with Array return $this->assertEquals($handler, $handler->setEditor(function ($file, $line) { $file = rawurlencode($file); $line = rawurlencode($line); return [ 'url' => "http://google.com/search/?q=$file:$line", 'ajax' => true, ]; })); $this->assertEquals( $handler->getEditorHref('/foo/bar.php', 10), 'http://google.com/search/?q=%2Ffoo%2Fbar.php:10' ); $this->assertEquals( $handler->getEditorAjax('/foo/bar.php', 10), true ); $this->assertEquals($handler, $handler->setEditor(function ($file, $line) { $file = rawurlencode($file); $line = rawurlencode($line); return [ 'url' => "http://google.com/search/?q=$file:$line", 'ajax' => false, ]; })); $this->assertEquals( $handler->getEditorHref('/foo/bar.php', 10), 'http://google.com/search/?q=%2Ffoo%2Fbar.php:10' ); $this->assertEquals( $handler->getEditorAjax('/foo/bar.php', 10), false ); $this->assertEquals($handler, $handler->setEditor(function ($file, $line) { return false; })); $this->assertEquals( $handler->getEditorHref('/foo/bar.php', 10), false ); } /** * @covers Whoops\Handler\PrettyPageHandler::setEditor * @covers Whoops\Handler\PrettyPageHandler::addEditor * @covers Whoops\Handler\PrettyPageHandler::getEditorHref */ public function testAddEditor() { $handler = $this->getHandler(); $this->assertEquals($handler, $handler->addEditor('test-editor', function ($file, $line) { return "cool beans $file:$line"; })); $this->assertEquals($handler, $handler->setEditor('test-editor')); $this->assertEquals( $handler->getEditorHref('hello', 20), 'cool beans hello:20' ); } public function testEditorXdebug() { if (!extension_loaded('xdebug')) { // Even though this test only uses ini_set and ini_get, // without xdebug active, those calls do not work. // In particular, ini_get after ini_setting returns false. $this->markTestSkipped('The xdebug extension is not loaded.'); } $originalValue = ini_get('xdebug.file_link_format'); ini_set('xdebug.file_link_format', '%f:%l'); $handler = $this->getHandler(); $this->assertEquals($handler, $handler->setEditor('xdebug')); $this->assertEquals( '/foo/bar.php:10', $handler->getEditorHref('/foo/bar.php', 10) ); ini_set('xdebug.file_link_format', 'subl://open?url=%f&line=%l'); // xdebug doesn't do any URL encoded, matching that behaviour. $this->assertEquals( 'subl://open?url=/foo/with space?.php&line=2324', $handler->getEditorHref('/foo/with space?.php', 2324) ); ini_set('xdebug.file_link_format', $originalValue); } } ================================================ FILE: tests/Whoops/Handler/XmlResponseHandlerTest.php ================================================ getRunInstance(); $run->pushHandler($handler); $run->register(); ob_start(); $run->handleException($this->getException()); $data = ob_get_clean(); $this->assertTrue($this->isValidXml($data)); return simplexml_load_string($data); } /** * @depends testSimpleValid */ public function testSimpleValidFile(\SimpleXMLElement $xml) { $this->checkField($xml, 'file', $this->getException()->getFile()); } /** * @depends testSimpleValid */ public function testSimpleValidLine(\SimpleXMLElement $xml) { $this->checkField($xml, 'line', (string) $this->getException()->getLine()); } /** * @depends testSimpleValid */ public function testSimpleValidType(\SimpleXMLElement $xml) { $this->checkField($xml, 'type', get_class($this->getException())); } /** * Helper for testSimpleValid* */ private function checkField(\SimpleXMLElement $xml, $field, $value) { $list = $xml->xpath('/root/error/'.$field); $this->assertArrayHasKey(0, $list); $this->assertSame($value, (string) $list[0]); } private function getException() { return new RuntimeException(); } /** * See if passed string is a valid XML document * @param string $data * @return bool */ private function isValidXml($data) { $prev = libxml_use_internal_errors(true); $xml = simplexml_load_string($data); libxml_use_internal_errors($prev); return $xml !== false; } } ================================================ FILE: tests/Whoops/RunTest.php ================================================ */ namespace Whoops; use ArrayObject; use Exception; use InvalidArgumentException; use Mockery as m; use RuntimeException; use Whoops\Handler\Handler; use Whoops\Handler\HandlerInterface; use Whoops\Handler\PrettyPageHandler; use Whoops\Exception\Frame; use Whoops\Util\SystemFacade; class RunTest extends TestCase { public function testImplementsRunInterface() { $this->assertNotFalse(class_implements('Whoops\\Run', 'Whoops\\RunInterface')); } public function testConstantsAreAccessibleFromTheClass() { $this->assertEquals(RunInterface::ERROR_HANDLER, Run::ERROR_HANDLER); $this->assertEquals(RunInterface::EXCEPTION_HANDLER, Run::EXCEPTION_HANDLER); $this->assertEquals(RunInterface::SHUTDOWN_HANDLER, Run::SHUTDOWN_HANDLER); } /** * @param string $message * @return Exception */ protected function getException($message = "") { // HHVM does not support mocking exceptions // Since we do not use any additional features of Mockery for exceptions, // we can just use native Exceptions instead. return new \Exception($message); } /** * @return Handler */ protected function getHandler() { return m::mock('Whoops\\Handler\\Handler') ->shouldReceive('setRun') ->andReturn(null) ->mock() ->shouldReceive('setInspector') ->andReturn(null) ->mock() ->shouldReceive('setException') ->andReturn(null) ->mock(); } /** * @covers Whoops\Run::clearHandlers */ public function testClearHandlers() { $run = $this->getRunInstance(); $run->clearHandlers(); $handlers = $run->getHandlers(); $this->assertEmpty($handlers); } /** * @covers Whoops\Run::pushHandler */ public function testPushHandler() { $run = $this->getRunInstance(); $run->clearHandlers(); $handlerOne = $this->getHandler(); $handlerTwo = $this->getHandler(); $run->pushHandler($handlerOne); $run->pushHandler($handlerTwo); $handlers = $run->getHandlers(); $this->assertCount(2, $handlers); $this->assertContains($handlerOne, $handlers); $this->assertContains($handlerTwo, $handlers); } /** * @covers Whoops\Run::pushHandler */ public function testPushInvalidHandler() { $run = $this->getRunInstance(); $this->expectExceptionOfType('InvalidArgumentException'); $run->pushHandler('actually turnip'); } /** * @covers Whoops\Run::pushHandler */ public function testPushClosureBecomesHandler() { $run = $this->getRunInstance(); $run->pushHandler(function () {}); $this->assertInstanceOf('Whoops\\Handler\\CallbackHandler', $run->popHandler()); } /** * @covers Whoops\Run::popHandler * @covers Whoops\Run::getHandlers */ public function testPopHandler() { $run = $this->getRunInstance(); $handlerOne = $this->getHandler(); $handlerTwo = $this->getHandler(); $handlerThree = $this->getHandler(); $run->pushHandler($handlerOne); $run->pushHandler($handlerTwo); $run->pushHandler($handlerThree); $this->assertSame($handlerThree, $run->popHandler()); $this->assertSame($handlerTwo, $run->popHandler()); $this->assertSame($handlerOne, $run->popHandler()); // Should return null if there's nothing else in // the stack $this->assertNull($run->popHandler()); // Should be empty since we popped everything off // the stack: $this->assertEmpty($run->getHandlers()); } /** * @covers Whoops\Run::removeFirstHandler * @covers Whoops\Run::removeLastHandler * @covers Whoops\Run::getHandlers */ public function testRemoveHandler() { $run = $this->getRunInstance(); $handlerOne = $this->getHandler(); $handlerTwo = $this->getHandler(); $handlerThree = $this->getHandler(); $run->pushHandler($handlerOne); $run->pushHandler($handlerTwo); $run->pushHandler($handlerThree); $run->removeLastHandler(); $this->assertSame($handlerTwo, $run->getHandlers()[0]); $run->removeFirstHandler(); $this->assertSame($handlerTwo, $run->getHandlers()[0]); $this->assertCount(1, $run->getHandlers()); } /** * @covers Whoops\Run::register */ public function testRegisterHandler() { // It is impossible to test the Run::register method using phpunit, // as given how every test is always inside a giant try/catch block, // any thrown exception will never hit a global exception handler. // On the other hand, there is not much need in testing // a call to a native PHP function. $this->assertTrue(true); } /** * @covers Whoops\Run::unregister */ public function testUnregisterHandler() { $run = $this->getRunInstance(); $run->register(); $handler = $this->getHandler(); $run->pushHandler($handler); $run->unregister(); $this->expectExceptionOfType('Exception'); throw $this->getException("I'm not supposed to be caught!"); } /** * @covers Whoops\Run::pushHandler * @covers Whoops\Run::getHandlers */ public function testHandlerHoldsOrder() { $run = $this->getRunInstance(); $handlerOne = $this->getHandler(); $handlerTwo = $this->getHandler(); $handlerThree = $this->getHandler(); $handlerFour = $this->getHandler(); $run->pushHandler($handlerOne); $run->prependHandler($handlerTwo); $run->appendHandler($handlerThree); $run->appendHandler($handlerFour); $handlers = $run->getHandlers(); $this->assertSame($handlers[0], $handlerFour); $this->assertSame($handlers[1], $handlerThree); $this->assertSame($handlers[2], $handlerOne); $this->assertSame($handlers[3], $handlerTwo); } /** * @todo possibly split this up a bit and move * some of this test to Handler unit tests? * @covers Whoops\Run::handleException */ public function testHandlersGonnaHandle() { $run = $this->getRunInstance(); $exception = $this->getException(); $order = new ArrayObject(); $handlerOne = $this->getHandler(); $handlerTwo = $this->getHandler(); $handlerThree = $this->getHandler(); $handlerOne->shouldReceive('handle') ->andReturnUsing(function () use ($order) { $order[] = 1; }); $handlerTwo->shouldReceive('handle') ->andReturnUsing(function () use ($order) { $order[] = 2; }); $handlerThree->shouldReceive('handle') ->andReturnUsing(function () use ($order) { $order[] = 3; }); $run->pushHandler($handlerOne); $run->pushHandler($handlerTwo); $run->pushHandler($handlerThree); // Get an exception to be handled, and verify that the handlers // are given the handler, and in the inverse order they were // registered. $run->handleException($exception); $this->assertEquals((array) $order, [3, 2, 1]); } /** * @covers Whoops\Run::handleException */ public function testLastHandler() { $run = $this->getRunInstance(); $handlerOne = $this->getHandler(); $handlerTwo = $this->getHandler(); $handlerThree = $this->getHandler(); $handlerFour = $this->getHandler(); $run->pushHandler($handlerOne); $run->prependHandler($handlerTwo); $run->appendHandler($handlerThree); $run->appendHandler($handlerFour); $test = $this; $handlerFour ->shouldReceive('handle') ->andReturnUsing(function () use ($test) { $test->fail('$handlerFour should not be called'); }); $handlerThree ->shouldReceive('handle') ->andReturn(Handler::LAST_HANDLER); $twoRan = false; $handlerOne ->shouldReceive('handle') ->andReturnUsing(function () use ($test, &$twoRan) { $test->assertTrue($twoRan); }); $handlerTwo ->shouldReceive('handle') ->andReturnUsing(function () use (&$twoRan) { $twoRan = true; }); $run->handleException($this->getException()); // Reached the end without errors $this->assertTrue(true); } /** * Test error suppression using @ operator. */ public function testErrorSuppression() { $run = $this->getRunInstance(); $run->register(); $handler = $this->getHandler(); $run->pushHandler($handler); $test = $this; $handler ->shouldReceive('handle') ->andReturnUsing(function () use ($test) { $test->fail('$handler should not be called, error not suppressed'); }); @trigger_error("Test error suppression"); // Reached the end without errors $this->assertTrue(true); } public function testErrorCatching() { $run = $this->getRunInstance(); $run->register(); $handler = $this->getHandler(); $run->pushHandler($handler); $test = $this; $handler ->shouldReceive('handle') ->andReturnUsing(function () use ($test) { $test->fail('$handler should not be called error should be caught'); }); try { trigger_error('foo', E_USER_NOTICE); $this->fail('Should not continue after error thrown'); } catch (\ErrorException $e) { // Do nothing $this->assertTrue(true); return; } $this->fail('Should not continue here, should have been caught.'); } /** * Test to make sure that error_reporting is respected. */ public function testErrorReporting() { $run = $this->getRunInstance(); $run->register(); $handler = $this->getHandler(); $run->pushHandler($handler); $test = $this; $handler ->shouldReceive('handle') ->andReturnUsing(function () use ($test) { $test->fail('$handler should not be called, error_reporting not respected'); }); $oldLevel = error_reporting(E_ALL ^ E_USER_NOTICE); trigger_error("Test error reporting", E_USER_NOTICE); error_reporting($oldLevel); // Reached the end without errors $this->assertTrue(true); } /** * @covers Whoops\Run::silenceErrorsInPaths */ public function testSilenceErrorsInPaths() { $run = $this->getRunInstance(); $run->register(); $handler = $this->getHandler(); $run->pushHandler($handler); $test = $this; $handler ->shouldReceive('handle') ->andReturnUsing(function () use ($test) { $test->fail('$handler should not be called, silenceErrorsInPaths not respected'); }); $run->silenceErrorsInPaths('@^'.preg_quote(__FILE__, '@').'$@', E_USER_NOTICE); trigger_error('Test', E_USER_NOTICE); $this->assertTrue(true); } /** * @covers Whoops\Run::handleError * @requires PHP < 8 */ public function testGetSilencedError() { $run = $this->getRunInstance(); $run->register(); $handler = $this->getHandler(); $run->pushHandler($handler); @strpos(); $error = error_get_last(); $this->assertTrue($error && strpos($error['message'], 'strpos()') !== false); } /** * @covers Whoops\Run::handleError * @see https://github.com/filp/whoops/issues/267 */ public function testErrorWrappedInException() { try { $run = $this->getRunInstance(); $run->handleError(E_WARNING, 'my message', 'my file', 99); $this->fail("missing expected exception"); } catch (\ErrorException $e) { $this->assertSame(E_WARNING, $e->getSeverity()); $this->assertSame(E_WARNING, $e->getCode(), "For BC reasons getCode() should match getSeverity()"); $this->assertSame('my message', $e->getMessage()); $this->assertSame('my file', $e->getFile()); $this->assertSame(99, $e->getLine()); } } /** * @covers Whoops\Run::handleException * @covers Whoops\Run::writeToOutput */ public function testOutputIsSent() { $run = $this->getRunInstance(); $run->pushHandler(function () { echo "hello there"; }); ob_start(); $run->handleException(new RuntimeException()); $this->assertEquals("hello there", ob_get_clean()); } /** * @covers Whoops\Run::handleException * @covers Whoops\Run::writeToOutput */ public function testOutputIsNotSent() { $run = $this->getRunInstance(); $run->writeToOutput(false); $run->pushHandler(function () { echo "hello there"; }); ob_start(); $this->assertEquals("hello there", $run->handleException(new RuntimeException())); $this->assertEquals("", ob_get_clean()); } /** * @covers Whoops\Run::sendHttpCode */ public function testSendHttpCode() { $run = $this->getRunInstance(); $run->sendHttpCode(true); $this->assertEquals(500, $run->sendHttpCode()); } /** * @covers Whoops\Run::sendHttpCode */ public function testSendHttpCodeNullCode() { $run = $this->getRunInstance(); $this->assertEquals(false, $run->sendHttpCode(null)); } /** * @covers Whoops\Run::sendHttpCode */ public function testSendHttpCodeWrongCode() { $this->expectExceptionOfType('InvalidArgumentException'); $this->getRunInstance()->sendHttpCode(1337); } /** * @covers Whoops\Run::sendHttpCode */ public function testSendExitCode() { $run = $this->getRunInstance(); $run->sendExitCode(42); $this->assertEquals(42, $run->sendExitCode()); } /** * @covers Whoops\Run::sendExitCode */ public function testSendExitCodeDefaultCode() { $run = $this->getRunInstance(); $this->assertEquals(1, $run->sendExitCode()); } /** * @covers Whoops\Run::sendExitCode */ public function testSendExitCodeWrongCode() { $this->expectExceptionOfType('InvalidArgumentException'); $this->getRunInstance()->sendExitCode(255); } /** * @covers Whoops\Run::addFrameFilter * @covers Whoops\Run::getFrameFilters */ public function testAddFrameFilter() { $run = $this->getRunInstance(); $filterCallbackOne = function(Frame $frame) {}; $filterCallbackTwo = function(Frame $frame) {}; $run ->addFrameFilter($filterCallbackOne) ->addFrameFilter($filterCallbackTwo); $frameFilters = $run->getFrameFilters(); $this->assertCount(2, $frameFilters); $this->assertContains($filterCallbackOne, $frameFilters); $this->assertContains($filterCallbackTwo, $frameFilters); $this->assertInstanceOf("Whoops\\RunInterface", $run); } /** * @covers Whoops\Run::clearFrameFilters * @covers Whoops\Run::getFrameFilters */ public function testClearFrameFilters() { $run = $this->getRunInstance(); $run->addFrameFilter(function(Frame $frame) {}); $run = $run->clearFrameFilters(); $this->assertEmpty($run->getFrameFilters()); $this->assertInstanceOf("Whoops\\RunInterface", $run); } public function testShutdownHandlerDoesNotRunIfUnregistered() { $system = m::mock('Whoops\Util\SystemFacade'); $run = new Run($system); $run->writeToOutput(false); $run->allowQuit(false); $fatalError = [ 'type' => E_ERROR, 'message' => 'Simulated fatal error for shutdown', 'file' => 'somefile.php', 'line' => 10, ]; $system->shouldReceive('getLastError')->andReturn($fatalError)->byDefault(); $mockHandler = m::mock('Whoops\Handler\HandlerInterface'); $mockHandler->shouldNotReceive('handle'); $mockHandler->shouldNotReceive('setRun'); $mockHandler->shouldNotReceive('setInspector'); $mockHandler->shouldNotReceive('setException'); $run->pushHandler($mockHandler); $run->unregister(); ob_start(); $run->handleShutdown(); $output = ob_get_clean(); $this->assertEquals('', $output, "Output buffer should be empty."); } } ================================================ FILE: tests/Whoops/TestCase.php ================================================ */ namespace Whoops; use PHPUnit\Framework\TestCase as BaseTestCase; class TestCase extends BaseTestCase { /** * @return Run */ protected function getRunInstance() { $run = new Run(); $run->allowQuit(false); return $run; } /** * @param string $class * @return void */ protected function expectExceptionOfType($class) { if (method_exists($this, 'expectException')) { $this->expectException($class); } else { $this->setExpectedException($class); } } /** * @param string $a * @param string $b * @return void */ protected function assertStringContains($a, $b) { if (method_exists($this, 'assertStringContainsString')) { $this->assertStringContainsString($a, $b); } else { $this->assertContains($a, $b); } } /** * @param string $a * @param string $b * @return void */ protected function assertStringNotContains($a, $b) { if (method_exists($this, 'assertStringNotContainsString')) { $this->assertStringNotContainsString($a, $b); } else { $this->assertNotContains($a, $b); } } /** * @param object|string $class_or_object * @param string $method * @param mixed[] $args * @return mixed */ public static function callPrivateMethod($class_or_object, $method, $args = []) { $ref = new \ReflectionMethod($class_or_object, $method); // setAccessible does not do anything starting with 8.1, throws starting with 8.5 if (PHP_VERSION_ID < 80100) { $ref->setAccessible(true); } $object = is_object($class_or_object) ? $class_or_object : null; return $ref->invokeArgs($object, $args); } } ================================================ FILE: tests/Whoops/Util/HtmlDumperOutputTest.php ================================================ */ namespace Whoops\Util; use Whoops\TestCase; class HtmlDumperOutputTest extends TestCase { /** * @covers Whoops\Util::__invoke * @covers Whoops\Util::getOutput */ public function testOutput() { $htmlDumperOutput = new HtmlDumperOutput(); $htmlDumperOutput('first line', 0); $htmlDumperOutput('second line', 2); $expectedOutput = <<assertSame($expectedOutput, $htmlDumperOutput->getOutput()); } /** * @covers Whoops\Util::clear */ public function testClear() { $htmlDumperOutput = new HtmlDumperOutput(); $htmlDumperOutput('first line', 0); $htmlDumperOutput('second line', 2); $htmlDumperOutput->clear(); $this->assertNull($htmlDumperOutput->getOutput()); } } ================================================ FILE: tests/Whoops/Util/MiscTest.php ================================================ */ namespace Whoops\Util; use Whoops\TestCase; class MiscTest extends TestCase { /** * @dataProvider provideTranslateException * @param string $expected_output * @param int $exception_code */ public function testTranslateException($expected_output, $exception_code) { $output = Misc::translateErrorCode($exception_code); $this->assertEquals($expected_output, $output); } public function provideTranslateException() { return [ // When passing an error constant value, ensure the error constant // is returned. ['E_USER_WARNING', E_USER_WARNING], // When passing a value not equal to an error constant, ensure // E_UNKNOWN is returned. ['E_UNKNOWN', 3], ]; } } ================================================ FILE: tests/Whoops/Util/SystemFacadeTest.php ================================================ true]); $this->facade = new SystemFacade(); } /** * @after */ public function finishUp() { self::$runtime = null; \Mockery::close(); } public function test_it_delegates_output_buffering_to_the_native_implementation() { self::$runtime->shouldReceive('ob_start')->once(); $this->facade->startOutputBuffering(); } public function test_it_delegates_cleaning_output_buffering_to_the_native_implementation() { self::$runtime->shouldReceive('ob_get_clean')->once(); $this->facade->cleanOutputBuffer(); } public function test_it_delegates_getting_the_current_buffer_level_to_the_native_implementation() { self::$runtime->shouldReceive('ob_get_level')->once(); $this->facade->getOutputBufferLevel(); } public function test_it_delegates_ending_the_current_buffer_to_the_native_implementation() { self::$runtime->shouldReceive('ob_end_clean')->once(); $this->facade->endOutputBuffering(); } public function test_it_delegates_flushing_the_current_buffer_to_the_native_implementation() { self::$runtime->shouldReceive('flush')->once(); $this->facade->flushOutputBuffer(); } public function test_it_delegates_error_handling_to_the_native_implementation() { self::$runtime->shouldReceive('set_error_handler')->once(); $this->facade->setErrorHandler(function(){}); } public function test_it_delegates_error_handling_with_level_to_the_native_implementation() { self::$runtime->shouldReceive('set_error_handler')->once(); $this->facade->setErrorHandler(function(){}, E_CORE_ERROR); } public function test_it_delegates_exception_handling_to_the_native_implementation() { self::$runtime->shouldReceive('set_exception_handler')->once(); $this->facade->setExceptionHandler(function(){}); } public function test_it_delegates_restoring_the_exception_handler_to_the_native_implementation() { self::$runtime->shouldReceive('restore_exception_handler')->once(); $this->facade->restoreExceptionHandler(); } public function test_it_delegates_restoring_the_error_handler_to_the_native_implementation() { self::$runtime->shouldReceive('restore_error_handler')->once(); $this->facade->restoreErrorHandler(); } public function test_it_delegates_registering_a_shutdown_function_to_the_native_implementation() { self::$runtime->shouldReceive('register_shutdown_function')->once(); $this->facade->registerShutdownFunction(function(){}); } public function test_it_delegates_error_reporting_to_the_native_implementation() { self::$runtime->shouldReceive('error_reporting')->once()->withNoArgs(); $this->facade->getErrorReportingLevel(); } public function test_it_delegates_getting_the_last_error_to_the_native_implementation() { self::$runtime->shouldReceive('error_get_last')->once()->withNoArgs(); $this->facade->getLastError(); } public function test_it_delegates_sending_an_http_response_code_to_the_native_implementation() { self::$runtime->shouldReceive('headers_sent')->once()->withNoArgs(); self::$runtime->shouldReceive('header_remove')->once()->with('location'); self::$runtime->shouldReceive('http_response_code')->once()->with(230); $this->facade->setHttpResponseCode(230); } } function ob_start() { return SystemFacadeTest::delegate('ob_start'); } function ob_get_clean() { return SystemFacadeTest::delegate('ob_get_clean'); } function ob_get_level() { return SystemFacadeTest::delegate('ob_get_level'); } function ob_end_clean() { return SystemFacadeTest::delegate('ob_end_clean'); } function flush() { return SystemFacadeTest::delegate('flush'); } function set_error_handler(callable $handler, $types = 'use-php-defaults') { // Workaround for PHP 5.5 if ($types === 'use-php-defaults') { $types = E_ALL | E_STRICT; } return SystemFacadeTest::delegate('set_error_handler', func_get_args()); } function set_exception_handler(callable $handler) { return SystemFacadeTest::delegate('set_exception_handler', func_get_args()); } function restore_exception_handler() { return SystemFacadeTest::delegate('restore_exception_handler'); } function restore_error_handler() { return SystemFacadeTest::delegate('restore_error_handler'); } function register_shutdown_function() { return SystemFacadeTest::delegate('register_shutdown_function', func_get_args()); } function error_reporting($level = null) { return SystemFacadeTest::delegate('error_reporting', func_get_args()); } function error_get_last() { return SystemFacadeTest::delegate('error_get_last', func_get_args()); } function header_remove($header = null) { return SystemFacadeTest::delegate('header_remove', func_get_args()); } function headers_sent(&$filename = null, &$line = null) { return SystemFacadeTest::delegate('headers_sent', func_get_args()); } function http_response_code($code = null) { return SystemFacadeTest::delegate('http_response_code', func_get_args()); } ================================================ FILE: tests/Whoops/Util/TemplateHelperTest.php ================================================ */ namespace Whoops\Util; use Whoops\TestCase; class TemplateHelperTest extends TestCase { /** * @var TemplateHelper */ private $helper; /** * @before */ public function getReady() { $this->helper = new TemplateHelper(); } /** * @covers Whoops\Util\TemplateHelper::escapeButPreserveUris * @covers Whoops\Util\TemplateHelper::escape */ public function testEscape() { $original = "This is a Foo test string"; $this->assertEquals( $this->helper->escape($original), "This is a <a href=''>Foo</a> test string" ); } public function testEscapeBrokenUtf8() { // The following includes an illegal utf-8 sequence to test. // Encoded in base64 to survive possible encoding changes of this file. $original = base64_decode('VGhpcyBpcyBhbiBpbGxlZ2FsIHV0Zi04IHNlcXVlbmNlOiDD'); // Test that the escaped string is kinda similar in length, not empty $this->assertLessThan( 10, abs(strlen($original) - strlen($this->helper->escape($original))) ); } /** * @covers Whoops\Util\TemplateHelper::escapeButPreserveUris */ public function testEscapeButPreserveUris() { $original = "This is a http://google.com test string"; $this->assertEquals( $this->helper->escapeButPreserveUris($original), "This is a <a href=''>http://google.com</a> test string" ); } /** * @covers Whoops\Util\TemplateHelper::breakOnDelimiter */ public function testBreakOnDelimiter() { $this->assertSame( 'abc-123-456', $this->helper->breakOnDelimiter('-', 'abc-123-456') ); } /** * @covers Whoops\Util\TemplateHelper::shorten */ public function testShorten() { $path = '/foo/bar/baz/abc.def'; $this->assertSame($path, $this->helper->shorten($path)); $this->helper->setApplicationRootPath('/foo/bar'); $this->assertSame('…/baz/abc.def', $this->helper->shorten($path)); } /** * @covers Whoops\Util\TemplateHelper::slug */ public function testSlug() { $this->assertEquals("hello-world", $this->helper->slug("Hello, world!")); $this->assertEquals("potato-class", $this->helper->slug("Potato class")); } /** * @covers Whoops\Util\TemplateHelper::render */ public function testRender() { $template = __DIR__ . "/../../fixtures/template.php"; ob_start(); $this->helper->render($template, ["name" => "Bb"]); $output = ob_get_clean(); $this->assertEquals( $output, "hello-world\nMy name is B<o>b" ); } /** * @covers Whoops\Util\TemplateHelper::setVariables * @covers Whoops\Util\TemplateHelper::getVariables * @covers Whoops\Util\TemplateHelper::setVariable * @covers Whoops\Util\TemplateHelper::getVariable * @covers Whoops\Util\TemplateHelper::delVariable */ public function testTemplateVariables() { $this->helper->setVariables([ "name" => "Whoops", "type" => "library", "desc" => "php errors for cool kids", ]); $this->helper->setVariable("name", "Whoops!"); $this->assertEquals($this->helper->getVariable("name"), "Whoops!"); $this->helper->delVariable("type"); $this->assertEquals($this->helper->getVariables(), [ "name" => "Whoops!", "desc" => "php errors for cool kids", ]); } } ================================================ FILE: tests/bootstrap.php ================================================ * * Bootstrapper for PHPUnit tests. */ error_reporting(E_ALL); require_once __DIR__ . '/../vendor/autoload.php'; ================================================ FILE: tests/fixtures/frame.lines-test.php ================================================ slug("hello world!"); ?> My name is escape($name) ?>