/ Gists / PHP

Gists - PHP

On gists

Curl - PHP auth

PHP

curl-php-auth.php #

<?php
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
		curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
		$output = curl_exec($ch);
		$info = curl_getinfo($ch);
		curl_close($ch);

On gists

PHP Auth

PHP

php-auth.php #

<?php

if (empty($_SERVER['PHP_AUTH_USER']) ||
     $_SERVER['PHP_AUTH_USER'] != "login" ||
     $_SERVER['PHP_AUTH_PW'] != "pass") {
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Zde nemáte přístup bez jména a hesla';
    exit;
}

On gists

Gists API

PHP

gistApi.php #

<?php

class GistEdit {

	private $data;
	
	private static $_instance = NULL ;
	
	public static function init () {
		if (self::$_instance === NULL) {
            self::$_instance = new self;
        }
		self::$_instance->data = array();
        return self::$_instance;
	}
	
	public function edit ($file, $newContent = NULL, $newFileName = NULL) {
		
		if ($newContent !== NULL) {
			$this->data[$file]['content'] = $newContent ;
		}
		if ($newFileName !== NULL) {
			$this->data[$file]['filename'] = $newFileName ;
		}
		return $this;
	}
	
	public function deleteFile ($file) {
		$this->data[$file] = NULL ;
		return $this;
	}
	
	public function newFile ($file, $content){
		$this->data[$file]['content'] = $content;
		return $this;
	}
	
	public function get () {
		return $this->data;
	}

}

class gistAPI {
	
	private $url = "https://api.github.com" ;
	
	private $user = "github" ;
	
	public $ch ;
	
	private $response ;
	
	public $loginInfo ;
	
	
	function __construct($id = NULL, $pass = NULL) {
		if($id === NULL || $pass === NULL){
			$loginInfo = NULL;
		} else {
			$loginInfo = array('username' => $id,
							   'password' => $pass);
		}
		$this->loginInfo = $loginInfo;
		$this->chReset();
	}
	
	public function listGists ($type = "public", $user = NULL) {
	
		switch ($type) {
			case "public":
				curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists/public");
				break;
			case "user":
				curl_setopt($this->ch, CURLOPT_URL, $this->url . "/users/" . ($user === NULL ? $this->user:$user) ."/gists");
				break;
			case "starred":
				curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists/starred");
				break;
		}
		return $this->returnCode();
	
	}
	
	public function getGist ($gistId) {
	
		curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists/".$gistId);
		return $this->returnCode();
	
	}
	
	public function createGist ($files, $description = "", $public = false) {
	
		$filesArray = array();
		foreach ($files as $fileName => $content)
			$filesArray[$fileName]['content'] = $content;
		$postArray = array(
					"files"		  => $filesArray,
					"description" => $description,
					"public"	  => $public
					);
		$jsonArray = json_encode($postArray);
		
		curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists");
		curl_setopt($this->ch, CURLOPT_POST, 1);
		curl_setopt($this->ch, CURLOPT_POSTFIELDS, $jsonArray);
		return $this->returnCode();
	
	}
	
	public function editGist ($gistId, $files = NULL, $description = NULL) {
	
		curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists/". $gistId);
		curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, 'PATCH');
		if ($files === NULL && $description !== NULL) {
			$jsonArray = json_encode(array("description" => $description));
		} elseif ($description === NULL && $files !== NULL) {
			$jsonArray = json_encode(array("files" => $files));
		} elseif ($description !== NULL && $files !== NULL) {
			$jsonArray = json_encode(array("description" => $description, "files" => $files));
		} else {
			$this->chReset();
			return 0;
		}
		curl_setopt($this->ch, CURLOPT_POSTFIELDS, $jsonArray);
		return $this->returnCode();
	
	}
	
	public function gistCommits ($gistId) {
	
		curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists/" . $gistId . "/commits");
		return $this->returnCode();
	
	}
	
	public function starGist ($gistId) {
	
		curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists/". $gistId ."/star");
		curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, 'PUT');
		return $this->returnCode();
	
	}
	
	public function unstarGist ($gistId) {
	
		curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists/". $gistId ."/star");
		curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
		return $this->returnCode();
	
	}
	
	public function checkStarGist ($gistId) {
	
		curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists/". $gistId ."/star");
		return $this->returnCode();
	
	}
	
	public function forkGist ($gistId) {
	
		curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists/". $gistId ."/forks");
		curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, 'POST');
		return $this->returnCode();
	
	}
	
	public function listForkGist ($gistId) {
	
		curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists/". $gistId ."/forks");
		return $this->returnCode();
	
	}
	
	public function deleteGist ($gistId) {
	
		curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists/". $gistId);
		curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
		return $this->returnCode();
	
	}
	
	public function gistComments ($gistId) {
	
		curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists/".$gistId."/comments");
		return $this->returnCode();
	
	}
	
	public function getComment ($gistId, $commentId) {
	
		curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists/". $gistId ."/comments/". $commentId);
		return $this->returnCode();
	
	}
	
	public function createComment ($gistId, $comment){
	
		curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists/". $gistId ."/comments");
		curl_setopt($this->ch, CURLOPT_POST, 1);
		$jsonArray = json_encode(array("body" => $comment));
		curl_setopt($this->ch, CURLOPT_POSTFIELDS, $jsonArray);
		return $this->returnCode();
	
	}
	
	public function editComment ($gistId, $commentId, $comment) {
	
		curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists/". $gistId ."/comments/". $commentId);
		curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, 'PATCH');
		$jsonArray = json_encode(array("body" => $comment));
		curl_setopt($this->ch, CURLOPT_POSTFIELDS, $jsonArray);
		return $this->returnCode();
	
	}
	
	public function deleteComment ($gistId, $commentId) {
	
		curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists/". $gistId ."/comments/". $commentId);
		curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
		return $this->returnCode();
	
	}
	
	public function getLimits() {
	
		curl_setopt($this->ch, CURLOPT_URL, $this->url . "/rate_limit");
		return $this->returnCode();
	}
	
	private function parseHeader ($header_text) {
		
		$headers = array();
		foreach (explode("\r\n", $header_text) as $i => $line){
			if (strlen($line) > 1 && $i != 0){
				list ($key, $value) = explode(': ', $line);
				$headers[$key] = $value;
			} else if ($i == 0){
				$headers['http_code'] = $line;
			}
		}
		return $headers;
	}
	
	private function returnCode () {
	
		$this->response = curl_exec($this->ch);
		$header_size = curl_getinfo($this->ch, CURLINFO_HEADER_SIZE);
		$header = substr($this->response, 0, $header_size);
		$body = substr($this->response, $header_size);
		$return = array("header" => $this->parseHeader($header),
					 "body"	  => json_decode($body, true),
					 "raw"    => $this->response);
		$this->chReset();
		return $return;
	}
	
	public function chReset () {
	
		$this->ch = curl_init();
		curl_setopt($this->ch, CURLOPT_HEADER,         true);
		curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($this->ch, CURLOPT_TIMEOUT,        30);
		curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, false);
		if ($this->loginInfo !== NULL){
			$this->user = $this->loginInfo['username'];
			curl_setopt($this->ch, CURLOPT_USERAGENT, $this->loginInfo['username']);
			curl_setopt($this->ch, CURLOPT_USERPWD, $this->loginInfo['username'].":".$this->loginInfo['password']);
		} else {
			curl_setopt($this->ch, CURLOPT_USERAGENT, "gistAPI v1.0");
		}
		unset($this->response);
	
	}
	
	function __destruct() {
		curl_close($this->ch);
	}

}
?>

On gists

Returning value by reference // fn

PHP

example01.php #

<?php

class Fruit {
    private $color = "red";

    public function getColor() {
        return $this->color;
    }

    public function &getColorByRef() {
        return $this->color;
    }
} 



echo "\nTEST RUN 1:\n\n";
$fruit = new Fruit;
$color = $fruit->getColor();
echo "Fruit's color is $color\n"; 
$color = "green"; // does nothing, but bear with me
$color = $fruit->getColor();
echo "Fruit's color is $color\n"; 

echo "\nTEST RUN 2:\n\n";
$fruit = new Fruit;
$color = &$fruit->getColorByRef(); // also need to put & here
echo "Fruit's color is $color\n"; 
$color = "green"; // now this changes the actual property of $fruit
$x = $fruit->getColor();
echo "Fruit's color is $color\n"; 

On gists

Node Tree

PHP

note-tree.php #

<?php
/**
 * This file is part of Tree
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @author Nicolò Martini <nicmartnic@gmail.com>
 */

namespace Tree\Node;

use Tree\Visitor\Visitor;

trait NodeTrait
{
    /**
     * @var mixed
     */
    private $value;

    /**
     * parent
     *
     * @var NodeInterface
     * @access private
     */
    private $parent;

    /**
     * @var NodeInterface[]
     */
    private $children = [];

    /**
     * @param mixed $value
     * @param NodeInterface[] $children
     */
    public function __construct($value = null, array $children = [])
    {
        $this->setValue($value);
        if (!empty($children)) {
            $this->setChildren($children);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function setValue($value)
    {
        $this->value = $value;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getValue()
    {
        return $this->value;
    }

    /**
     * {@inheritdoc}
     */
    public function addChild(NodeInterface $child)
    {
        $child->setParent($this);
        $this->children[] = $child;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function removeChild(NodeInterface $child)
    {
        foreach ($this->children as $key => $myChild) {
            if ($child == $myChild) {
                unset($this->children[$key]);
            }
        }

        $this->children = array_values($this->children);

        $child->setParent(null);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function removeAllChildren()
    {
        $this->setChildren([]);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getChildren()
    {
        return $this->children;
    }

    /**
     * {@inheritdoc}
     */
    public function setChildren(array $children)
    {
        $this->removeParentFromChildren();
        $this->children = [];

        foreach ($children as $child) {
            $this->addChild($child);
        }

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function setParent(NodeInterface $parent = null)
    {
        $this->parent = $parent;
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return $this->parent;
    }

    /**
     * {@inheritdoc}
     */
    public function getAncestors()
    {
        $parents = [];
        $node = $this;
        while ($parent = $node->getParent()) {
            array_unshift($parents, $parent);
            $node = $parent;
        }

        return $parents;
    }

    /**
     * {@inheritDoc}
     */
    public function getAncestorsAndSelf()
    {
        return array_merge($this->getAncestors(), [$this]);
    }

    /**
     * {@inheritdoc}
     */
    public function getNeighbors()
    {
        $neighbors = $this->getParent()->getChildren();
        $current = $this;

        // Uses array_values to reset indexes after filter.
        return array_values(
            array_filter(
                $neighbors,
                function ($item) use ($current) {
                    return $item != $current;
                }
            )
        );
    }

    /**
     * {@inheritDoc}
     */
    public function getNeighborsAndSelf()
    {
        return $this->getParent()->getChildren();
    }

    /**
     * {@inheritDoc}
     */
    public function isLeaf()
    {
        return count($this->children) === 0;
    }

    /**
     * @return bool
     */
    public function isRoot()
    {
        return $this->getParent() === null;
    }

    /**
     * {@inheritDoc}
     */
    public function isChild()
    {
        return $this->getParent() !== null;
    }

    /**
     * Find the root of the node
     *
     * @return NodeInterface
     */
    public function root()
    {
        $node = $this;

        while ($parent = $node->getParent())
            $node = $parent;

        return $node;
    }

    /**
     * Return the distance from the current node to the root.
     *
     * Warning, can be expensive, since each descendant is visited
     *
     * @return int
     */
    public function getDepth()
    {
        if ($this->isRoot()) {
            return 0;
        }

        return $this->getParent()->getDepth() + 1;
    }

    /**
     * Return the height of the tree whose root is this node
     *
     * @return int
     */
    public function getHeight()
    {
        if ($this->isLeaf()) {
            return 0;
        }

        $heights = [];

        foreach ($this->getChildren() as $child) {
            $heights[] = $child->getHeight();
        }

        return max($heights) + 1;
    }

    /**
     * Return the number of nodes in a tree
     * @return int
     */
    public function getSize()
    {
        $size = 1;
        foreach ($this->getChildren() as $child) {
            $size += $child->getSize();
        }

        return $size;
    }

    /**
     * {@inheritdoc}
     */
    public function accept(Visitor $visitor)
    {
        return $visitor->visit($this);
    }

    private function removeParentFromChildren()
    {
        foreach ($this->getChildren() as $child)
            $child->setParent(null);
    }
} 

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