Skip to content

Instantly share code, notes, and snippets.

@anwas
Last active October 10, 2020 00:50
Show Gist options
  • Save anwas/37de1cbd4967d7e447a16546895d48c3 to your computer and use it in GitHub Desktop.
Save anwas/37de1cbd4967d7e447a16546895d48c3 to your computer and use it in GitHub Desktop.
[Helpers functions class]
<?php
/**
* Anwp_Debug_Helpers class
*
* @package Anwp_App
*/
declare( strict_types = 1 );
namespace Anwp_App;
/**
* Class for custom helpers (debuging) functions.
*
* Usage:
namespace Anwp_App;
if ( ! function_exists( 'h' ) ) {
function h() {
return new Anwp_Debug_Helpers();
}
}
* After function create:
* * `h()->action_print_device_pixel_ratio_script()`
* * `h()->action_print_viewport_size_script()`
* * `h()->get_user_ip()`
* * `h()->get_pp( $value )`
* * `h()->get_vep( $value )`
* * `h()->get_vdp( $value )`
* * `h()->pp( $value, bool $is_escape = false, $display_fileinfo = false )`
* * `h()->vep( $value, bool $is_escape = false, $display_fileinfo = false )`
* * `h()->vdp( $value, bool $is_escape = false, $display_fileinfo = false )`
* * `h()->script_run_time( $start_time = null )`
* * `h()->esc_html( $value )`
* * `h()->wp_strip_all_tags( $string, $remove_breaks = false )`
*/
class Anwp_Debug_Helpers {
/**
* Prints an inline script to display Device Pixel Ration.
*
* The script is not enqueued because it is tiny.
*/
public function action_print_device_pixel_ratio_script() {
?>
<script>
const canvasEL = document.createElement( 'canvas' );
const entryContent = document.querySelectorAll( '#device-pixel-ratio' );
entryContent[0].append( canvasEL );
const canvasElStyles = {
position: 'relative',
left: '50%',
margin: 'auto',
transform: 'perspective(1px) translateX(-50%)'
};
Object.assign( canvasEL.style, canvasElStyles );
// let canvas = document.getElementById('canvas');
let canvas = canvasEL;
let ctx = canvas.getContext('2d');
// Set display size (css pixels).
let size = 360;
let fontSize = 42;
canvas.style.width = size + "px";
canvas.style.height = size + "px";
// Set actual size in memory (scaled to account for extra pixel density).
let scale = window.devicePixelRatio; // Change to 1 on retina screens to see blurry canvas.
canvas.width = size * scale;
canvas.height = size * scale;
// Normalize coordinate system to use css pixels.
ctx.scale(scale, scale);
ctx.fillStyle = "#bada55";
ctx.fillRect(10, 10, 350, 350);
ctx.fillStyle = "#ffffff";
ctx.font = fontSize + 'px Arial';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
let x = size / 2;
let y = size / 2;
let textString = "Scale: " + scale;
let textString2 = "Css width: " + ( screen.width );
let textString3 = "Css height: " + ( screen.height );
let y1 = y - ( fontSize * 2.25 );
let y3 = y + ( fontSize * 2 );
ctx.fillText(textString, x, y1);
ctx.fillText(textString2, x, y);
ctx.fillText(textString3, x, y3);
</script>
<?php
}
/**
* Prints an inline script to display Viewport Size.
*
* Script to display the viewport size when working on responsive stuff.
* Adpted to vanilla JS by: Taylor Hunt - https://codepen.io/tigt/
*
* The script is not enqueued because it is tiny.
*/
public function action_print_viewport_size_script() {
?>
<script>
const EL = document.createElement( 'output' );
let elStyles = {};
document.body.append( EL );
const isAdminBar = document.querySelector( '.admin-bar' );
console.log( isAdminBar );
function updateOutput() {
var html = document.documentElement;
if (window.matchMedia("(max-width: 782px)").matches) {
/* The viewport is less than, or equal to, 782 pixels wide */
elStyles = {
position: 'fixed',
bottom: ( isAdminBar ) ? '46px' : 0,
left: 0,
background: '#0f0f0f',
color: '#f0f0f0',
padding: '3px 3px 2px',
margin: '0px',
lineHeight: '11px',
fontFamily: 'Arial, Helvetica, sans-serif',
fontSize: '11px',
opacity: 0.7,
// transformOrigin: 'top left',
// transform: 'rotate(-90deg)'
};
} else {
/* The viewport is greater than 782 pixels wide */
elStyles = {
position: 'fixed',
bottom: ( isAdminBar ) ? '32px' : 0,
left: 0,
background: '#0f0f0f',
color: '#f0f0f0',
padding: '3px 3px 2px',
margin: '0px',
lineHeight: '11px',
fontFamily: 'Arial, Helvetica, sans-serif',
fontSize: '11px',
opacity: 0.7,
// transformOrigin: 'top left',
// transform: 'rotate(-90deg)'
};
}
Object.assign( EL.style, elStyles );
EL.value = html.clientWidth + ' × ' + html.clientHeight;
}
window.addEventListener( 'resize', updateOutput );
updateOutput();
</script>
<?php
}
/**
* Gauti naudotojo IP
*
* @return string $ip IP address.
*********************************************************************/
public function get_user_ip() : string {
if ( isset( $_SERVER ) && ! empty( $_SERVER ) ) {
$client = isset( $_SERVER['HTTP_CLIENT_IP'] ) ? stripslashes( $_SERVER['HTTP_CLIENT_IP'] ) : false; // phpcs:ignore
$forward = isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ? stripslashes( $_SERVER['HTTP_X_FORWARDED_FOR'] ) : false; // phpcs:ignore
$remote = stripslashes( $_SERVER['REMOTE_ADDR'] ); // phpcs:ignore
} else {
$client = false;
$forward = false;
$remote = false;
}
if ( filter_var( $client, FILTER_VALIDATE_IP ) ) {
$ip = $client;
} elseif ( filter_var( $forward, FILTER_VALIDATE_IP ) ) {
$ip = $forward;
} else {
$ip = $remote;
}
return (string) $ip;
}
/**
* Gauname kintamąjį aiškioje peržiūrai formoje
*
* @param mixed $value Reikšmė (object, array, string etc.).
* @return string
*/
public function get_pp( $value ) : string {
return print_r( $value, true ); // phpcs:ignore
}
/**
* Gauname kintamąjį aiškioje peržiūrai formoje
*
* @param mixed $value Reikšmė (object, array, string etc.).
* @return string
*/
public function get_vep( $value ) : string {
ob_start();
var_export( $value ); // phpcs:ignore
$o = ob_get_clean();
$output = ( false !== $o ) ? $o : 'Negauta jokių rezultatų';
return $output;
}
/**
* Gauname kintamąjį aiškioje peržiūrai formoje
*
* @param mixed $value Reikšmė (object, array, string etc.).
* @return string
*/
public function get_vdp( $value ) : string {
ob_start();
var_dump( $value ); // phpcs:ignore
$o = ob_get_clean();
$output = ( false !== $o ) ? $o : 'Negauta jokių rezultatų';
return $output;
}
/**
* Suformuojama derinimo išvedimo eilutė.
*
* @param string $output Derinimo informacios eilute.
* @param string $fileinfo Informacija apie failą iš kurio iškviesta derinimo funkcija.
* @param boolean $is_escape Ar naudoti esc_html() funkciją.
* @return string
*/
private function get_output_string( $output, string $fileinfo = '', bool $is_escape = false ) : string {
$output_str = '';
$open_tags = '<pre style="margin: 0; padding: 0.5rem; white-space: pre-wrap;"><code style="font-size: 0.85rem;">';
$close_tags = '</code></pre>';
$output_str .= '<div style="box-shadow: 0 2px 8px 3px rgba( 0, 0, 0, 0.5 ); background: #f3f3f3;">';
if ( ! empty( $fileinfo ) ) {
$output_str .= '<div style="background: #0f0f0f; color: #f0f0f0; padding: 0.25rem; font-family: monospace; font-size: 12px;">';
$output_str .= $fileinfo;
$output_str .= '</div>';
}
$output_str .= $open_tags;
// WordPress aplinkoje galima naudoti ir wp_strip_all_tags() funkciją (veikia kitaip, nei esc_html()).
// Žiūrėti https://developer.wordpress.org/reference/functions/wp_strip_all_tags/ .
$output_str .= ( true === $is_escape ) ? $this->esc_html( $output ) : $output;
$output_str .= $close_tags;
$output_str .= '</div>';
return $output_str;
}
/**
* Išvedame kintamąjį aiškioje peržiūrai formoje
*
* @param mixed $value Reikšmė (object, array, string etc.).
* @param boolean $is_escape Ar naudoti esc_html() funkciją.
* @param boolean $display_fileinfo Ar rodyti informaciją iš kurio failo iškviestą funkcija.
* @return void
*/
public function pp( $value, bool $is_escape = false, bool $display_fileinfo = false ) {
if ( true === $display_fileinfo ) {
$fileinfo = 'negauta informacijos apie failą';
$backtrace = debug_backtrace(); // phpcs:ignore
// Gauname failą ir eilutę iš kur iškviesta derinimo funkcija.
if ( ! empty( $backtrace[0] ) && is_array( $backtrace[0] ) ) {
$fileinfo = $backtrace[0]['file'] . ':' . $backtrace[0]['line'];
}
} else {
$fileinfo = '';
}
echo $this->get_output_string( $this->get_pp( $value ), $fileinfo, $is_escape ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
/**
* Išvedame kintamąjį aiškioje peržiūrai formoje
*
* @param mixed $value Reikšmė (object, array, string etc.).
* @param boolean $is_escape Ar naudoti esc_html() funkciją.
* @param boolean $display_fileinfo Ar rodyti informaciją iš kurio failo iškviestą funkcija.
* @return void
*/
public function vep( $value, bool $is_escape = false, bool $display_fileinfo = false ) {
if ( true === $display_fileinfo ) {
$fileinfo = 'negauta informacijos apie failą';
$backtrace = debug_backtrace(); // phpcs:ignore
// Gauname failą ir eilutę iš kur iškviesta derinimo funkcija.
if ( ! empty( $backtrace[0] ) && is_array( $backtrace[0] ) ) {
$fileinfo = $backtrace[0]['file'] . ':' . $backtrace[0]['line'];
}
} else {
$fileinfo = '';
}
echo $this->get_output_string( $this->get_vep( $value ), $fileinfo, $is_escape ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
/**
* Išvedame kintamąjį aiškioje peržiūrai formoje
*
* @param mixed $value Reikšmė (object, array, string etc.).
* @param boolean $is_escape Ar naudoti esc_html() funkciją.
* @param boolean $display_fileinfo Ar rodyti informaciją iš kurio failo iškviestą funkcija.
* @return void
*/
public function vdp( $value, bool $is_escape = false, bool $display_fileinfo = false ) {
if ( true === $display_fileinfo ) {
$fileinfo = 'negauta informacijos apie failą';
$backtrace = debug_backtrace(); // phpcs:ignore
// Gauname failą ir eilutę iš kur iškviesta derinimo funkcija.
if ( ! empty( $backtrace[0] ) && is_array( $backtrace[0] ) ) {
$fileinfo = $backtrace[0]['file'] . ':' . $backtrace[0]['line'];
}
} else {
$fileinfo = '';
}
echo $this->get_output_string( $this->get_vdp( $value ), $fileinfo, $is_escape ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
/**
* Gauti scenarijaus vykdymo trukmę
*
* @param mixed null/int $start_time Null arba scenarijaus vykdymo pradžios timestamp žyma.
* @return mixed
*/
public function script_run_time( $start_time = null ) : string {
$now = (float) microtime( true );
if ( isset( $_SERVER['REQUEST_TIME_FLOAT'] ) ) {
// As of PHP 5.4.0, REQUEST_TIME_FLOAT is available in the $_SERVER superglobal array.
// It contains the timestamp of the start of the request with microsecond precision.
return (string) ( $now - (float) $_SERVER['REQUEST_TIME_FLOAT'] );
} elseif ( ! is_null( $start_time ) ) {
return (string) ( $now - $start_time );
} else {
return '';
}
}
/**
* Convert special characters to HTML entities.
*
* @param string $value Eilutė, kurią reikia konvertuoti.
* @return string
*/
public function esc_html( $value ) {
if ( function_exists( 'esc_html' ) ) {
return esc_html( $value );
} elseif ( ! is_array( $value ) && ! is_object( $value ) ) {
return htmlspecialchars( trim( $value ), ENT_QUOTES, 'UTF-8', false );
} else {
return 'Perduotas parametras NĖRA eilutė (string)';
}
}
/**
* Properly strip all HTML tags including script and style
*
* This differs from strip_tags() because it removes the contents
* of the <script> and <style> tags. E.g. strip_tags( '<script>something</script>' )
* will return ‘something’. wp_strip_all_tags will return ”.
*
* @param string $string Perduodama eilutė.
* @param boolean $remove_breaks Ar panaiginti eilutės lūžius.
* @return string Išvalyta eilutė.
*/
public function wp_strip_all_tags( $string, $remove_breaks = false ) {
if ( function_exists( 'wp_strip_all_tags' ) ) {
return wp_strip_all_tags( $string, $remove_breaks );
}
$string = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $string );
$string = strip_tags( $string ); // phpcs:ignore
if ( $remove_breaks ) {
$string = preg_replace( '/[\r\n\t ]+/', ' ', $string );
}
return trim( $string );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment