/ Gists

Gists

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

Find column name in database

MySql

find-column.sql #

SELECT 
    table_name, 
    column_name, 
    data_type,
    ordinal_position

FROM  INFORMATION_SCHEMA.COLUMNS 

WHERE TABLE_SCHEMA = 'database-name'     
AND COLUMN_NAME = 'column'

On gists

PHP DOM examples

PHP-PHPDOM

example.php #

<?php


/ Bez tohoto volání při načítání HTML5 vyskakují podobné chyby:
// Warning:  DOMDocument::loadHTML(): Tag header invalid in Entity
libxml_use_internal_errors(true);

$data = file_get_contents("test.html");

$dom = new DOMDocument();
$dom->loadHtml(mb_convert_encoding($data, 'HTML-ENTITIES', 'UTF-8'));
$finder = new DomXPath($dom);


// Elementy
$nodesByElement = $finder->query("//a");       # CSS: a
$nodesByElement = $finder->query("//a/span");  # CSS: a > span
$nodesByElement = $finder->query("//a//span"); # CSS: a span

// ID a atributy
$nodeById = $finder->query("//*[@id='testId']");   # CSS: #testId
$nodeById = $finder->query("//div[@id='testId']"); # CSS: div#testId
$nodeByAttr = $finder->query("//*[@data-city]");   # CSS: [data-city]

// Třídy - těch může být více v jednom atributu, trochu se to komplikuje
// CSS: .inactive
$classToFind = "inactive";
$byClass = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' ".$classToFind." ')]");

// XPath se v těchto případech nechová úplně stejně jako CSS
$byIndex = $finder->query("//div/a[2]");      # CSS: div > a:nth-child(2)
$lastNode = $finder->query("//div/a[last()]");# CSS: div > a:last-child

// Vyhledávání pouze v dříve vyhledaném elementu
$finder->query("//a", $nodeById);

// Rodič, potomci, předchozí sourozenec, následující sourozenec
// POZOR: Počítá i TextNode
$parentNode = $nodeById->item(0)->parentNode;
$previousSibling = $nodeById->item(0)->previousSibling;
$nextSibling = $nodeById->item(0)->nextSibling;
$children = $nodeById->item(0)->childNodes;


// Získání kusu HTML nalezeného selektorem
$htmlPart = $dom->saveHtml($nodeById->item(0));

//Získání hodnotu atributu
$linkNode->item(0)->getAttribute("href");

// Změnu atributu
$linkNode->item(0)->setAttribute("href", "/");

// Smazání tagu img, který je přímým potomkem
$toRemove = $finder->query("img", $nodeList->item(2));
$removedItem = $nodeList->item(2)->removeChild($toRemove->item(0));

//Vložení nového (nyní odstraněného) elementu
$nodeList->item(0)->appendChild($removedItem);

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

Slick slider with thumbs

JavaScript jQuery

example.js #

// https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.5.9/slick.min.js
// //cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js

 $('.slider-for').slick({
   slidesToShow: 1,
   slidesToScroll: 1,
   arrows: false,
   fade: true,
   asNavFor: '.slider-nav'
 });
 $('.slider-nav').slick({
   slidesToShow: 3,
   slidesToScroll: 1,
   asNavFor: '.slider-for',
   dots: true,
   focusOnSelect: true
 });

 $('a[data-slide]').click(function(e) {
   e.preventDefault();
   var slideno = $(this).data('slide');
   $('.slider-nav').slick('slickGoTo', slideno - 1);
 });

On gists

Redirect from old domain to new

htaccess

htaccess #

  RewriteEngine On
  RewriteCond %{HTTP_HOST} ^olddomain.com$ [OR]
  RewriteCond %{HTTP_HOST} ^www.olddomain.com$
  RewriteRule (.*)$ http://www.newdomain.com/$1 [R=301,L]

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);
        }