/ Gists / PHP

Gists - PHP

On gists

PHP array sorting

PHP

ways.php #

  <?php
  $array = [
              [
                ['name'=>'John B'],
                ['age'=>30],
                ['sizes'=>
                          [
                          'weight'=>80, 
                          'height'=>120
                          ]
                ]
              ],
              [
                ['name'=>'Marie B'],
                ['age'=>31],
                ['sizes'=>
                          [
                          'weight'=>60, 
                          'height'=>110
                          ]
                ]
              ],
              [
                ['name'=>'Carl M'],
                ['age'=>12],
                ['sizes'=>
                          [
                          'weight'=>70, 
                          'height'=>100
                          ]
                ]
              ],
              [
                ['name'=>'Mike N'],
                ['age'=>19],
                ['sizes'=>
                          [
                          'weight'=>70, 
                          'height'=>150
                          ]
                ]
              ],
              [
                ['name'=>'Nancy N'],
                ['age'=>15],
                ['sizes'=>
                          [
                          'weight'=>60, 
                          'height'=>150
                          ]
                ]
              ],
              [
                ['name'=>'Cory X'],
                ['age'=>15],
                ['sizes'=>
                          [
                          'weight'=>44, 
                          'height'=>150
                          ]
                ]
              ]
  ];

  

   //Method1: sorting the array using the usort function and a "callback that you define"
   function method1($a,$b) 
   {
     return ($a[2]["sizes"]["weight"] <= $b[2]["sizes"]["weight"]) ? -1 : 1;
   }
   usort($array, "method1");
   print_r($array);




//Method 2: The bubble method
$j=0;
$flag = true;
$temp=0;

while ( $flag )
{
  $flag = false;
  for( $j=0;  $j < count($array)-1; $j++)
  {
    if ( $array[$j][2]["sizes"]["weight"] > $array[$j+1][2]["sizes"]["weight"] )
    {
      $temp = $array[$j];
      //swap the two between each other
      $array[$j] = $array[$j+1];
      $array[$j+1]=$temp;
      $flag = true; //show that a swap occurred
    }
  }
}
print_r($array);



  //Method3: DIY 
  $temp = [];
  foreach ($array as $key => $value)
    $temp[$value[2]["sizes"]["weight"] . "oldkey" . $key] = $value; //concatenate something unique to make sure two equal weights don't overwrite each other
  ksort($temp); // or ksort($temp, SORT_NATURAL); see paragraph above to understand why
  $array = array_values($temp);
  unset($temp);
  print_r($array);



  // Method 4
  array_multisort(array_map(function($element) {
    return $element[2]['sizes']['weight'];
}, $array), SORT_ASC, $array);


print_r($array);

On gists

Remove diacritics - strtr

PHP

rem-dia.php #

<?php

    private function removeDiacritics($str)
    {
        return strtr($str, "ÁÄČÇĎÉĚËÍŇÓÖŘŠŤÚŮÜÝŽáäčçďéěëíňóöřšťúůüýž", "AACCDEEEINOORSTUUUYZaaccdeeeinoorstuuuyz");
    }

On gists

Nette own storage via Session - wrapper

Nette PHP

Storage.php #

<?php

namespace Model;

use Nette;

class DemandStorage extends Nette\Object
{
    protected $session;
    public function __construct(Nette\Http\Session $session)
    {
        $this->session = $session->getSection('demandForm');    
    }

    public function flush()
    {
        $this->session->remove();
    }

    public function getRawData()
    {
        return isset($this->session['formData']) ? $this->session['formData'] : array();
    }

    public function getStepNumber()
    {
        return isset($this->session['step']) ? $this->session['step'] : 1;
    }

    public function setRawData($data)
    {
        $this->session['formData'] = $data;
        return $this;
    }

    public function addRawData($data)
    {
        $originalData = $this->getRawData();
        $data = array_merge($originalData, $data);
        $this->setRawData($data);
        return $this;
    }

    public function setStepNumber($step = 1)
    {
        $this->session['step'] = $step;
        return $this;
    }

    public function getValue($name, $default = NULL)
    {
        $data = $this->getRawData();
        return Nette\Utils\Arrays::get($data, $name, $default);
    }

    public function setValue($name, $value)
    {
        $data = $this->getRawData();
        $data[$name] = $value;
        $this->setRawData($data);
        return $this;
    }

    public function unsetValue($name)
    {
        $data = $this->getRawData();
        if(isset($data[$name]))
            unset($data[$name]);
        $this->setRawData($data);
        return $this;
    }

    public function issetValue($name)
    {
        $data = $this->getRawData();
            return isset($data[$name]);
    }

}

On gists

Anonymous self invoke functions

PHP Helpers-Filters-Plugins

anonymous.php #

<?php

call_user_func(function() { 
  
  // your code here ...

});

On gists

Check datum is in range

PHP Helpers-Filters-Plugins

in-range.php #

<?php
    public function checkDatum(\DateTime $date)
    {
        $startDate = new \DateTime('2018-12-17 00:00:00');
        $endDate   = new \DateTime('2018-12-23 23:59:59');
        
        return $date > $startDate && $date < $endDate;
     
    }

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';