Code Monkey home page Code Monkey logo

dump_r.php's Introduction

dump_r()

a cleaner, leaner mix of print_r() and var_dump() (MIT Licensed)

screenshot

Installing

Composer

https://packagist.org/packages/leeoniya/dump-r

{
	"require": {
		"leeoniya/dump-r": "dev-master"
	}
}

Require

require 'dump_r.php';

Using & Config

Use dump_r() as a drop-in replacement for print_r() and var_dump(). It has some additional arguments that control output. The full signature of the function is:

function dump_r($value, $return = false, $html = true, $depth = 1e3, $expand = 1e3);
  • $value is the thing you want to dump
  • $return determines whether to return the dump rather than output to screen
  • $html controls whether the output is text or html
  • $depth sets the recursion limit for the dump
  • $expand sets the auto-expanded child node depth

There are also two modifier keys that can be used to control how the node expanding/collapsing works:

  1. Holding Shift while toggling will expand/collapse the full depth of the node.
  2. Hold Ctrl while toggling will expand/collapse all siblings after that node also. This is useful if you have an array of objects/arrays and want to expand all of them to one level simultaneously by clicking just the first one in the group. It works well for deep, complex objects.
  3. Shift and Ctrl can be used together.

Double-clicking binary strings will toggle them between mixed hex/ascii and hex-only representations:

binary_toggle

Some types of strings can be pretty-printed and additonal rendering options can be tweaked (shown with defaults):

dump_r\Rend::$xml_pretty	= false;	// pretty-print xml strings
dump_r\Rend::$json_pretty	= false;	// pretty-print json strings
dump_r\Rend::$sql_pretty	= false;	// pretty-print sql strings (requires https://github.com/jdorn/sql-formatter)
dump_r\Rend::$recset_tbls	= true;		// recordset detection & table-style output
dump_r\Rend::$trace_info	= true;		// show file & line where dump_r was invoked
dump_r\Rend::$val_space		= 4;		// number of spaces between key and value columns (affects text output only, not html)

Circular reference (recursion) detection and duplicate output is indicated like this for arrays, objects, closures and resources respectively: [*],{*},(*),<*>.

You can re-style all aspects of the html output using CSS, everything is class-tagged.

Extending

Adding your own classifiers & parsers is extremely easy. Here are instructions and two concrete examples of how the String base type can be subtyped. First for displaying EXIF data of jpeg and tiff image paths and then showing row data from CSV file paths.

This array

$stuff = [
	'imgs/img_1771.jpg',
	'data/people.csv',
];

Which would normally dump like this:

coretyped

Can be dumped like this with subtyping:

usertyped

To do this, hook the correct core type and provide a function that classifies and processes the raw value, then modifies and returns an instance of Type. Here are the properties that can be modified/augmented:

  1. $type->types - Array of subtype string(s) of your choice. These get appended as CSS classes and are also displayed inline.
  2. $type->nodes - Array of expandable subnodes to display. Provide null if no subnodes are needed or to retain any subnodes extracted by the core type.
  3. $type->length - A string to be displayed at the end of the line, indicating length of subnodes. You can also abuse this param to display other length-esque information (the EXIF example below uses it to display image dimensions inline). Provide null to retain the default length display for the hooked core type.
use dump_r\Type;

// Example 1: dump EXIF data with image filepath strings

Type::hook('_String', function($raw, Type $type, $path) {
	// match path-esque strings (containing '/' or '\') trailed by an
	// EXIF-capable image extension, then verify this file actually exists
	if (preg_match('#[\/]+.+\.(jpe?g|tiff?)$#', $raw) && is_file($raw)) {
		$nodes = $exif = exif_read_data($raw, 0, true);
		$len = $exif['COMPUTED']['Width'] . 'x' . $exif['COMPUTED']['Height'];

		$type->types	= ['image'];
		$type->nodes	= ['EXIF' => $nodes['EXIF']];
		$type->length	= $len;

		return $type;
	}
});

// Example 2: dump CSV records with csv filepath strings

Type::hook('_String', function($raw, Type $type, $path) {
	if (preg_match('#[\/]+.+\.csv$#', $raw) && is_file($raw)) {

		$type->types	= ['csv'];
		$type->nodes	= csv2array($raw);
		$type->length	= count($type->nodes);

		return $type;
	}
});

function csv2array($file) {
	$csv = [];
	$rows = array_map('str_getcsv', file($file));
	$header = array_shift($rows);
	foreach ($rows as $row)
		$csv[] = array_combine($header, $row);
	return $csv;
}

All core types (see src/dump_r/Node dir) can be hooked by their fully namespaced names. For example, if you wanted to further subtype a JSON object string, you would use

Type::hook('_String\\_JSON\\_Object', function($raw, Type $type, $path) {
	// code here
});

Filtering, Marking & Recursion Control

Using the same Type hooks (introduced above) allows you to modify additional aspects of the renderer and iterator.

Skip specific nodes based on their properties or path in the hierarchy

// prevent anything keyd under 'xxx' from dumping
Type::hook('*', function($raw, Type $type, $path) {
	if (end($path) === 'xxx')
		return false;
});

Stop recursion of specific nodes

// prevent arrays keyed under 'c' from dumping sub-nodes
Type::hook('_Array', function($raw, Type $type, $path) {
	if (end($path) === 'c')
		$type->depth = 1;

	return $type;
});

CSS-tag nodes via classes

// tag nodes keyed under `yyy` with addl CSS classes
Type::hook('*', function($raw, Type $type, $path) {
	if (end($path) === 'yyy') {
		$type->classes[] = 'marked';
	}

	return $type;
});

dump_r.php's People

Contributors

leeoniya 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

dump_r.php's Issues

assoc array bug

Hello,
this kind of array

$obj = [
  [
    'id' => 1,
    'unit' => 11,
    'action' => 21,
  ],
  [
    'id' => 2,
    'unit' => 12,
    'action' => 22,
  ],
  [
    'id' => 4,
    'unit' => 14,
    'comment' => 'xxx',
    'action' => 24,
  ],
];

renders in HTML as
2015-07-14 12-57-48 test2 local dump_r test index php - google chrome

provide more info about callbacks when possible

simple fn() is insufficient for some callables, especially when more detail is provided as strings within the original.

http://php.net/manual/en/language.types.callable.php

array('myClass','method');
array('myClass', 'parent::method');
'myClass::method';

should output fn() [myClass,method] or similar

array($obj, 'method')
$a = function(){};

should output something fn() [<obj>, method] and fn() [closure]

need to think of something more uniform...

option to expand resources

expand mysql resources as a <table>
expand streams as <pre>

all with configurable limits on chars or records

detect homogenous collections

when the final result is a complex object or assoc array (which can be either one or multiple objects) like SimpleXML, JSON, JSONH - detect uniform nodes and treat homogenous collections as arrays to show length and dump children appropriately.

detect array references + infinite array recursions

PHP sucks, and provides no way to do this. even hacking it by using print_r or serialize only tells you if there is recursion, but not where.

http://stackoverflow.com/questions/9042142/detecting-infinite-array-recursion-in-php

https://bugs.php.net/bug.php?id=51533

http://noteslog.com/post/detecting-recursive-dependencies-in-php-composite-values/

// recursion
$arr    = array();
$arr    = array(&$arr);

// references
$moo = array();
$arr = array();
$arr[] = &$moo;
$arr[] = &$moo;
var_dump($arr);

Why pass by by reference

Hello, I would like to know what is the rationale for dump_r to accept its first parameter as a refenrence dump_r(&$raw, ...).

Is that for performances reasons ? It prevent's users from calling dump_r(getSomeValue()).

Thank you.

expand/collaspe all

This would be really cool. Thank you very much for this project its amazing

Provide a way to pass-in the name of the "input parameter" and calling file

I'm working on a Drupal logging module that wraps dump_r. For that module, dump_r is actually getting invoked by the logging API. Consequently, I'd love it if it would be possible for the code that detects the calling file and the name of the variable being passed-in to dump_r was a bit more configurable and/or a separate component.

Right now, it always logs the name of the variable the logging API uses to print a value, instead of the name of the variable passed-in to the logger. In addition, the calling file ends up always being Logger.php instead of the actual caller in the code invoking the Logger.

switch to font coloring rather than background coloring

so this has bugged me for a long time.

the main reason for using (ugly) background colors rather than text colors is the inability to show leading/trailing whitespace for strings. this can be worked around in several ways.

already, an entirely empty string uses an gray "middle dot".

/* display empty strings as a gray middle dot */
.dump_r .empty.string:not(.numeric) > .lbl .val:after {
    content: "\0387";
    color: #BBBBBB;
}

in addition, there is a trailing/leading right and left border that's added if the string is indicated as having leading/trailing spaces.

the key goal is to have the string copy-able to the clipboard in the exact form it was originally and that it be very obvious visually if there are trailing or leading spaces since they're frequently a huge source of time-consuming debugging for trivial reasons. one idea is just to render a color background only for leading/trailing spaces which means splitting them off into a separate div/span.

perhaps in combination with #49, it should be possible to move the default theme away from using the jarring background colors, or at least provide a workable alternative with no sacrifices.

Great library, need "class" support...

Love your library, great work, thanks for providing this for free!

One thing I am needing is the formatting of "class" objects... when I try to dump an class instance using your library all I get is the name of the class... such as:

image

Anything I can do to make it display this or have you just not gotten to displaying this output as of yet?

Thanks!
Patrick

Please tag stable versions

I'm using your project in one of mine and the integration tests just failed because dump-r switched to PHP 5.4 and we're still stuck with PHP 5.3.

I would not have a problem with that, as I can simply require an older version of your library (dev-master#5c8602e). The problem is that Composer seems to clone the master branch first and check its composer.json, telling me that I need PHP 5.4.

I would highly appreciate tagged versions, including one tagged version for PHP 5.3.x.

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.