Coder Social home page Coder Social logo

php-sage / sage Goto Github PK

View Code? Open in Web Editor NEW
44.0 4.0 4.0 1.92 MB

☯ Insightful PHP Debugging Assistant. Exceeds expectations. PHP 5.1→8.3

License: MIT License

PHP 46.98% JavaScript 5.96% Dockerfile 0.25% Makefile 0.46% HTML 41.68% SCSS 4.67%
php trace vardumper backtrace debugging-tool json-parser dumper php5 php8

sage's Introduction

Sage - Insightful PHP debugging assistant ☯

At first glance Sage is just a drop-in replacement for var_dump() and debug_backtrace().

However, it's much, much more.


Sage is designed to exceed expectations, it intelligently handles everything that you throw at it and displays in the best possible way.

If you can think of how it can be better, please create an issue!

For an overview of Sage's outstanding features jump to the F.A.Q.

Installation

composer require php-sage/sage --dev

Or if you prefer, download the phar and simply

<?php
require 'sage.phar';

sage('Hello, 🌎!');

Or if your PHP version does not support either, download the latest source code and include Sage.php

require 'sage-main/Sage.php';

sage('Hello, 🌎!');

Usage

sage($GLOBALS, $_SERVER); // dump any number of parameters

saged($i); // alias for sage();die;

sage(1); // shortcut for dumping trace
Function Shorthand
sage s Dump (same as \Sage::dump())
saged sd Dump & die
ssage ss Simple dump
ssaged ssd Simple dump & die
sagetrace s(1) Debug backtrace (same as \Sage::trace())

Simple dump:

simple mode example

Debug backtrace:

Trace view

Guarantees ✅

  1. Sage just works and it displays ALL available information (or in cases when something is truncated - that is clear too).

  2. Each release is vigorously tested. Or - use the bleeding edge dev-main version at your own risk.

  3. Semver versioning ensures there's no compatibility breaks if you use it in your production (eg. reporting).

  4. Sage has gotten lots of love and improvements in the last >10 years. It is used by a lot of real people in a lot of real-world scenarios, it is battle tested and has a lot of advanced features no other tool has.

More cool stuff

Sage displays the passed variable name and supports prefixes to the dump function call. Use it for some common on-the-fly adjustments to the dump output.

~ss($var); // outputs plain text
$output = @ss($var); // returns output instead of displaying it
! sage($var); // ignores depth limit for large objects
+ sage($var); // auto-expands the view
print sd($var); // saves output into "sage.html" in the current directory
print ! sd($var); // saves output into "sage.html" while also ignoring the output depth limit!

Sage tokenizes & introspects the calling code to get all this information. All that can be done with prefixes can also be achieved with standard, verbose syntax:

~ss($var); 
// is equivalent to:
Sage::enabled(Sage::MODE_TEXT_ONLY);
Sage::dump($var);

See Advanced section below if you want more tips & tricks.

Verbose versions

If you want to use Sage as part of permanent code (e.g. part of a test helper/logger/exception reporter etc), you can use the verbose way to invoke Sage:

// instead of sage()
Sage::dump('this looks way less hacky (yeah right:)');

// equivalent to sage(1);
Sage::trace(); 

// a real-life test helper:
class TestHelper{
  public function getVarDump(mixed $providedContext): string
  {
      if (! $providedContext) {
          return '';
      }
  
      $state = Sage::saveState();
      Sage::enabled(Sage::MODE_TEXT_ONLY);
      Sage::$aliases[]         = __CLASS__ . '::' . __FUNCTION__;
      Sage::$returnOutput      = true;
      Sage::$displayCalledFrom = false;
      $debugOutput             = Sage::dump($providedContext);
      
      Sage::saveState($state); // now reset settings to presumed defaults
  
      return PHP_EOL . $debugOutput;
  }
}

Customization

The main goal of Sage is to be zero-setup. There are also several customization options for advanced uses.

Where to store the configuration?

  1. Add this entry to the autoload.files configuration in composer.json:
"autoload": {
    "files": [
        "config/sage.php" /* <--------------- create this file with your settings! */
    ]
}, ...
  1. Put settings inside of php.ini:
; change sage theme:
sage.theme = solarized-dark
; always display all dump levels, almost always crashes the browser:
sage.maxLevels = 0
; set your IDE links
sage.editor = vscode
; disable Sage unless explicitly enabled
sage.enabled = 0 
  1. Include the desired settings in your bootstrap process anywhere™.
require 'sage.phar';
Sage::$theme = Sage::THEME_LIGHT;

All available options

Sage::$theme = Sage::THEME_ORIGINAL;

Currently available themes are:

  • Sage::THEME_ORIGINAL
  • Sage::THEME_LIGHT
  • Sage::THEME_SOLARIZED
  • Sage::THEME_SOLARIZED_DARK

Sage::$editor = ini_get('xdebug.file_link_format');

Make visible source file paths clickable to open your editor. Available options are:

'phpstorm-remote' - default (requires IDE Remote Control plugin), 'sublime', 'textmate', 'emacs', 'macvim', 'phpstorm', 'idea', 'vscode', 'vscode-insiders', 'vscode-remote', 'vscode-insiders-remote', 'vscodium', 'atom', 'nova', 'netbeans', 'xdebug'

Or pass a custom string where %file should be replaced with full file path, %line with line number to create a custom link. Set to null to disable linking.


Sage::$displayCalledFrom = true;

Whether to display where Sage was called from


Sage::$maxLevels = 7;

Max array/object levels to go deep, set to zero/false to disable


Sage::$expandedByDefault = false;

Draw rich output already expanded without having to click


Sage::$cliDetection = true; 

Enable detection when running in command line and adjust output format accordingly.


Sage::$cliColors = true;

In addition to above setting, enable detection when Sage is run in UNIX command line. Attempts to add coloring, but if opened as plain text, the color information is visible as gibberish.


Sage::$charEncodings =  [ 'UTF-8', 'Windows-1252', 'euc-jp' ]

Possible alternative char encodings in order of probability.


Sage::$returnOutput = false;

Sage returns output instead of printing it.


Sage::$aliases;

Add new custom Sage wrapper names. Optional, but needed for backtraces, variable name detection and modifiers to work properly. Accepts array or comma separated string. Use notation Class::method for methods.


🧙 Advanced Tips & Tricks

this section is under construction :)

// we already saw:
sage($GLOBALS, $_SERVER); 
// you can also go shorter for the same result:
s($GLOBALS, $_SERVER);
// or you can go the verbose way, it's all equivalent:
Sage::dump($GLOBALS, $_SERVER); 


// ss() will display a more basic, javascript-free display (but with colors)
ss($GLOBALS, $_SERVER);
// to recap: s() or sage() - dumps. Add "d" to die afterwards: sd(), saged()
// preppend "s" to simplify output: ss(), ssage().
// works in combination, too: ssd() and ssagedd() will dump in "simple mode" and die!

// prepending a tilde will make the output *even more basic* (rich->basic and basic->plain text)
~d($GLOBALS, $_SERVER); // more on modifiers below

// show a trace
Sage::trace();
s(1); // shorthand works too!
s(2); // trace - but just the paths 
Sage::dump( debug_backtrace() ); // you can even pass a custom result from debug_trace and it will be recognized

// dump and die debugging
sd($GLOBALS, $_SERVER); // dd() might be taken by your framework
saged($GLOBALS, $_SERVER); // so this is an equivalent alternative
ssd($GLOBALS, $_SERVER); // available for plain display too!

// this will disable Sage completely
Sage::enabled(false);
sd('Get off my lawn!'); // no effect
  • Sage supports keyboard shortcuts! Just press d when viewing output and the rest is self-explanatory, try it out! (p.s. vim-style hjkl works as well);

  • Call Sage::enabled(Sage::MODE_PLAIN); to switch to a simpler, js-free output.

  • Call Sage::enabled(Sage::MODE_TEXT_ONLY); for pure-plain text output which you can save or pass around by first setting Sage::$returnOutput = true;

  • Sage can provide a plain-text version of its output and does so automatically when invoked via PHP running in command line mode.

  • Double clicking the [+] sign in the output will expand/collapse ALL nodes; triple clicking a big block of text will select it all.

  • Clicking the tiny arrow on the right of the output will open it in a separate window where you can keep it for comparison.

  • Sage supports themes:

    For customization instructions read the section below.

  • If a variable is an object, its classname can be clicked to open the class in your IDE.

  • There are several real-time prefix modifiers you can use (combinations possible):

    Prefix Example
    print Puts output into current DIR as sage.html print sage()
    ! Dump ignoring depth limits for large objects ! sage()
    ~ Simplifies sage output (rich->html->plain) ~ sage()
    - Clean up any output before dumping - sage()
    + Expand all nodes (in rich view) + sage()
    @ Return output instead of displaying it @ sage()
  • Sage also includes a naïve profiler you may find handy. It's for determining relatively which code blocks take longer than others:

  • Sage runs perfectly fine on PHP 5.1 (couldn't find a way to test it on 5.0).

Sage::dump( microtime() ); // just pass microtime() - also works if you pass NOTHING: s();
sleep( 1 );
Sage::dump( microtime(), 'after sleep(1)' );
sleep( 2 );
sd( microtime(), 'final call, after sleep(2)' );


F.A.Q.

💬 How is it different or better than symfony/var-dumper?

  • Visible Variable name
  • Keyboard shortcuts. Type d and the rest is just self-explanatory (use arrows, space, tab, enter, you'll get it!).
  • Debug backtraces with full insight of arguments, callee objects and more.
  • Custom display for a lot of recognized types: custom types
  • Has text-only, plain and rich views, has several visual themes - created by a professional designer.
  • A huge number of usability enhancements - like the (clickable) call trace in the footer of each output.
  • Supports convenience modifiers, for example @sage($var); will return instead of outputting, -sage($var); will ob_clean all output to be the only thing on page (see advanced section above for more).
  • Compatibility! Fully works on PHP 5.1 - 8.1+!
  • Code is way less complex - to read and contribute to.
  • Sage came first - developed since pre-2012. It inspired the now ubiquitous dd shorthand, pioneered a lot of the concepts in the tool niche.

💬 What are the other dumpers out there

💬 Why does Sage look so much like Kint? A.K.A. Why does this repo have so few stars?

Because it is Kint, and I am its author, however the project was forcibly taken over by a malicious contributor!

Instead of fighting windmills I chose to fork and rename the last good version and continue under a new name!

You can use Sage as a drop-in replacement for Kint. Simple.

💬 How is var_dump - style debugging still relevant when we have Xdebug?

  1. In practice, Xdebug is quite often very difficult and time-consuming to install and configure.
  2. There's many use-cases where dump&die is just faster to bring up.
  3. There is no way you can visualise a timeline of changed data with XDebug. For example, all values dumped from within a loop.
  4. And there's more subtle use-cases, eg. if you stepped over something there's no way to go back, but with var-dumping the values are still there...

I use xdebug almost daily, by the way. Side by side with Sage.

Known issues

  1. Since PHP 8.2 variable name detection for multiline Sage calls is broken. Simple matter of Backtrace format changing the reported line, fix is comming.

Contributing

🎲 Prerequisites

  • Install Docker Compose.
  • If you're on Windows 10+ you need to use WSL2:
    1. Setup: wsl --install
    2. Set Ubuntu as your default wsl shell: wsl --set-version Ubuntu 2.
    3. All commands listed below must be run from inside wsl shell: wsl

Do your changes but before committing run

 docker compose run php composer build
 # OR (see Makefile):
 make build

To compile resources and build the phar file.

Author

Rokas Šleinius (Raveren)

Contributors: https://github.com/php-sage/sage/graphs/contributors

License

Licensed under the MIT License


Hope you'll love using Sage as much as I love creating it!

sage's People

Contributors

aljinovic avatar beeyev avatar efalder413 avatar eimajenthat avatar frosas avatar grahamcampbell avatar istvan-ujjmeszaros avatar jnvsor avatar larrybolt avatar mcd-php avatar pborreli avatar plugowski avatar rarst avatar raveren avatar schlessera avatar tgr avatar ulentini avatar vinculis avatar will123195 avatar willzyx-dev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

sage's Issues

DOM functions show no dumped data

Trying to use sage when debugging DOM manipulation with https://www.php.net/manual/en/book.dom.php functions, dump shows no real info.

DOMNodeList

print_r output:

DOMNodeList Object
(
    [length] => 1
)

sage output (omitted header with variable name and trace string):

DOMNodeList (0)

DOMElement

print_r output:

DOMElement Object
(
    [tagName] => span
    [schemaTypeInfo] =>
    [nodeName] => span
    [nodeValue] => This item is currently unavailable in your region
    [nodeType] => 1
    [parentNode] => (object value omitted)
    [childNodes] => (object value omitted)
    [firstChild] => (object value omitted)
    [lastChild] => (object value omitted)
    [previousSibling] => (object value omitted)
    [nextSibling] => (object value omitted)
    [attributes] => (object value omitted)
    [ownerDocument] => (object value omitted)
    [namespaceURI] =>
    [prefix] =>
    [localName] => span
    [baseURI] =>
    [textContent] => This item is currently unavailable in your region
)

sage output (omitted header with variable name and trace string):

DOMElement (0)

Simple dump functions are not defined (Composer installation)

Hi, I've installed sage with Composer in a pre-existing project, the setup is PHP 8.1 with some Symfony components (so dd is taken).

I tested it by using the sage() and saged() functions and it works very well (backtrace dump works too).
However, it seems that their shorthand versions - s() and sd() respectively - are actually returning simple dumps, while explicitly calling the simple dump functions - i.e., ssage() and ssaged() - raises a fatal error because they seem to be undefined.

As far as I understand, the library injects functions in the global namespace, so it shouldn't be necessary to explicitly require the class and/or individual functions with use statements, correct?

This is a sample output of calling saged('testing'):

image

while this is the output of sd('testing'):

image

Is this the expected behaviour?

PHP version compatibility

Hi Rokas,

I'm working on a php v5.3 codebase. I'm downloaded Sage v1.5.4 and required it and I'm getting this error
Parse error: syntax error, unexpected '=' in phar:///var/www/docroot/lib/sage.phar/Sage.php on line 354

I checked the file, and I'm suspecting it could be the array destructure that is only available in php v7.1.

Do you know what I can do about it?

Not Available Methods

Hello, I have just discovered php-sage and I find it good because it avoids the exceptions that Kint generates.

However, I noticed a few things:

1- Sage does not display available methods like in Kint;

2- In the "Called From", we cannot see the complete path like in Kint

3- I haven't seen all of Kint's themes

4- It seems that not all Kint plugins are included
Screenshot

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.