/ Gists / PHP

Gists - PHP

On gists

Lamba & Closures

PHP

demo1.php #

<?php

function getMultiplier($product)
{
	echo "kolikrat se spusti?"; // jen 1
	
    return function ($value) use ($product) {
        return $value * $product;
    };
}

// $multi23 je "násobička 23"
$multi23 = getMultiplier(23);
echo $multi23(1);
echo $multi23(2);
echo $multi23(3); 
echo $multi23(4);

On gists

České řazení / czech sorting

PHP

sorting.php #

<?php
setlocale(LC_COLLATE, 'cs_CZ.utf8');
$cities = [
    158 => "Ženeva",
    52 => "Zanzibar",
    200 => "Česká Lípa",
    33 => "Praha"
];
uasort($cities, 'strcoll');
$form->addSelectBox->('cities', 'cities', $cities);

On gists

PHPDOM - examples

PHP PHP-PHPDOM

responsive-images.php #

  // Create a DOMDocument
  $dom = new DOMDocument();
	
  // Load html including utf8, like Hebrew
  $dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
	
  // Create the div wrapper
  $div = $dom->createElement('div');
  $div->setAttribute('class', 'responsive-img');
	
  // Get all the images
  $images = $dom->getElementsByTagName('img');
 
  // Loop the images
  foreach ($images as $image) 
  {
    //Clone our created div
    $new_div_clone = $div->cloneNode();
		
    //Replace image with wrapper div
    $image->parentNode->replaceChild($new_div_clone,$image);
		
    //Append image to wrapper div
    $new_div_clone->appendChild($image);
  }
	
  // Save the HTML
  $html = $dom->saveHTML();
	
  return $html;

On gists

Extending the SimpleXMLElement

PHP

betterxml.function.php #

<?php 
/**
 * Giving myself more functionality over this bit
 * 
 * @author byrd
 *
 */
class BetterXML extends SimpleXMLElement
{
    /**
     * 
     */
    public function parentNode() {
        $parent = current($this->xpath('parent::*'));
        return $parent;
    }
    
    /**
     * 
     * @param unknown_type $sametag
     */
    function getSiblings( $sametag = false ) {
        if ($sametag) {
            $sametag = $this->getName();
        }
        if (!$sametag)
            $sametag = '*';
        return $this->xpath("preceding-sibling::$sametag | following-sibling::$sametag");
    }
    
    /**
     * 
     * @param unknown_type $sametag
     */
    function getSiblingsToo( $sametag = false ) {
        if ($sametag) {
            $sametag = $this->getName();
        }
        if (!$sametag)
            $sametag = '*';
        return $this->xpath("preceding-sibling::$sametag | following-sibling::$sametag | .");
    }
    
    /**
     * 
     * @param unknown_type $key
     * @param unknown_type $value
     */
    public function addChild($key, $value=null)
    {
        $value = str_replace('&', '&amp;', $value);
        return parent::addChild($key, $value);
    }
    
    /**
     * Add CDATA text in a node
     * @param string $cdata_text The CDATA value  to add
     */
    private function addCData($cdata_text)
    {
        $node= dom_import_simplexml($this);
        $no = $node->ownerDocument;
        $node->appendChild($no->createCDATASection($cdata_text));
    }
    
    /**
     * 
     * @param unknown_type $add
     */
    public function extend( $add )
    {
        if ( $add->count() != 0 )
            $new = $this->addChild($add->getName());
        else
            $new = $this->addChild($add->getName(), $add);
        foreach ($add->attributes() as $a => $b)
        {
            $new->addAttribute($a, $b);
        }
        if ( $add->count() != 0 )
        {
            foreach ($add->children() as $child)
            {
                $new->extend($child);
            }
        }
    }
    
    /** 
    * remove a SimpleXmlElement from it's parent 
    * @return $this 
    */ 
    public function remove()
    {
        $node = dom_import_simplexml($this);
        $node->parentNode->removeChild($node); 
        return $this; 
    } 
    
    /**
     * remove given SimpleXmlElement from current element
     * @return $this
     */
    public function removeChild(SimpleXMLElement $child)
    {
        $node = dom_import_simplexml($this);
        $child = dom_import_simplexml($child);
        $node->removeChild($child);
        return $this;
    }
    
    /** 
     * replace current element with another SimpleXmlElement 
     * @param SimpleXmlElement $replaceElmt passed by reference 
     *        (must be done if we want further modification to the $replaceElmt element to be applyed to the document) 
     * @return $this 
     */ 
    public function replace(SimpleXmlElement &$replaceElmt)
    { 
        list($node,$_replaceElmt) = self::getSameDocDomNodes($this,$replaceElmt); 
        $node->parentNode->replaceChild($_replaceElmt,$node); 
        $replaceElmt = simplexml_import_dom($_replaceElmt); 
        return $this; 
    } 
    
    /**
     * replace a child SimpleXmlElement with another SimpleXmlElement
     * @param SimpleXmlElement $newChild passed by reference
     *        (must be done if we want further modification to the newChild element to be applyed to the document)
     * @param SimpleXmlElement $oldChild
     * @return $this
     */
    public function replaceChild(SimpleXmlElement &$newChild,SimpleXmlElement $oldChild)
    {
        list($oldChild,$_newChild) = self::getSameDocDomNodes($oldChild,$newChild);
        $oldChild->parentNode->replaceChild($_newChild,$oldChild);
        $newChild= simplexml_import_dom($_newChild);
        return $this;
    }
    
    /**
     * static utility method to get two dom elements and ensure that the second is part of the same document than the first given.
     * @param SimpleXmlElement $node1
     * @param SimpleXmlElement $node2
     * @return array(DomElement,DomElement)
     */
    static public function getSameDocDomNodes(SimpleXMLElement $node1,SimpleXMLElement $node2)
    {
        $node1 = dom_import_simplexml($node1);
        $node2 = dom_import_simplexml($node2);
        if(! $node1->ownerDocument->isSameNode($node2->ownerDocument) )
            $node2 = $node1->ownerDocument->importNode($node2, true);
        return array($node1,$node2);
    }
    
    /**
     * 
     * @param unknown_type $name
     * @param unknown_type $value
     */
    public function prependChild($name, $value)
    {
        $dom = dom_import_simplexml($this);
        $new = $dom->insertBefore(
            $dom->ownerDocument->createElement($name, $value),
            $dom->firstChild
        );
        return simplexml_import_dom($new, get_class($this));
    }
    
    /**
     * 
     * @param unknown_type $p1
     * @param unknown_type $p2
     * @return BetterXML
     */
    public function sort( $p1 )
    {
        // Build a sortable array
        $count = 0;
        $array = array();
        foreach ($this->getSiblingsToo() as $p) {
            foreach( $p as $name => $entry ) {
                $array[$count][$name] = (string) $entry; // Record to array
            }
            if (array_key_exists($count, $array)) {
                $array[$count]['__index'] = $count;
            }
            $count++;
        }
        
        // Sort it
        $this->_sortBy = (string) $p1;
        usort($array, array($this, 'sortBy'));
        unset($this->_sortBy);
        
        // Update the xml
        $siblings = $this->getSiblingsToo();
        foreach ($array as $k => $a) {
            $xml = simplexml_load_string( $siblings[$a['__index']]->asXML() );
            $siblings[$a['__index']]->remove();
            $this->parentNode()->extend( $xml );
        }
        return $this;
    }
    
    /**
     * usort callback
     * 
     * @param unknown_type $a
     * @param unknown_type $b
     * @return boolean
     */
    public function sortBy( $a, $b ) {
        return $a[(string)$this->_sortBy] > $b[(string)$this->_sortBy];
    }
    
    /**
     * Convert XML string to an array
     * 
     * @param unknown_type $xmlStirng
     */
    function asArray() {
        return json_decode(json_encode($this->getSiblingsToo(true)),true);
    }
}

On gists

PHP DataContainer class

PHP

data-container.php #

<?php


class dataContainer_helper implements ArrayAccess {
    
    protected $data;
    
    public function __toString() {
        
        return '';
        
    }
    
    // array access
    public function offsetSet($offset, $value) {
        $this->__set($offset, $value);
    }
    
    public function offsetUnset($offset) {
        $this->__unset($offset);
    }
    
    public function offsetExists($offset) {
        
        return $this->__isset($offset);
    }
    
    public function offsetGet($offset) {
        
        //return $this->{$offset};
        return $this->__get($offset);
        
    }
    
    public function __get($name) {
        
        
        
        if(!isset($this->data[$name])) {   
            
            $this->data[$name] = new dataContainer_helper;
            
        }
        
        //var_dump($this->data[$name]);
        
        return $this->data[$name];
        
    }
    
    public function __set($name, $value) {
        
        
        if(is_array($value) && !is_int(key($value))) {
            
            if(!($this->data[$name] instanceof dataContainer_helper)) {
            
                $this->data[$name] = new dataContainer_helper;
            }
            
            foreach($value as $key => $v) {
                
                $this->data[$name]->$key = $v;
                
            }            
            
        } else {
            $this->data[$name] = $value;
        }

    }
    
    
    public function __unset($name) {
        
        unset($this->data[$name]);   
        
    }
    
    public function __isset($name) {
        
        if(isset($this->data[$name])) {
            
            if($this->data[$name] instanceof dataContainer_helper) {
                
                if($this->data[$name]->isNull()) {
                    
                    //var_dump($this->data[$name]);
                    
                    return false;
                    
                }
                
            }
            
            if($this->data[$name] !== null) {
            
                return true;
                
            }
            
        }
        
        return false;
        
    }
    
    public function getContainerData() {
        
        if(is_array($this->data)) {
            
            $data = array();
        
            foreach($this->data as $key => $value) {
                
                if($value instanceof dataContainer_helper) {
                    
                    $data[$key] = $value->getContainerData();
                    
                    if($data[$key] === false) {
                        
                        unset($data[$key]);
                        
                    }
                    
                } else {
                    
                    $data[$key] = $value;
                    
                }
                
            }
            
            return $data;
            
        }
        
        return false;
        
        
        
    }
    
    public function setContainerData($data) {
        
        if(is_array($data)) {
        
            foreach($data as $key => $value) {
                
                $this->$key = $value;
                
            }
            
        } else {
            
            return false;
            
        }
        
    }
    
    public function isNull() {
        
        if($this->data === null) {
            
            return true;
            
        } else {
            
            return false;
            
        }
        
    }
    
    
}


$a = new dataContainer_helper;

echo $a->kkt->b = 'ku';

On gists

List of HTTP headers

PHP

List of HTTP headers.php #

 private function get_status_message(){
            $status = array(
                        100 => 'Continue',  
                        101 => 'Switching Protocols',  
                        200 => 'OK',
                        201 => 'Created',  
                        202 => 'Accepted',  
                        203 => 'Non-Authoritative Information',  
                        204 => 'No Content',  
                        205 => 'Reset Content',  
                        206 => 'Partial Content',  
                        300 => 'Multiple Choices',  
                        301 => 'Moved Permanently',  
                        302 => 'Found',  
                        303 => 'See Other',  
                        304 => 'Not Modified',  
                        305 => 'Use Proxy',  
                        306 => '(Unused)',  
                        307 => 'Temporary Redirect',  
                        400 => 'Bad Request',  
                        401 => 'Unauthorized',  
                        402 => 'Payment Required',  
                        403 => 'Forbidden',  
                        404 => 'Not Found',  
                        405 => 'Method Not Allowed',  
                        406 => 'Not Acceptable',  
                        407 => 'Proxy Authentication Required',  
                        408 => 'Request Timeout',  
                        409 => 'Conflict',  
                        410 => 'Gone',  
                        411 => 'Length Required',  
                        412 => 'Precondition Failed',  
                        413 => 'Request Entity Too Large',  
                        414 => 'Request-URI Too Long',  
                        415 => 'Unsupported Media Type',  
                        416 => 'Requested Range Not Satisfiable',  
                        417 => 'Expectation Failed',  
                        500 => 'Internal Server Error',  
                        501 => 'Not Implemented',  
                        502 => 'Bad Gateway',  
                        503 => 'Service Unavailable',  
                        504 => 'Gateway Timeout',  
                        505 => 'HTTP Version Not Supported');
            return ($status[$this->_code])?$status[$this->_code]:$status[500];
        }
                        
                      
                          private function set_headers(){
            header("HTTP/1.1 ".$this->_code." ".$this->get_status_message());
            header("Content-Type:".$this->_content_type);
        }

On gists

curl POST examples

PHP

server.js #

var app = require('express')();
var bodyParser = require('body-parser');

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

app.post('/data', function (req, res) {
  console.log(req.body);
  res.end();
});

app.listen(3000);

On gists

DateTime

PHP

DateTimeTest.php #

<?php

require_once __DIR__ . '/DateTime.php';

class DateTimeTest extends \PHPUnit_Framework_TestCase
{
    public function providerSetDate()
    {
        $now = new \MyNamespace\DateTime();
        return array(
            array('2014-02-28', 31, 2),
            array('2014-02-01', 1, 2),
            array('2014-06-30', 31, 6),
            array($now->format('Y-m-d'), null, null, null),
        );
    }

    /**
     * @test
     * @dataProvider providerSetDate
     */
    public function setDate($result, $day, $month, $year = '2014')
    {
        $dateTime = new \MyNamespace\DateTime();
        $dateTime->setDate($year, $month, $day);
        $this->assertEquals($result, $dateTime->format('Y-m-d'));
    }

    public function providerModify()
    {
        return array(
            array('2014-02-28', '0 day 0 month 0 year'),
            array('2014-01-28', 'next month'),
            array('2014-01-28', 'next months'),
            array('2014-01-02', '+1 month', '2014-02-02'),
            array('2014-01-31', '1 months'),
            array('2014-03-31', '-1 month'),
            array('2012-02-29', '24 month'),
            array('2016-02-29', '-24 months'),
            array('2014-02-27', 'next day'),
            array('2014-02-27', '1 day'),
            array('2014-02-27', '+1 day'),
            array('2013-02-01', '-1 day next month next year'),
            array('2013-01-27', '1 day 1 month 1 year'),
            array('2015-04-01', '-1 day -1 month -1 year'),
            array('2011-12-26', '2 day 2 month 2 year'),
            array('2011-12-31', '2 month 2 year'),
        );
    }

    /**
     * @test
     * @dataProvider providerModify
     */
    public function modify($date, $shift, $result = '2014-02-28')
    {
        $dateTime = new \MyNamespace\DateTime($date);
        $dateTime->modify($shift);
        $this->assertEquals($result, $dateTime->format('Y-m-d'));
    }

    /**
     * @test
     * @expectedException PHPUnit_Framework_Error_Warning
     */
    public function modifyError()
    {
        $dateTime = new \MyNamespace\DateTime();
        $dateTime->modify('2 month sdfg year');
    }
}

On gists

Ul to select (for responsive navigation)

JavaScript jQuery PHP Responsive

example.js #

$(function(){

    var select = $("select");
    $("nav a").each(function(){
        
        var $this = $(this);
        var text = $this.text();  
        var level = $this.parents("ul").length;
        var indent = '';
        if (level > 1)
        {
            indent = str_repeat("\u2013", level);
        }
        select.append('<option>'+indent + text+'</option>');
    
    
    });   



});


function str_repeat(string, times) {
  var repeatedString = "";
  while (times > 0) {
    repeatedString += string;
    times--;
  }
  return repeatedString;
}

On gists

PHP in the command line

PHP

commands.cmd #

# To parse and execute a php script:
php file
 
# To check syntax on (i.e. lint) a PHP script:
php -l file
 
# To run PHP interactively:
php -a
 
# To run PHP code (Notes: Don't use <? ?> tags; escape double quotes with backslash):
php -r "code"
 
# To start a PHP built-in web server in the current directory:
php -S host:port