Code Monkey home page Code Monkey logo

php-ref's Introduction

REF, or r() is a nicer alternative to PHP's print_r / var_dump functions.

Requirements

  • (server) PHP 5.3+ (5.4+ displays additional info)
  • (client) Any browser, except IE 8 and lower of course

Installation using Composer

Add REF to your composer.json:

{
    "require": {
        "digitalnature/php-ref": "dev-master"
    }
}

Now tell composer to download the bundle by running:

$ php composer.phar update digitalnature/php-ref

Composer will install the bundle to the directory vendor/digitalnature.

Usage

Basic example:

// include the class (not needed if project runs with Composer because it's auto-loaded)
require '/full/path/to/ref.php';

// display info about defined classes
r(get_declared_classes());

// display info about global variables
r($GLOBALS);

To print in text mode you can use the rt() function instead:

rt($var);

To terminate the script after the info is dumped, prepend the bitwise NOT operator:

~r($var);   // html
~rt($var);  // text

Prepending the error control operator (@) will return the information:

$output = @r($var);   // html
$output = @rt($var);  // text

Keyboard shortcuts (javascript must be enabled):

  • X - collapses / expands all levels
  • Ctrl + X - toggles display state

To modify the global configuration call ref::config():

// example: initially expand first 3 levels
ref::config('expLvl', 3);

You can also add configuration options in your php.ini file like this:

[ref]
ref.expLvl = 3
ref.maxDepth = 4

Currently available options and their default values:

Option Default Description
'expLvl' 1 Initially expanded levels (for HTML mode only). A negative value will expand all levels
'maxDepth' 6 Maximum depth (0 to disable); note that disabling it or setting a high value can produce a 100+ MB page when input involves large data
'showIteratorContents' FALSE Display iterator data (keys and values)
'showResourceInfo' TRUE Display additional information about resources
'showMethods' TRUE Display methods and parameter information on objects
'showPrivateMembers' FALSE Include private properties and methods
'showStringMatches' TRUE Perform and display string matches for dates, files, json strings, serialized data, regex patterns etc. (SLOW)
'formatters' array() Custom/external formatters (as associative array: format => className)
'shortcutFunc' array('r', 'rt') Shortcut functions used to detect the input expression. If they are namespaced, the namespace must be present as well (methods are not supported)
'stylePath' '{:dir}/ref.css' Local path to a custom stylesheet (HTML only); FALSE means that no CSS is included.
'scriptPath' '{:dir}/ref.js' Local path to a custom javascript (HTML only); FALSE means no javascript (tooltips / toggle / kbd shortcuts require JS)
'showUrls' FALSE Gets information about URLs. Setting to false can improve performance (requires showStringMatches to be TRUE)
'timeout' 10 Stop execution after this amount of seconds, forcing an incomplete listing. Applies to all calls
'validHtml' FALSE For HTML mode only. Whether to produce W3C-valid HTML (larger code output) or unintelligible, potentially browser-incompatible but much smaller code output

Similar projects

TODOs

  • Inherit DocBlock comments from parent or prototype, if missing
  • Refactor "bubbles" (for text-mode)
  • Correctly indent multi-line strings (text-mode)
  • Move separator tokens to ::before and ::after pseudo-elements (html-mode)

License

http://opensource.org/licenses/mit-license.html

php-ref's People

Contributors

aolin480 avatar bukashk0zzz avatar digitalnature avatar insign avatar ivosabev avatar jcmarchi avatar joe-walker avatar morrislaptop avatar patrioticcow avatar ureimers avatar wycks 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

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

php-ref's Issues

script crashes

For some reason all my php scripts who has r() or rt() crashes.
I see 2-3 r() outputs before crash, but no error messages, scripts just stops.
if I change r() function to just

function r(){
$args = func_get_args();
print_r($args);
return false;

everything works.

I dont know why I see no any errors, on local it works but on my server it crashes.
But, anyway, I should see error messages no?

It doesnt looks like javascript related because rt() giving same issue.
It can be momry leak, but I have my error handler and can see all critical issues.

E_WARNING DateTime

E_WARNING DateTime::__construct(): Failed to parse time string (995 0901) at position 0 (9): Unexpected character - ref.php:1403

preg_grep() error line 773

ErrorException in ref.php line 773:
preg_grep(): Compilation failed: unknown property name after \P or \p at offset 12

__debugInfo support

If I create a class with magic methods, for example to store my properties in an array named $propertyList (to have a weak-structured object for non-typed usage), I can trick the standard PHP's var_dump($var) function to dump the properties inside this array, just like they were 'standard' class properties. Let me show what I mean (of course the code could be simpler than it is, but I wrote the example quickly as a proof of concept, so please don't focus on that):

First - the standard behavior:

<?php

class Test
{
    public $propertyList;

    function __call($name, $arguments)
    {
        if ('set' === substr($name, 0, strlen('set')))
        {
            $name = lcfirst(substr($name, strlen('set'), strlen($name) - strlen('set')));
            $this->propertyList[$name] = $arguments[0];
            return $this;
        }
        elseif ('get' === substr($name, 0, strlen('get')))
        {
            $name = lcfirst(substr($name, strlen('get'), strlen($name) - strlen('get')));

            if (array_key_exists($name, $this->propertyList)) return $this->propertyList[$name];
        }
    }
}

$t = new Test();

$t->setId(123);

var_dump($t);

the result:

object(Test)#1 (1) {
  ["propertyList"]=>
  array(1) {
    ["id"]=>
    int(123)
  }
}

then, the behavior with __debugInfo overriden - like so:

class Test
{
    public $propertyList;

    function __debugInfo()
    {
        return $this->propertyList;
    }
    
    function __call($name, $arguments)
    {
        if ('set' === substr($name, 0, strlen('set')))
        {
            $name = lcfirst(substr($name, strlen('set'), strlen($name) - strlen('set')));
            $this->propertyList[$name] = $arguments[0];
            return $this;
        }
        elseif ('get' === substr($name, 0, strlen('get')))
        {
            $name = lcfirst(substr($name, strlen('get'), strlen($name) - strlen('get')));

            if (array_key_exists($name, $this->propertyList)) return $this->propertyList[$name];
        }
    }
}

$t = new Test();

$t->setId(123);

var_dump($t);

resulting in:

object(Test)#1 (1) {
  ["id"]=>
  int(123)
}

It would be nice for the library to mind the __debugInfo function like the standard PHP dumping functions do. It would make it easier to preview dynamic objects like above, as now all I get is an object with $propertyList as its lone property, where this variable's role is purely to overshadow the 'virtual' / 'dynamic' properties, which are of interest. Of course I have all properties dumped inside, but it would be a nice DX improvement to have them on sight without having to expand the $propertyList variable first.

Is it possible to implement such a functionality?

Wrong nesting

php-ref produces wrong html for this code:

$a = array(
    'key1' => array('subkey' => array(array("1","2"))),
    'key2' => '3',
);
r($a);

You can see key2 => 3 falls out of scope.
Thus rt($a) seems to work correctly.

SimpleXMLElement attributes

For some reason, I cannot get properties inside the @attributes object of SimpleXMLElement objects to show.

http://i.imgur.com/84AtMfy.png

Kint and xdebug's var_dump can see them, I'm not sure about stock PHP var_dump. I love REF, it looks way more appealing and clean than Kint, but this problem makes it unusable for me.

Also, have you thought about adding support for backtracing? I would completely get rid of Kint in favor of this project if this was added :)

Hiding path to PHP file

Hi - firstly, thanks for writing this - I use it all the time and find it really useful.

When the php-ref output is diplayed, e.g. if I did r($my_array) then in the top-right of the outputted data, I see e.g.

C:\websites\playlist.php:77

On your demo page the line number and file name are not displayed.

I have looked at the settings on the Options part of your instructions page but can't see an option I could use to hide the file name and line number.

Is there a way to hide the info which is displayed in this part of the php-ref output, using an example file path below:

<r data-backtrace="">
	C:\websites\playlist.php:77
</r>

I can see I can hide the path using jQuery - e.g.

$('r[data-backtrace=""]').hide();

However, as that's at the end of the page, I can still see the path to the PHP for a second or two before the path is hidden by the jQuery code.

Thanks

Jim

Better regex matching of date & datetime.

http://rgxdb.com/r/526K7G5W

/^(?:[+-]?\d{4}(?!\d{2}\b))(?:(-?)(?:(?:0[1-9]|1[0-2])(?:\1(?:[12]\d|0[1-9]|3[01]))?|W(?:[0-4]\d|5[0-2])(?:-?[1-7])?|(?:00[1-9]|0[1-9]\d|[12]\d{2}|3(?:[0-5]\d|6[1-6])))(?:T\s?(?:\2[0-5]\d(?:[.,]\d+)?)?(?:[zZ]|(?:[+-])(?:[01]\d|2[0-3]):?(?:[0-5]\d)?)?)?)?$/

This regex above is supposed to match ISO-8601 dates and I suppose that it's better at identifying date strings than the original code. I was prompted to add this better-date-matching since the current code mis-identified a "HK phone number with center-blank-separator" (1234 5678) as dates and it bugged me.

protected $iso_8601 = '/^(?:[\+-]?\d{4}(?!\d{2}\b))(?:(-?)(?:(?:0[1-9]|1[0-2])(?:\1(?:[12]\d|0[1-9]|3[01]))?|W(?:[0-4]\d|5[0-2])(?:-?[1-7])?|(?:00[1-9]|0[1-9]\d|[12]\d{2}|3(?:[0-5]\d|6[1-6])))(?:[T\s](?:(?:(?:[01]\d|2[0-3])(?:(:?)[0-5]\d)?|24\:?00)(?:[\.,]\d+(?!:))?)?(?:\2[0-5]\d(?:[\.,]\d+)?)?(?:[zZ]|(?:[\+-])(?:[01]\d|2[0-3]):?(?:[0-5]\d)?)?)?)?$/';
if(($length < 128) && static::$env['supportsDate'] && preg_match($this->iso_8601, $subject) && !preg_match('/[^A-Za-z0-9.:+\s\-\/]/', $subject)){

If the author don't mind, please add this to your fantastic work. If no one issue any pull request, at least users of this piece of code can add the regex themselves.

Thanks.

Some changes please

On this line is problem: $components = $this->splitRegex($subject);
splitRegex() is static!
2.
dont use deprecated mysql functions like:
mysql_list_dbs, etc.
3.
for: public function __set($name, $value)

  • make pair function __isset

"data-exptxt" empty when used inside a loop

Seems like "data-exptxt" only gets set once when r() is used inside a loop. For example:

foreach([1,2,3,4,5] as $n) { r($n); }

The result of the above code is that only the first output has "data-exptxt" set. All others do not.

Integrations with a WP plugin

I hope you don't mind I forked this into a WP plugin https://github.com/wycks/WP-Pretty-Debug

Not sure what your plans are but I can maintain it with your upstream changes, there are some CSS issues with inline debugging that I'm not sure how to tackle, so far I'm just using an extra CSS style sheet to over ride.

Should I put some work into it or are you planning on doing a plugin with it? I don't want to step on anyones toes considering you created it.

Setup expand status

ref::$expanded should be made public so that one can set it initially to false.

r($object), throw a ReflectionException

Type: ReflectionException
Code: 0
Message: Internal error: Failed to retrieve the default value
File: E:\Codes\myCodes\imnicy.com\vendor\digitalnature\php-ref\ref.php
Line: 1956

#0 E:\Codes\myCodes\imnicy.com\vendor\digitalnature\php-ref\ref.php(1956): ReflectionParameter->isDefaultValueConstant()
#1 E:\Codes\myCodes\imnicy.com\vendor\digitalnature\php-ref\ref.php(314): ref->evaluate(Object(Nicy\Support\Collection))
#2 E:\Codes\myCodes\imnicy.com\vendor\digitalnature\php-ref\ref.php(40): ref->query(Object(Nicy\Support\Collection), '$result')
#3 E:\Codes\myCodes\imnicy.com\app\Http\Controllers\HomeController.php(16): r(Object(Nicy\Support\Collection))
#4 E:\Codes\myCodes\imnicy.com\framework\src\Handlers\Strategies\RequestResponse.php(43): App\Http\Controllers\HomeController->index(Object(Symfony\Component\HttpFoundation\Request))
......

Composer / Packagist support

This is an awesome project! Please consider adding support for Composer and Packagist very soon.

In the meantime, I figured I'd share how I set things up in my composer.json project file (you have to bump up the version number manually everytime you want to fetch updates):

"require-dev": {
    "digitalnature/php-ref": "*"
},

"repositories": [
    {
        "type": "package",
        "package": {
            "name": "digitalnature/php-ref",
            "version": "0.0.1",
            "dist": {
                "url": "https://github.com/digitalnature/php-ref/archive/master.zip",
                "type": "zip"
            },
            "source": {
                "url": "https://github.com/digitalnature/php-ref.git",
                "type": "git",
                "reference": "master"
            },
            "autoload": {
                "classmap": [
                    "ref.php"
                ],
                "files": [
                    "ref.php"
                ]
            }
        }
    }
]

Bugfix for Array (Simple)

At least on PHP v8.1 I was getting the following error:

Trying to access array offset on value of type null in /inc/vendor/digitalnature/php-ref/ref.php on line 472

I was able to fix this locally by adjusting line 472 from

if(in_array($parts[1][0], array('&', '$'), true)){

to

if(is_array($parts[1]) && in_array($parts[1][0], array('&', '$'), true)){

Please confirm if this fix works & if this can be adjusted in your repo.

Get assets manually

Hi!

I'd like to be able to get the assets manually (ref::getAssets()?) so that i can cache them.
You could maybe combine this with something like ref::config('autogenAssets', FALSE).

ref::transform would then contain something like:

if(static::$autogenAssets && !$didAssets) {
    echo ref::getAssets();
    $didAssets = true;
}

There is also a small error in the style html tag. It contains indeed the scoped tag with may prevent the styles to be applied to some output. This attribute is poorly supported today but this could be an issue soon.

Thanks for your GREAT work!

Doctype should not be sent when output buffering is enabled

I use output buffering to render and cache different parts of a website. Because of that, no headers are sent before everything is rendered. This is detected by headers_sent() returning true in ref.php:43 and causes r() to send the headers every time is is called.

For that reason I replaced line 43 by:
if(!headers_sent() && ob_get_level() == 0)

This may not be the best solution (which woud require to check every output buffer's length) but it did the trick for me (I don't use r() before content was sent to the browser).

DEBUG_BACKTRACE_IGNORE_ARGS constant missing in PHP < 5.3.6

Hello,

There's an error on line 2667 in this file: https://github.com/digitalnature/php-ref/blob/master/ref.php

I'm having difficulties using the well known CentOS 6.x series with php provided by default repository, version 5.3.3. Your code throws a warning due to the fact that I'm missing DEBUG_BACKTRACE_IGNORE_ARGS constant that was added in php 5.3.6. Replacing the package with something else or compiling a newer version of php is not an acceptable fix within the institution policy.

Would you consider implementing a fix for this ? If it helps: as far as I searched the web and tested locally on my machine (php 5.6.9) I evaluated this constant to be an integer of value 2. Also, I used composer to install the library.

Json output for API ?

Hi,

First thank you for you great library, I use it everyday !
I would like to know if there is a way to print the output as a JSON to use it on my API !

Thank you very much !

Why the rt() function set the http header ?

Hi Sir

we use the @rt() function inside our Slim webapp to log data to file.
The problem is that the same function set the http header with the following statement:
header('Content-Type: text/plain; charset=utf-8'); (file ref.php, line 73)
That goes in conflict with our webapp which should serve html content.

Any advice ?
Thank you

Apache crash with Laravel model

I have issue with php-ref. I used your project in past (it is AWESOME), but now, when i want to display single Model, get by find() or findOrFail() or all()[0] it just crashes apache.

Apache stopped working:
//it is in czech, hope you can translate it or just recognize by any other windows error
Podpis problému:
  Název události problému:   APPCRASH
  Název aplikace:  httpd.exe
  Verze aplikace:   2.4.18.0
  Časové razítko aplikace:   5667f02e
  Název chybného modulu:  php7ts.dll
  Verze chybného modulu:   7.0.1.0
  Časové razítko chybného modulu:   5671ed04
  Kód výjimky:    c0000005
  Posun výjimky:   000fc962
  Verze operačního systému:  6.1.7601.2.1.0.256.49
  ID národního prostředí:   1029
  Další informace 1:  0a9e
  Další informace 2:  0a9e372d3b4ad19135b953a78882e789
  Další informace 3:  0a9e
  Další informace 4:  0a9e372d3b4ad19135b953a78882e789

In Apache log is just that child process stopped working, nothing else, PHP log I can't find and Laravel log is clear.
Laravel version: 5.2
php-rev version: dev-master and v1.2, both do same
When i use it on anything else, like collection of models or whatever it works, just single model does not work.
Hope you will fix soon this so I can use this further, until then I must switch to anything else, but other projects are ugly :/

Release

Release it please, cause if someone (like me) adds it like requries in composer.json for my packadge, then i cannot update it :)

Mark as abandoned?

Since no new PRs have been accepted in a while, nor have issues been getting resolved - perhaps it's best to mark this project as abandoned so someone else may fork and continue the work? @digitalnature

Wordpress Plugin

Even though this is dead simple to implement manually, would you be opposed to somebody making a WordPress plugin out of this git?

Problem use it in error handler

Hi,
I tried use it in error handles to show debug_backtrace() with some problems.

Listing incomplete. Timed-out after 10.86s
2.
When I have some global object with content in variable, and content included html,doctype meta tags, it will crash or not show.

php-ref folder delets on push to origin

Hello, I dont think this is an issue with php-ref but i'm not sure how to fix it. I push vendor folder to origin (tsk, tsk, I know). When I do the php-ref folder never makes it. Do you have any idea how to keep this from happening? THnks

Exclude HTML

Hi. Is it possible to remove the surrounding HTML structure? I just want the body.

emulate kintLite

how can i get kintLite back from 0.9.1?
i tried the 3 modes but they output in a strange way
i just need the old fashion kintLite

"Implements", "Properties" and "Methods"

I love this project but have one concern

Would it be possible add a parameter to r() to show only object values as (var_dump but coloured) without annoying methods and implements variables only?

Let say, r() will return me only "Implements", "Properties" and "Methods" lists but var_dump return actual data.

Example of useless r() output

$message/media/DriveD/www/complex/test2.php:47XSimpleXMLElement :: XSimpleXMLIterator :: XCFSimpleXML object(ImplementsCountable (1), Iterator (5), RecursiveIterator (7), Traversable (0)Properties->xml_ns=XSimpleXMLElement :: XSimpleXMLIterator :: XCFSimpleXML object()->xml_ns_url=XSimpleXMLElement :: XSimpleXMLIterator :: XCFSimpleXML object()->encoded=XSimpleXMLElement :: XSimpleXMLIterator :: XCFSimpleXML object()->Body=XSimpleXMLElement :: XSimpleXMLIterator :: XCFSimpleXML object()->MD5OfBody=XSimpleXMLElement :: XSimpleXMLIterator :: XCFSimpleXML object()->ReceiptHandle=XSimpleXMLElement :: XSimpleXMLIterator :: XCFSimpleXML object()->MessageId=XSimpleXMLElement :: XSimpleXMLIterator :: XCFSimpleXML object()Methods->__call($name, $arguments)->__toString()::init($data, $options, $data_is_url, $ns, $is_prefix = false)->query($expr)->parent($node = null)->to_string()->to_array()->to_stdClass()->to_json()->to_yaml()->is($value)->contains($value)->matches($pattern)->starts_with($value)->ends_with($value)->rewind()->valid()->current()->key()->next()->hasChildren()->getChildren()->F__construct($data, $options = null, $data_is_url = null, $ns = null, $is_prefix = null)->asXML($filename = null)->saveXML($filename = null)->xpath($path)->registerXPathNamespace($prefix, $ns)->attributes($ns = null, $is_prefix = null)->children($ns = null, $is_prefix = null)->getNamespaces($recursve = null)->getDocNamespaces($recursve = null)->getName()->addChild($name, $value = null, $ns = null)->addAttribute($name, $value = null, $ns = null)->count())

thanks!

"x" keystroke

The x key can be used to expand all the properties of arrays and objects.
While this feature is not that useful (in my opinion at least), it prevents from typing x's in input fields.
You should either remove this behavior or prevent it from happening when an input, textarea or select is focussed.

unable to handle closed curl resource

Under the following example, r assumes the resource is of type object because php 5.5's gettype() doesn't return 'resource' as it should. This is primarily a bug in PHP but can be worked around in ref->evaluate().

reproducible with example:
$resource = curl_init();
curl_close($resource);
r($resource);

firefox isse

on firefox it shows only one instance or R correctly and all styles missing for the rest instances.

Chrome shows Ok.

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.