/ Gists / PHP

Gists - PHP

On gists

Magic Method: __invoke

PHP

wakeup.php #

<?php


class User {

    protected $name;  
    protected $timeline = array();

    public function __construct($name)  
    {  
        $this->name = $name;  
    }

    public function addTweet(Tweet $tweet)  
    {  
        $this->timeline[] = $tweet;  
    }

}

class Tweet {

    protected $id;  
    protected $text;  
    protected $read;

    public function __construct($id, $text)  
    {  
        $this->id = $id;  
        $this->text = $text;  
        $this->read = false;  
    }

    public function __invoke($user)  
    {  
        $user->addTweet($this);  
        return $user;  
    }

}

$users = array(new User('Ev'), new User('Jack'), new User('Biz'));  
$tweet = new Tweet(123, 'Hello world');  
$users = array_map($tweet, $users);

var_dump($users);

On gists

PHP DOM - saveHtml (solution without entities and html,body tags)

PHP PHP-PHPDOM

dom.php #

<?php
 
$string = '<div>ěščřžýáíé</div><p>testik</p> <p>testik2</p>';
 
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->loadHTML('<body>'.mb_convert_encoding($string, 'HTML-ENTITIES', 'UTF-8').'</body>');
 
// změny na $dom
 
echo substr($dom->saveHTML($dom->documentElement), 12, -14);

On gists

PHP CLI colors & getopts commands

PHP CLI

cli.php #

<?php

// https://www.supercoders.in/2019/07/php-command-line-php-parsing-program_16.html
// https://misc.flogisoft.com/bash/tip_colors_and_formatting
// https://joshtronic.com/2013/09/02/how-to-use-colors-in-command-line-output/

$longopts  = array(
    "required:",     // Required value
    "optional::",    // Optional value
    "option",        // No value
    "opt",           // No value
);

$options = getopt("", $longopts);

echo "\e[0;34;41mMerry Christmas!\e[0m\n";
echo "kunda";
echo "\033[31m some colored text \033[0m some white text \n";
echo  "Normal \e[5mBlink \n";
echo "Normal \e[1mBold \n";
echo "Default \e[33mYellow \n";


On gists

Microtime - rychlost měření php kódu

PHP

mereni.php #

<?php


function starttime() {
$r = explode( ' ', microtime() );
$r = $r[1] + $r[0];
return $r;
}

function endtime($starttime) {
$r = explode( ' ', microtime() );
$r = $r[1] + $r[0];
$r = round($r - $starttime,4);
return '<strong>Execution Time</strong>: '.$r.' seconds<br />';
}



$start = starttime();

$list = [1,2,3,4,5];

for ($i=0 ; $i< 1e5; $i++) {
    
	if (count($list))
	{
	}
}

echo endtime($start);



$start = starttime();

$list = [1,2,3,4,5];

for ($i=0 ; $i< 1e6; $i++) {
    
	if (!isset($x))
	{
		$x = [];
	}
}

echo endtime($start);

On gists

Distance between 2 points

PHP

distance.php #

<?php


echo get_distance(50.0598058, 14.3255396, 51.0769658, 13.6325016, 'Km');


function get_distance($latitude1, $longitude1, $latitude2, $longitude2, $unit = 'Mi') { 
    $theta = $longitude1 - $longitude2; 
    $distance = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + 
                (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * 
                cos(deg2rad($theta))); 
    $distance = acos($distance); 
    $distance = rad2deg($distance); 
    $distance = $distance * 60 * 1.1515; 
    switch($unit) { 
        case 'Mi': 
            break; 
        case 'Km' : 
            $distance = $distance * 1.609344; 
    } 
    return (round($distance,2)); 
}

On gists

Remove accents

PHP

remove.php #

<?php

function removeAccents($str)
{
    static $map = [
        // single letters
        'à' => 'a',
        'á' => 'a',
        'â' => 'a',
        'ã' => 'a',
        'ä' => 'a',
        'ą' => 'a',
        'å' => 'a',
        'ā' => 'a',
        'ă' => 'a',
        'ǎ' => 'a',
        'ǻ' => 'a',
        'À' => 'A',
        'Á' => 'A',
        'Â' => 'A',
        'Ã' => 'A',
        'Ä' => 'A',
        'Ą' => 'A',
        'Å' => 'A',
        'Ā' => 'A',
        'Ă' => 'A',
        'Ǎ' => 'A',
        'Ǻ' => 'A',


        'ç' => 'c',
        'ć' => 'c',
        'ĉ' => 'c',
        'ċ' => 'c',
        'č' => 'c',
        'Ç' => 'C',
        'Ć' => 'C',
        'Ĉ' => 'C',
        'Ċ' => 'C',
        'Č' => 'C',

        'ď' => 'd',
        'đ' => 'd',
        'Ð' => 'D',
        'Ď' => 'D',
        'Đ' => 'D',


        'è' => 'e',
        'é' => 'e',
        'ê' => 'e',
        'ë' => 'e',
        'ę' => 'e',
        'ē' => 'e',
        'ĕ' => 'e',
        'ė' => 'e',
        'ě' => 'e',
        'È' => 'E',
        'É' => 'E',
        'Ê' => 'E',
        'Ë' => 'E',
        'Ę' => 'E',
        'Ē' => 'E',
        'Ĕ' => 'E',
        'Ė' => 'E',
        'Ě' => 'E',

        'ƒ' => 'f',


        'ĝ' => 'g',
        'ğ' => 'g',
        'ġ' => 'g',
        'ģ' => 'g',
        'Ĝ' => 'G',
        'Ğ' => 'G',
        'Ġ' => 'G',
        'Ģ' => 'G',


        'ĥ' => 'h',
        'ħ' => 'h',
        'Ĥ' => 'H',
        'Ħ' => 'H',

        'ì' => 'i',
        'í' => 'i',
        'î' => 'i',
        'ï' => 'i',
        'ĩ' => 'i',
        'ī' => 'i',
        'ĭ' => 'i',
        'į' => 'i',
        'ſ' => 'i',
        'ǐ' => 'i',
        'Ì' => 'I',
        'Í' => 'I',
        'Î' => 'I',
        'Ï' => 'I',
        'Ĩ' => 'I',
        'Ī' => 'I',
        'Ĭ' => 'I',
        'Į' => 'I',
        'İ' => 'I',
        'Ǐ' => 'I',

        'ĵ' => 'j',
        'Ĵ' => 'J',

        'ķ' => 'k',
        'Ķ' => 'K',


        'ł' => 'l',
        'ĺ' => 'l',
        'ļ' => 'l',
        'ľ' => 'l',
        'ŀ' => 'l',
        'Ł' => 'L',
        'Ĺ' => 'L',
        'Ļ' => 'L',
        'Ľ' => 'L',
        'Ŀ' => 'L',


        'ñ' => 'n',
        'ń' => 'n',
        'ņ' => 'n',
        'ň' => 'n',
        'ʼn' => 'n',
        'Ñ' => 'N',
        'Ń' => 'N',
        'Ņ' => 'N',
        'Ň' => 'N',

        'ò' => 'o',
        'ó' => 'o',
        'ô' => 'o',
        'õ' => 'o',
        'ö' => 'o',
        'ð' => 'o',
        'ø' => 'o',
        'ō' => 'o',
        'ŏ' => 'o',
        'ő' => 'o',
        'ơ' => 'o',
        'ǒ' => 'o',
        'ǿ' => 'o',
        'Ò' => 'O',
        'Ó' => 'O',
        'Ô' => 'O',
        'Õ' => 'O',
        'Ö' => 'O',
        'Ø' => 'O',
        'Ō' => 'O',
        'Ŏ' => 'O',
        'Ő' => 'O',
        'Ơ' => 'O',
        'Ǒ' => 'O',
        'Ǿ' => 'O',


        'ŕ' => 'r',
        'ŗ' => 'r',
        'ř' => 'r',
        'Ŕ' => 'R',
        'Ŗ' => 'R',
        'Ř' => 'R',


        'ś' => 's',
        'š' => 's',
        'ŝ' => 's',
        'ş' => 's',
        'Ś' => 'S',
        'Š' => 'S',
        'Ŝ' => 'S',
        'Ş' => 'S',

        'ţ' => 't',
        'ť' => 't',
        'ŧ' => 't',
        'Ţ' => 'T',
        'Ť' => 'T',
        'Ŧ' => 'T',


        'ù' => 'u',
        'ú' => 'u',
        'û' => 'u',
        'ü' => 'u',
        'ũ' => 'u',
        'ū' => 'u',
        'ŭ' => 'u',
        'ů' => 'u',
        'ű' => 'u',
        'ų' => 'u',
        'ư' => 'u',
        'ǔ' => 'u',
        'ǖ' => 'u',
        'ǘ' => 'u',
        'ǚ' => 'u',
        'ǜ' => 'u',
        'Ù' => 'U',
        'Ú' => 'U',
        'Û' => 'U',
        'Ü' => 'U',
        'Ũ' => 'U',
        'Ū' => 'U',
        'Ŭ' => 'U',
        'Ů' => 'U',
        'Ű' => 'U',
        'Ų' => 'U',
        'Ư' => 'U',
        'Ǔ' => 'U',
        'Ǖ' => 'U',
        'Ǘ' => 'U',
        'Ǚ' => 'U',
        'Ǜ' => 'U',


        'ŵ' => 'w',
        'Ŵ' => 'W',

        'ý' => 'y',
        'ÿ' => 'y',
        'ŷ' => 'y',
        'Ý' => 'Y',
        'Ÿ' => 'Y',
        'Ŷ' => 'Y',

        'ż' => 'z',
        'ź' => 'z',
        'ž' => 'z',
        'Ż' => 'Z',
        'Ź' => 'Z',
        'Ž' => 'Z',


        // accentuated ligatures
        'Ǽ' => 'A',
        'ǽ' => 'a',
    ];
    return strtr($str, $map);
}

On gists

Iteration and Recursive Iteration Examples Code

PHP

iteration-and-recursive-iteratio #

<?php
/*
* Iteration and Recursive Iteration Examples Code
*
* @link http://stackoverflow.com/questions/12077177/how-does-recursiveiteratoriterator-works-in-php
* @author hakre <http://hakre.wordpress.com>
*/

### To have these examples to work, a directory with subdirectories is needed,
### I named mine "tree":

$path = 'tree';


/**
 * Example 1: DirectoryIterator
 */
$dir = new DirectoryIterator($path);

echo "[$path]\n";
foreach ($dir as $file) {
    echo " ├ $file\n";
}


/**
 * Example 2: IteratorIterator
 */
$files = new IteratorIterator($dir);

echo "[$path]\n";
foreach ($files as $file) {
    echo " ├ $file\n";
}


/**
 * Example 3: RecursiveDirectoryIterator
 */
$dir = new RecursiveDirectoryIterator($path);

echo "[$path]\n";
foreach ($dir as $file) {
    echo " ├ $file\n";
}


/**
 * Example 4: RecursiveIteratorIterator
 */
$files = new RecursiveIteratorIterator($dir);

echo "[$path]\n";
foreach ($files as $file) {
    echo " ├ $file\n";
}


/**
 * Example 5: Meta-Information
 */
echo "[$path]\n";
foreach ($files as $file) {
    $indent = str_repeat('   ', $files->getDepth());
    echo $indent, " ├ $file\n";
}


/**
 * Example 6: Recursion Mode
 */
$dir   = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::SELF_FIRST);

echo "[$path]\n";
foreach ($files as $file) {
    $indent = str_repeat('   ', $files->getDepth());
    echo $indent, " ├ $file\n";
}


/**
 * Appendix: Nicely Formatted Directory Listings (as used in the answer)
 */
$unicodeTreePrefix = function(RecursiveTreeIterator $tree)
{
    $prefixParts = [
        RecursiveTreeIterator::PREFIX_LEFT         => ' ',
        RecursiveTreeIterator::PREFIX_MID_HAS_NEXT => '│ ',
        RecursiveTreeIterator::PREFIX_END_HAS_NEXT => '├ ',
        RecursiveTreeIterator::PREFIX_END_LAST     => '└ '
    ];
    foreach ($prefixParts as $part => $string) {
        $tree->setPrefixPart($part, $string);
    }
};

$dir  = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::KEY_AS_FILENAME | RecursiveDirectoryIterator::SKIP_DOTS);
$tree = new RecursiveTreeIterator($dir);
$unicodeTreePrefix($tree);

### non-recursive and recursive listing
foreach ([0, -1] as $level) {
    $tree->setMaxDepth($level);
    echo "[$path]\n";
    foreach ($tree as $filename => $line) {
        echo $tree->getPrefix(), $filename, "\n";
    }
}


/**
 * Appendix: Do It Yourself: Make the `RecursiveTreeIterator` Work Line by Line.
 */
$dir   = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS);
$lines = new RecursiveTreeIterator($dir);
$unicodeTreePrefix($lines);
echo "[$path]\n", implode("\n", iterator_to_array($lines));

echo "

/// Solution Suggestion ///

";
@include('recursive-directory-iterator-solution.php');

$lines = new RecursiveTreeIterator(
    new DiyRecursiveDecorator($dir)
);
$unicodeTreePrefix($lines);
echo "[$path]\n", implode("\n", iterator_to_array($lines));

On gists

PHP - sleep, outputbuffer (fake loading)

PHP

sleep.php #

<?php

if (ob_get_level() == 0) ob_start();

for ($i = 0; $i<10; $i++){

        echo "<br> $i Line to show.";
        echo str_pad('',4096)."\n";   

        ob_flush();
        flush();
        sleep(1);
}

echo "<br> Done.";

ob_end_flush();

On gists

Csv to UTF-8

PHP

csv.php #

<?php

	$csv = file_get_contents(INDEX_DIR . '/../temp/slozky-csv.csv');
	$csv = iconv("windows-1250//TRANSLIT//IGNORE", 'utf-8', $csv);
	$csv = explode("\n", $csv);

On gists

Recursive array walk with replace

PHP

recursive.php #

<?php

	protected function parseQueryData(&$array, $data) 
	{
		array_walk_recursive($array, function(&$item, $key) use ($data) 
		{
			if(substr($item, 0, 1) == '%') 
			{
				$item = $data[substr($item, 1)];
			}
		});
	}