/ Gists / PHP

Gists - PHP

On gists

PHP local server

PHP CLI

in-cli.cli #

php -S localhost:9000

On gists

Access Control (cross origin allow for all) - API

PHP Web Api

api.php #

<?php

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

$films = [
    [
        'id' => 1628,
        'name' => 'Sám doma',
        'url' => 'https://www.csfd.cz/film/1628-sam-doma/prehled/',
    ],
    [
        'id' => 1629,
        'name' => 'Sám doma 2',
        'url' => 'https://www.csfd.cz/film/1629-sam-doma-2-ztracen-v-new-yorku/prehled/',
    ]
];

echo json_encode($films);

On gists

Sort array by multiple values

Popular ⭐ PHP

sort.php #

<?php

// https://blog.martinhujer.cz/clever-way-to-sort-php-arrays-by-multiple-values/
// https://stackoverflow.com/questions/2699086/how-to-sort-a-multi-dimensional-array-by-value
// COMPLEX: https://stackoverflow.com/questions/17364127/how-can-i-sort-arrays-and-data-in-php
// https://stackoverflow.com/questions/44309585/properly-sorting-multidimensional-array-using-usort-and-spaceship-operator/44309755#44309755

// 1)
// order products by: price ASC, inStock DESC, isRecommended DESC, name ASC
usort($products, function (Product $a, Product $b): int {
    return
        ($a->getPrice() <=> $b->getPrice()) * 1000 + // price ASC
        ($b->isInStock() <=> $a->isInStock()) * 100 + // inStock DESC
        ($b->isRecommended() <=> $a->isRecommended()) * 10 + // isRecommended DESC
        ($a->getName() <=> $b->getName()); // name ASC
});


// 2) 
// order products by: price ASC, inStock DESC, isRecommended DESC, name ASC
usort($products, fn (Product $a, Product $b): int =>
    ($a->getPrice() <=> $b->getPrice()) * 1000 + // price ASC
    ($b->isInStock() <=> $a->isInStock()) * 100 + // inStock DESC
    ($b->isRecommended() <=> $a->isRecommended()) * 10 + // isRecommended DESC
    ($a->getName() <=> $b->getName()) // name ASC
);

// 3)
usort($products, fn (Product $a, Product $b): int =>
    [$a->getPrice(), $b->isInStock(), $b->isRecommended(), $a->getName()]
    <=>
    [$b->getPrice(), $a->isInStock(), $a->isRecommended(), $b->getName()]
);



usort($myArray, function($a, $b) {
    $retval = $a['order'] <=> $b['order'];
    if ($retval == 0) {
        $retval = $a['suborder'] <=> $b['suborder'];
        if ($retval == 0) {
            $retval = $a['details']['subsuborder'] <=> $b['details']['subsuborder'];
        }
    }
    return $retval;
});

On gists

Get file ext from filename

PHP

getExtension.php #

<?php

// https://stackoverflow.com/questions/173868/how-to-get-a-files-extension-in-php

$ext = end(explode('.', $filename));
$ext = substr(strrchr($filename, '.'), 1);
$ext = substr($filename, strrpos($filename, '.') + 1);
$ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $filename);
$ext = strrchr($filename, '.');
$ext = pathinfo($filename, PATHINFO_EXTENSION)['extension'];
$ext  = (new SplFileInfo($path))->getExtension();

$exts = split("[/\\.]", $filename);
$n    = count($exts)-1;
$ext  = $exts[$n];

On gists

Move in array

PHP

list.php #

<?php

$states = ['Přijatá', 'Nová', 'K zaplacení', 'Zaplaceno', 'Expedováno', 'Doručeno'];
$currentState = isset($_GET['state']) ? $_GET['state'] : 'K zaplacení';

$totalStates = count($states);
$currentIndex = array_search($currentState, $states);
$prev = null;
$next = null;
$prevAll = [];
$nextAll = [];

foreach ($states as $index => $state) {

    if ($index < $currentIndex) {
        $prev = $state;
        $prevAll[] = $state;
    }

    if ($index > $currentIndex && $next === null) {
        $next = $state;
    }

    if ($index > $currentIndex) {
        $nextAll[] = $state;
    }
}

$meta = [
    'prev' => $prev, // predchozi stav vuci aktualnimu ...
    'prevAll' => $prevAll, // vsechny predchozi vuci aktualnimu  ...
    'next' => $next, // nasledujici stav vuci aktualnimu
    'nextAll' => $nextAll, // vsechny nasledujici po aktualnim
    'currentStateNumber' => $currentIndex, // aktualni cislo stavu, K zaplaceni => 2, Doručeno => 6 atd.
    'totalStates' => $totalStates, // celkovy pocet stavu, tj. 6
];


echo '<pre>';
print_r($meta);

On gists

Unique File name / Unique parent

PHP

unique-name-or-parent.php #

<?php
// 1
    do {
      $name = time() . rand(1,10);
      $name = "scr_" . substr(md5($name),0,8);
      $path = "images/screenshots/fullsize/" . $name . ".jpg";
    } while (file_exists($path));
    
  // 2
    while ($parent = $node->getParent()) {
            array_unshift($parents, $parent);
            $node = $parent;
    }
    
    
    
    $arr = ['name', 'name0', 'name1', 'name2'];

// 3
$i = 0;
$name = 'name';
while (in_array($newName = $name. $i++, $arr)) {

}
echo $newName;

On gists

MatchResult component

Nette Nette-Controls PHP

MatchResultControl.php #

<?php


class MatchResult extends Control{

	const TEMPLATE_FULL = 'full';
	const TEMPLATE_INLINE = 'inline';

	public function renderFull($match){
		$this->render($match, self::TEMPLATE_FULL);
	}

	public function renderInline($match){
		$this->render($match, self::TEMPLATE_INLINE);
	}

	private function render($match, $templateName){
		$template = $this->createTemplate();
		$template->setFile(__DIR__.'/'.$templateName.'.latte');
		$template->match = $this->evaluateResult($match);
		$template->render();
	}

	private function evaluateResult($match){
		return //...
	}
}

On gists

SelectionResolver

Nette PHP Nette-Database PHP Patterns

SelectionResolver.php #

<?php

// usage
		$this->paymentList = $this->payment->getPaymentSelectionResolver()
				->getBaseSelection()
				//->setCountry($this->order->billing__country_id)
				->setUserGroups($this->user->isLoggedIn() ? $this->user->getRoles() : NULL)
				->setOnlyForProduct($this->payment->getPaymentOnlyForProduct($this->order->getItems($this->order::ITEM_PRODUCT)))
				->toArray();
				
// ...				
    public function getPaymentSelectionResolver()
    {
        return $this->paymentSelectionResolver;
    }
    
    
// ...
class PaymentEshopOrderSelectionResolver
{
    /**
     * @var Context
     */
    protected $connection;

    /**
     * 
     * @var Nette\Database\Table\Selection
     */
    protected $selection;


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

    
    public function getBaseSelection()
    {
        $this->selection = $this->connection->table('payment_type')
            ->where('active = 1');
        return $this;
    }


    public function setCountry($countryId)
    {
        $this->selection->where(':payment_type_country.country_id IN (?) OR all_countries = 1', (array) $countryId);
        //$this->selection->where(':transport_type_variant.country_id IS NULL OR :transport_type_variant.country_id IN (?)', (array) $countryId);
        return $this;
    }


    public function setOnlyForProduct($paymentTypeIds = NULL)
    {
        if ($paymentTypeIds === NULL)
        {
            $this->selection->where('only_for_product = 0 OR only_for_product IS NULL');
        }
        else
        {
            $this->selection->where('payment_type.id IN (?)', (array) $paymentTypeIds);
        }
        return $this;
    }


    public function setUserGroups($usegroupsId = NULL)
    {
        if ($usegroupsId === NULL)
        {
            $this->selection->where(':payment_type_usergroup.usergroup_id IS NULL');
        }
        else
        {
            $this->selection->where(':payment_type_usergroup.usergroup_id IS NULL OR :payment_type_usergroup.usergroup_id  IN (?)', $usegroupsId);
        }
        return $this;
    }


    public function toArray()
    {
        $rows = [];
        foreach ($this->selection as $row)
        {
            $rows[$row->id] = $row;
        }

        return $rows;
    }

}

On gists

MSP Vat resolver

PHP AW PHP Patterns

solution.php #

<?php

namespace Model;
use Nette;


class VatCzSkResolver
{
	private static $instance;

	public $eshopOrderFormMasoprofit;
	
	public function __construct(EshopOrderFormMasoprofit $eshopOrderFormMasoprofit)
	{
		self::$instance = $this;
		$this->eshopOrderFormMasoprofit = $eshopOrderFormMasoprofit;
	}

	public static function getDphRewrite()
	{
		if (!self::$instance) { // nejsme na frontendu
			return null;
		}
		
		if ($billingAddress = self::$instance->eshopOrderFormMasoprofit->getBillingAddress()) {
			if (isset($billingAddress['country_id']) && $billingAddress['country_id'] == 186) {
				if (isset($billingAddress['ic_vat']) && $billingAddress['ic_vat'] && isset($billingAddress['dic']) && $billingAddress['dic']) {
					return 0;
				}

				return 20;
			}
		}

		return null;
	}
}

On gists

CheckboxList - booleaned all values

PHP Nette-Forms Nette-Tricks

example.php #

<?php
/* https://forum.nette.org/cs/35218-muze-checkboxlist-vracet-associativni-pole-misto-indexoveho#p220072 */

0 => 'po'
1 => 'st'
2 => 'ct'


po => true
ut => false
st => true
ct => true
pa => false


array_walk($arr, fn(&$item, $key, $values) => $item = in_array($key, $values), $values);