Szybkie posty

Jeżeli coś jest wartego uwagi a nie jest to materiał na pełnoprawnwgo posta na blogu to będę starać się to umieszczać w tym miejscu.

#ajax #apache #behat #bitbacket #bootstrap #composer #cookies #cqrs #css #css flex #ct8 #curl #docker #doctrine #edukacja #elasticsearch #enet #enp sla #filmy #firma #funkcje php #git #google #htaccess #html #inne #javascript #jedzenie #jquery #js/jquery #kawały #krypto #laravel #linux #oop #pdo #php #php wzorce narzędzia #phpmyadmin #phpspec #phpstan #phpstorm #phpunit #podcast #rabbit #redis #seo #soap #sql #symfony #szukanie po stringach w php #twig #virtual host #visual studio code #vue #wamp #windows #wino-nalewki #wyrazenia regularne #wzorce projektowe #xml #xxx #zdjecia #złote myśli
  • Szukasz po tagu: php
  • Ilość rekordów w bazie: 109

array map php funkcja anonimowa

return array_map(function($value) {
   return $value['1'];
}, $result);

Php ważne

Funkcje substr i strlen krzaczą się z polskimi znakami. Zamiast nich używać :
<?php
$string = 'ćów123214';
$lenght = mb_strlen($string, 'UTF-8');
$cut = mb_substr($string, 0, 2, 'UTF-8');
var_dump($lenght,$cut);

Wzorzec dekorator

<?php
interface CarInterface {
    public function calcualtePrice(): int;
}

abstract class CarDecorator implements CarInterface {
    protected $car;
    public function __construct(CarInterface $car) {
        $this->car = $car;
    }
}

Class Car implements CarInterface {
    public function calcualtePrice(): int {
        return 5000;
    }
}

Class CarWithAirConditioning extends CarDecorator {
    public function calcualtePrice(): int {
        return $this->car->calcualtePrice() + 101;
    }
}

Class CarWithSunRoof extends CarDecorator {
    public function calcualtePrice(): int {
        return $this->car->calcualtePrice() + 70;
    }
}

Class CarWith5Skin extends CarDecorator {
    public function calcualtePrice(): int {
        return $this->car->calcualtePrice() + 111;
    }
}

Class CarWithCamera extends CarDecorator {
    public function calcualtePrice(): int {
        return $this->car->calcualtePrice() + 52;
    }
}

$car1 = new CarWithCamera(new CarWithAirConditioning(new Car()));
var_dump($car1->calcualtePrice());

$car2 = new CarWithAirConditioning(new CarWith5Skin(new Car()));
var_dump($car2->calcualtePrice());

$car3 = new Car();
$car3 = new CarWithAirConditioning($car3);
$car3 = new CarWithSunRoof($car3);
$car3 = new CarWith5Skin($car3);
$car3 = new CarWithCamera($car3);
var_dump($car3->calcualtePrice());

Php obcinanie stringa

<?php
$test = 'ęą';

$res1 = substr($test, 0, 11));
$res2 = mb_substr($test, 0, 11));

//substr sie wykrzczy na polskich znakach!!!! 

Regex z forum

<?php
 
$regex = '/\d(\.\d{1,2})+/';
 
$inputs = [
    '1.1',
    '1.11',
    '1.11.1'
];
 
foreach( $inputs as $input ) {
    $matches = [];
    preg_match( $regex, $input, $matches );
    var_dump( $matches );
}

Wzorzec adapter

<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

interface ImageResizeInterface {

    public function setImage(string $fileName);

    public function resizeTo(string $width, string $height);

    public function resizeHeightByWidth(string $width);

    public function save();
}

class ResizeImage implements ImageResizeInterface {

    public function setImage(string $fileName) {
        //code
    }

    public function resizeTo(string $width, string $height) {
        //code
    }

    public function resizeHeightByWidth(string $width) {
        //code
    }

    public function save() {
        //code
    }

}

interface ImageInterface {

    public function setImageToResize(string $fileName);

    public function resizeImageTo(string $imageWidth, string $imageHeight);

    public function resizeImageHeightByWidth(string $width);

    public function saveImage();
}

class ImageResize implements ImageInterface {

    public function setImageToResize(string $fileName) {
        //code
    }

    public function resizeImageTo(string $imageWidth, string $imageHeight) {
        //code
    }

    public function resizeImageHeightByWidth(string $width) {
        //code
    }

    public function saveImage() {
        //code
    }

}

class ImageAdapter implements ImageResizeInterface {

    private $image;

    public function __construct(ImageResize $image) {
        $this->image = $image;
    }

    public function setImage(string $fileName) {
        $this->image->setImageToResize($fileName);
    }

    public function resizeTo(string $width, string $height) {
        $this->image->resizeImageTo($width, $height);
    }

    public function resizeHeightByWidth(string $width) {
        $this->image->resizeImageHeightByWidth($width);
    }

    public function save() {
        $this->image = saveImage();
    }

}

$imageAdapter = new ImageAdapter(new ImageResize());


var_dump($imageAdapter);

2//

<?php

//Book
class Book {

    private $author;
    private $title;

    function __construct(string $author, string $title) {
        $this->author = $author;
        $this->title = $title;
    }

    function getAuthor(): string {
        return $this->author;
    }

    function getTitle(): string {
        return $this->title;
    }

}

//book adapter
class BookAdapter {

    private $book;

    function __construct(Book $book) {
        $this->book = $book;
    }

    function getAuthorAndTitle(): string {
        return $this->book->getTitle() . ' by ' . $this->book->getAuthor();
    }

}

// client
$book = new Book("J.R.R. Tolkien", "Władca Pierścieni:");
$bookAdapter = new BookAdapter($book);

echo ('Author and Title: ' . $bookAdapter->getAuthorAndTitle());

Offset i limit w tablicy

$getDataToProcess = array_slice($allDataFromItem, $offset, $limit, true);

Petla do dniach miedzy dwoma datami

$dateTemp = clone $dateFrom;

//loop literate single days between two dates ($dateFrom, $dateTo)
while ($dateTemp <= ($dateTo->setTime(23, 59, 59, 999999))) {

   $dateTemp->modify('+1 days');
}

lub

<?php
$begin = new DateTime('2019-09-01');
$end = new DateTime('2019-09-10');

$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);

foreach ($period as $dt) {
    echo $dt->format("l Y-m-d H:i:s\n");
}

Ustawianie prywatne wartości w testach

<?php

namespace Tests\MultiStepFormBundle\Domain\Flow\Manager;

use MultiStepFormBundle\Domain\Flow\Manager\FlowManager;
use Tests\ModelTestCase;

class FlowManagerTest extends ModelTestCase {

    /**
     * @dataProvider mergeClientDataWithDataFromSidByMinModifyDateProvider
     */
    public function testMergeClientDataWithDataFromSidByMinModifyDate(array $clientData, array $clientDataFromSid, array $expected) {
        $transactionModelFactoryMock = $this->createMock(\MultiStepFormBundle\Domain\Transaction\Factory\TransactionModelFactory::class);
        $clientDataModelFactoryMock = $this->createMock(\MultiStepFormBundle\Domain\ClientData\Factory\ClientDataModelFactory::class);
        $formModelFactoryMock = $this->createMock(\MultiStepFormBundle\Domain\Form\Factory\FormModelFactory::class);
        $containerMock = $this->createMock(\Symfony\Component\DependencyInjection\Container::class);

        $service = new FlowManager($transactionModelFactoryMock, $clientDataModelFactoryMock, $formModelFactoryMock, $containerMock);

        $this->setPrivateVariable($service, 'copyClientData', $clientData);

        $method = $this->getMethod(FlowManager::class,
                'mergeClientDataWithDataFromSidByMinModifyDate');
        $result = $method->invokeArgs($service, [$clientDataFromSid]);

        return $this->assertEquals($expected, $result);
    }

    public function mergeClientDataWithDataFromSidByMinModifyDateProvider() {
        return [
            [
                [
                    'imie' => 'Jan',
                ],
                [
                    'imie' => [
                        'value' => 'Jan',
                        'modify' => (new \DateTime('now + 5minutes'))->format('Y-m-d H:i:s')
                    ],
                ],
                [
                    'imie' => 'Jan',
                ],
            ],
            [
                [
                    'imie' => 'Jan',
                ],
                [
                    'imie' => [
                        'value' => 'Stefan',
                        'modify' => (new \DateTime('now + 5minutes'))->format('Y-m-d H:i:s')
                    ],
                ],
                [
                    'imie' => 'Jan',
                ],
            ],
            [
                [
                    'imie' => '',
                ],
                [
                    'imie' => [
                        'value' => 'Stefan',
                        'modify' => (new \DateTime('now + 5minutes'))->format('Y-m-d H:i:s')
                    ],
                ],
                [
                    'imie' => 'Stefan',
                ],
            ],
            [
                [
                    'imie' => 'Dupa',
                ],
                [
                    'imie' => [
                        'value' => 'Stefan',
                        'modify' => (new \DateTime('now - 5 days'))->format('Y-m-d H:i:s')
                    ],
                ],
                [
                    'imie' => 'Dupa',
                ],
            ],
            [
                [
                    'imie' => '',
                ],
                [
                    'imie' => [
                        'value' => 'Stefan',
                        'modify' => (new \DateTime('now - 5 days'))->format('Y-m-d H:i:s')
                    ],
                ],
                [
                    'imie' => '',
                ],
            ],
            [
                [
                    'imie' => 'Jan',
                ],
                [
                    'imie' => [
                        'value' => 'Stefan',
                        'modify' => null
                    ],
                ],
                [
                    'imie' => 'Jan',
                ],
            ],
            [
                [
                    'imie' => 'Jan',
                ],
                [
                    'imie' => [
                        'value' => 'Stefan',
                        'modify' => ''
                    ],
                ],
                [
                    'imie' => 'Jan',
                ],
            ],
            [
                [
                    'imie' => 'Jan',
                ],
                [],
                [
                    'imie' => 'Jan',
                ],
            ],
            [
                [
                ],
                [
                    'imie' => [
                        'value' => 'Stefan',
                        'modify' => (new \DateTime('now + 5 days'))->format('Y-m-d H:i:s')
                    ],
                ],
                [
                    'imie' => 'Stefan',
                ],
            ],
            [
                [],
                [
                    'imie' => [
                        'value' => 'Stefan'
                    ],
                ],
                [],
            ],
            [
                [
                    'imie' => 'janusz'
                ],
                [
                    'imie' => [
                        'value' => 'Stefan'
                    ],
                ],
                [
                    'imie' => 'janusz'
                ],
            ],
        ];
    }

    /**
     * get acces to private method
     * @param string $className
     * @param string $methodName
     * @return \ReflectionMethod
     */
    protected static function getMethod(string $className, string $methodName) {
        $class = new \ReflectionClass($className);
        $method = $class->getMethod($methodName);
        $method->setAccessible(true);
        return $method;
    }

    protected static function setPrivateVariable($object, string $objectParameter, $objectValue) {
        $reflection = new \ReflectionClass($object);
        $property = $reflection->getProperty($objectParameter);
        $property->setAccessible(true);
        $property->setValue($object, $objectValue);
    }

}

Wiele parametrów przekazanych nie jako tablica

function sum(...$numbers) {
    $acc = 0;
    foreach ($numbers as $n) {
        $acc += $n;
    }
    return $acc;
}
echo sum(1, 2, 3, 4);//10

Fabryka abstrakcyjna

<?php

interface CarType {

    CONST POTROL = 'petrol';
    CONST DIESEL = 'desiel';

}

class CarsFactory {

    public function createDesiel() {
        return new Car(CarType::DIESEL, '1.7', false);
    }

    public function createFastBigCar() {
        return new Car(CarType::POTROL, '3.7', false);
    }

    public function createFastSmallCar() {
        return new Car(CarType::POTROL, '1.0', true);
    }

}

Class Car {

    private $engine;
    private $capacity;
    private $turbo;

    public function __construct(string $engine, string $capacity, bool $turbo) {
        $this->engine = $engine;
        $this->capacity = $capacity;
        $this->turbo = $turbo;
    }

}

$factory = new CarsFactory();

$diesel = $factory->createDesiel();
$fastBigCar = $factory->createFastBigCar();
$fastSmallCar = $factory->createFastSmallCar();

var_dump($diesel, $fastBigCar, $fastSmallCar);

Losowanie lotto

<?php

class Lotto {

    /**
     * @var int 
     */
    private $numbersQuantity;

    /**
     * @var int
     */
    private $maxNumber;

    /**
     * @param int $numbersQuantity
     * @param int $maxNumber
     */
    public function __construct(int $numbersQuantity, int $maxNumber) {
        if ($numbersQuantity <= 0 || $maxNumber <= 0) {
            throw new \Exception('Parameters musts been biggers than zero');
        }

        $this->numbersQuantity = $numbersQuantity;
        $this->maxNumber = $maxNumber;
    }

    /**
     * generate lotto numbers
     * 
     * @return array
     */
    public function generateLottoNumbers(): array {
        $numbers = range(1, $this->maxNumber);
        shuffle($numbers);

        $lottoNumbers = array_slice($numbers, - $this->numbersQuantity);

        sort($lottoNumbers);

        return $lottoNumbers;
    }

}

/**
 * @param array $data
 * @return boolean
 */
function consecutiveElementsInArray(array $data): bool {
    $count = count($data);
    foreach ($data as $key => $value) {
        if ($key == $count - 1) {
            break;
        }

        if (($data[$key + 1]) != ($value + 1)) {
            return false;
        }
    }

    return true;
}

$lottoNumbers = (new Lotto(6, 49))->generateLottoNumbers();

$interest = array_intersect($lottoNumbers, [3, 7, 9, 12, 27, 45]);

echo '<h1>trafiles: ' . count($interest) . ' liczb';
echo '<br>';

foreach ($lottoNumbers as $number) {
    echo '<b>' . $number . '</b>  ';
}

die;

$count = 0;

for ($i = 1; $i < 139; $i++) {
    $lottoNumbers = (new Lotto(6, 49))->generateLottoNumbers();
    if (consecutiveElementsInArray($lottoNumbers)) {
        $count++;
    }
}

echo '<h1>tyle ma liczby po kolei: ' . $count . '</h1>';
die;
​

yield w php

<?php

// Starting clock time in seconds
$start_time = microtime(true);
$a = 1;

function convert($size) {
	$unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');
	return @round($size / pow(1024, ($i = floor(log($size, 1024)))), 2) . ' ' . $unit[$i];
}

function getLines($file) {
	while ($line = fgets($file)) {
		yield $line;
	}
}

$file = fopen('a.csv', 'rb');
$lines = getLines($file);

foreach ($lines as $line) {
	//echo $line;
}
fclose($file);

echo convert(memory_get_usage(true)); // 123 kb

echo '<br>';
// End clock time in seconds
$end_time = microtime(true);

// Calculate script execution time
$execution_time = ($end_time - $start_time);

echo " Execution time of script = " . $execution_time . " sec";
<?php
// Starting clock time in seconds
$start_time = microtime(true);
$a = 1;

function convert($size) {
	$unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');
	return @round($size / pow(1024, ($i = floor(log($size, 1024)))), 2) . ' ' . $unit[$i];
}

function getLines($file) {
	$lines = [];
	while ($line = fgets($file)) {
		$lines[] = $line;
	}
	return $lines;
}

$file = fopen('a.csv', 'rb');
$lines = getLines($file);
fclose($file);

foreach ($lines as $line) {

}

echo convert(memory_get_usage(true)); // 123 kb

echo '<br>';
// End clock time in seconds
$end_time = microtime(true);

// Calculate script execution time
$execution_time = ($end_time - $start_time);

echo " Execution time of script = " . $execution_time . " sec";

Symfony walidacja w osobnym obiekcie

https://sarvendev.com/2018/01/encja-byc-zawsze-poprawnym-obiektem/


Iterator w php

https://www.php.net/manual/en/class.iteratoraggregate.php

https://www.php.net/manual/en/class.arrayiterator.php

class CarsIterator implements Iterator {
	private $position = 0;
	private $cars = ['BMW', 'Audi', 'KIA', 'Opel', 'Ford'];

	public function current() {
		return $this->cars[$this->position];
	}

	public function key() {
		return $this->position;
	}

	public function next() {
		$this->position++;
	}

	public function rewind() {
		$this->position = 0;
	}

	public function valid() {
		if (isset($this->cars[$this->position])) {
			return true;
		}

		return false;
	}
	public function reverse() {
		$this->cars = array_reverse($this->cars, true);
	}
}

$tests = new CarsIterator();

var_dump($tests->current());

$tests->next();
$tests->next();
$tests->next();
$tests->next();
$tests->next();

var_dump($tests->current());

sortowanie asocjacyjnej tablicy po 2 kluczach


  foreach ($normalLinks as $linkId => $data) {
            // prepare additional parameters from link
            // find link
            /* @var $link Linki */
            $link = $this->linksRepository->find($linkId);
            // norlam link CPL
            if (isset($data['linkUrl']) && $data['linkUrl'] != '') {
                // save to result
                $result[$linkId] = [
                    'partnerName' => $transaction->getPartnerNameLinkId($linkId),
                    'redirectUrl' => $data['linkUrl'],
                    'logoSrc' => $link ? $link->getLogoSrc() : null,
                    'description' => $link ? $link->getDescription() : null,
                    'customOrderNr' =>$link ? $link->getCustomOrderNr():null,
                    'orderNr' => isset($data['orderNr']) ? $data['orderNr'] : 99999,
                ];
            }
        }
        
        //sort by customOrderNr and orderNr
        uasort($result, function ($a, $b) {
            $customOrderNrDiff = $a['customOrderNr'] - $b['customOrderNr'];
            return $customOrderNrDiff ?  $customOrderNrDiff: $a['orderNr'] - $b['orderNr'];
        });

        return $result;

Sortowanie malejąco:

uasort($parseLogs['fields'], function ($a, $b) {
    if ($a['numberOfErrors'] == $b['numberOfErrors']) {
       return 0;
    }

    return $a['numberOfErrors'] < $b['numberOfErrors'] ? 1 : -1;
});

strpos problem

if (isset($resposne['message']) && (strpos($resposne['message'], 'wystepuje blokada ponownego dodania')!== false)) {
   $this->normalizeStatus = self::STATUS_DUPLICATE;
}

Trzeba dodać !== false bo ineczej nie działa to poprawnie


Zamiana klucza w json

/**
     * replace user agent in text to user agent from actual environment
     * 
     * @param string $text
     * 
     * @return string
     */
    private function replaceUserAgent(string $text): string {
        $client = new Client();
        $userAgent = str_replace('/', '\/', ($client->getConfig('headers')['User-Agent']));

        $result = preg_replace('/"user_agent":"(Guzzle[A-Za-z0-9 . \/\\\]*)"/', '"user_agent":"' . $userAgent . '"', $text);

//or $result = preg_replace('/"user_agent":"GuzzleHttp(.*)"/', '"user_agent":"' . $userAgent . '"', $text);

//. kropka - dowolny znak * oznacza dowolną ilosc razy bez gwiazdki brało by pod uwagę tylko pierwszy znak.  

        return $result;
    }

zamiana na kropki wszystkich / z pominięciem pierwszego

<?php

$str     = '6/3/2';
$res_str = array_chunk(explode("/",$str),2);
foreach( $res_str as &$val){
   $val  = implode("/",$val);
}
echo implode(".",$res_str);

//6/3.2

Wzorzec strategia

1/

<?php
interface AbstractStrategy{
    function task();
}
class ConcreteStrategy1 implements AbstractStrategy{
    public function task() {
        echo "Strategy 1";
    }
}
class ConcreteStrategy2 implements AbstractStrategy{
    public function task() {
        echo "Strategy 2";
    }
}
class Context{
    private $strategy;
 
    public function setStrategy(AbstractStrategy $obj) {
        $this->strategy=$obj;
    }
    public function getStrategy() {
        return $this->strategy;
    }
}
// testy
$obj = new Context();
$obj->setStrategy(new ConcreteStrategy1);
$obj->getStrategy()->task(); // wyswietla „Strategy 1”
$obj->setStrategy(new ConcreteStrategy2);
$obj->getStrategy()->task(); // wyswietla „Strategy 2”
?>

2/

<?php
 
interface Tax{
    public function count($net);
}
 
class TaxPL implements Tax{
    public function count($net) {
        return 0.23*$net;
    }
}
 
class TaxEN implements Tax{
    public function count($net) {
        return 0.15*$net;
    }
}
 
class TaxDE implements Tax{
    public function count($net) {
        return 0.3*$net;
    }
}
 
class Context{
    private $tax;
 
    /**
     * @return mixed
     */
    public function getTax()
    {
        return $this->tax;
    }
 
    /**
     * @param mixed $tax
     */
    public function setTax(Tax $tax)
    {
        $this->tax = $tax;
    }
 
}
 
// testy
$tax = new Context();
$tax->setTax(new TaxPL());
echo $tax->getTax()->count(100); // wyswietla "23"
$tax->setTax(new TAXEN());
echo $tax->getTax()->count(100); // wyswietla "15"
$tax->setTax(new TAXDE());
echo $tax->getTax()->count(100); // wyswietla "30"
 
?>
<?php

interface Promotion {

    public function getPriseAfterPromotion(float $price): float;
}

class BlackFriday implements Promotion {

    public function getPriseAfterPromotion(float $price): float {
        return $price * 0.2;
    }

}

class SpanishKangaroosFestival implements Promotion {

    public function getPriseAfterPromotion(float $price): float {
        $discount = floor($price / 10) * 2;
        return $price - $discount;
    }

}

class Checkout {

    /**
     * @var type 
     */
    private $price;

    /**
     * @var Promotion 
     */
    private $promotion;

    /**
     * @param float $price
     */
    public function setPrice(float $price): void {
        $this->prise = $price;
    }

    /**
     * @param Promotion $promition
     */
    public function setPromotion(Promotion $promition): void {
        $this->promition = $promition;
    }

    /**
     * @return float
     */
    public function getTotalPrice(): float {
        return $this->promition->getPriseAfterPromotion($this->prise);
    }

}

$checkout = new Checkout();
$checkout->setPrice(22.333);
$checkout->setPromotion(new BlackFriday());

echo $checkout->getTotalPrice() . ' zl';
echo '<br><br>';

$checkout2 = new Checkout();
$checkout2->setPrice(120.9);
$checkout2->setPromotion(new SpanishKangaroosFestival());

echo $checkout2->getTotalPrice() . ' zl';

Ustawienie końca dnia dla obiektu datetime

$date = new DateTime();
      
var_dump($date->setTime(23, 59, 59, 999999));

Basic Auth php przykład

        $parameters = json_encode($parameters);
        
        $headers = [
            'Content-Type: application/json',
            'Accept: application/json',
        ];

        try {
            // curl setup, disabling certificate check
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_USERPWD, $this->login . ":" . $this->pass);

            $responseJson = curl_exec($ch);
            $response = json_decode($responseJson, true);

            $this->lastHttpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
        } catch (\Exception $ex) {
            throw new \Exception('Curl call failed! HttpCode: ' . $this->lastHttpCode . ' (Ex: ' . $ex->getMessage() . ')');
        }

        return $response;

Walidacja dowodu osobistego

<?php

class DowOsValidator {

    public static function valid($value) {
        //delete white chars
        $value = str_replace(' ', '', $value);

        //if is too short or too long
        if (strlen($value) <= 8 || strlen($value) > 9) {
            return false;
        }

        $defValue = [
            '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9,
            'A' => 10, 'B' => 11, 'C' => 12, 'D' => 13, 'E' => 14, 'F' => 15, 'G' => 16, 'H' => 17, 'I' => 18, 'J' => 19,
            'K' => 20, 'L' => 21, 'M' => 22, 'N' => 23, 'O' => 24, 'P' => 25, 'Q' => 26, 'R' => 27, 'S' => 28, 'T' => 29,
            'U' => 30, 'V' => 31, 'W' => 32, 'X' => 33, 'Y' => 34, 'Z' => 35
        ];

        $importance = [7, 3, 1, 9, 7, 3, 1, 7, 3];

        try {
            //change to upper
            $value = strtoupper($value);
            
            $identityCardSum = 0;

            for ($i = 0; $i < 9; $i++) {
                if (!isset($defValue[$value[$i]]) || ($i < 3 && $defValue[$value[$i]] < 10)) {
                    return false;
                } elseif (($i > 2 && $defValue[$value[$i]] > 9)) {
                    return false;
                }

                $identityCardSum += ((int) $defValue[$value[$i]]) * $importance[$i];
            }

 
            if ($identityCardSum % 10 != 0) {
                return false;
            }
            
        } catch (\Exception $ex) {
            return false;
        }

        return true;
    }
}

Pokazywanie rezultatu przed końcem wykonania skryptu

flush();
ob_flush();

Data początek i koniec dnia

<?php
// default and list items
$dateNow = new \DateTime('now');
$createdAtBeginDefault = new \DateTime($dateNow->format('Y-m-d') . ' 00:00:00');
$createdAtEndDefault = new \DateTime($dateNow->format('Y-m-d') . ' 23:59:59');

Mielenie każdej wartości w tablicy przy użyciu funkcji (array_map)

<?php
function myfunction($num)
{
  return($num*$num);
}

$a=array(1,2,3,4,5);
print_r(array_map("myfunction",$a));

// Array
// (
//     [0] => 1
//     [1] => 4
//     [2] => 9
//     [3] => 16
//     [4] => 25
// )
?>

Obcięcie stringa do max ilości znaków

mb_substr($var,0,142, "utf-8");

Sprawdzenie wspólnych kluczy tablicy

$config['parameters'] = ['test1 =>123,'test2'=333];

$parameters = ['test1 =>123];


$arrayIntersect = array_intersect_assoc($config['parameters'], $parameters);

ksort($arrayIntersect);
ksort($parameters);

if ($arrayIntersect == $parameters) {
   return $config['returnValue'];
}

Router początek

<?php

$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

print_r(parse_url($actual_link));
echo '<br>';
echo parse_url($actual_link, PHP_URL_PATH);

?>

/htacces

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^(.*)$ index.php [NC,L]

Pesel parser

<?php

class PeselParser
{
    /**
     * @var string 
     */
    private $pesel;

    /**
     * @param string $pesel
     */
    public function __construct(string $pesel)
    {
        $this->pesel = $pesel;
    }
    /**
     * get client age from pesel
     *
     * @return integer|null
     */
    public function getAge(): ?int
    {
        if ($this->extractDate() != null) {
            $today = new \DateTime;
            $age = $today->diff($this->extractDate())->y;
            return $age;
        } else {
            return null;
        }
    }

    /**
     *  get date from pesel
     *
     * @return \DateTime|null
     */
    public function extractDate(): ?\DateTime
    {
        try {
            list($year, $month, $day) = sscanf($this->pesel, '%02s%02s%02s');

            switch (substr($month, 0, 1)) {
                case 2:
                case 3:
                    $month -= 20;
                    $year += 2000;
                    break;
                case 4:
                case 5:
                    $month -= 40;
                    $year += 2100;
                case 6:
                case 7:
                    $month -= 60;
                    $year += 2200;
                    break;
                case 8:
                case 9:
                    $month -= 80;
                    $year += 1800;
                    break;
                default:
                    $year += 1900;
                    break;
            }

            return checkdate($month, $day, $year) ? new \DateTime($year . "-" . $month) : null;
        } catch (\Exception $ex) {
            return null;
        }
    }

    /**
     * check valid pesel 
     * 
     * return bool
     */
    public function checkValid(): bool
    {
        //if is too short or too long
        if (mb_strlen($this->pesel, 'UTF-8') <= 10) {
            return false;
        }
        if (mb_strlen($this->pesel, 'UTF-8') > 11) {
            return false;
        }

        //check that string is only numbers
        if (!ctype_digit($this->pesel)) {
            return false;
        }

        try {
            $w = [1, 3, 7, 9];
            $wk = 0;
            for ($i = 0; $i <= 9; $i++) {
                $wk = ($wk + $this->pesel[$i] * $w[$i % 4]) % 10;
            }
            $k = (10 - $wk) % 10;
            if (!($this->pesel[10] == $k)) {
                return false;
            }

            //if date from pesel is empty pesel is incorrect
            if ($this->extractDate() === null) {
                return false;
            }
        } catch (\Exception $ex) {
            return false;
        }

        return true;
    }
}​
<?php

class PeselParser {

    /**
     * @var type 
     */
    private $pesel;

    /**
     * @param string $pesel
     */
    public function __construct($pesel) {
        $this->pesel = $pesel;
    }

    /**
     * get client age from pesel
     */
    public function getAge() {
        if ($this->extractDate() != null) {
            $today = new \DateTime;
            $age = $today->diff($this->extractDate())->y;
            return $age;
        } else {
            return null;
        }
    }

    /**
     * get date from pesel
     * 
     * @return DateTime|null
     */
    public function extractDate() {
        list($year, $month, $day) = sscanf($this->pesel, '%02s%02s%02s');

        switch (substr($month, 0, 1)) {
            case 2:
            case 3:
                $month -= 20;
                $year += 2000;
                break;
            case 4:
            case 5:
                $month -= 40;
                $year += 2100;
            case 6:
            case 7:
                $month -= 60;
                $year += 2200;
                break;
            case 8:
            case 9:
                $month -= 80;
                $year += 1800;
                break;
            default:
                $year += 1900;
                break;
        }

        return checkdate($month, $day, $year) ? new \DateTime($year . "-" . $month) : null;
    }

    /**
     * check valid pesel 
     * 
     * return bool
     */
    public function checkValid() {
        //if is too short or too long
        if (strlen($this->pesel) <= 10) {
            return false;
        }
        if (strlen($this->pesel) > 11) {
            return false;
        }

        //check that string is only numbers
        if (!ctype_digit($this->pesel)) {
            return false;
        }

        try {
            $w = array(1, 3, 7, 9);
            $wk = 0;
            for ($i = 0; $i <= 9; $i++) {
                $wk = ($wk + $this->pesel[$i] * $w[$i % 4]) % 10;
            }
            $k = (10 - $wk) % 10;
            if (!($this->pesel[10] == $k)) {
                return false;
            }
        } catch (\Exception $ex) {
            return false;
        }
        //if date from pesel is empty pesel is incorrect
        if ($this->extractDate() === null) {
            return false;
        }

        return true;
    }

}

Pobieranie tekstu po wystąpieniu ostatniego znaku

//get id from string example - bestloan.pl-12 -> 12
$dataTypeId = substr(strrchr(rtrim($searchIdValue, '-'), '-'), 1);

Filtrowanie tablicy bez wywalania 0 w wartości

 $parameters = array_filter($parameters,function($value) {
      return ($value !== null && $value !== false && $value !== ''); 
 });

Pętla do określonej liczby z dodaniem zer

<?php
$maxNumber = 99999;
$intLenght = strlen($maxNumber);

for ($number = 0; $number <= $maxNumber; $number++) {
    $lenght = strlen($number);
    $repeat = str_repeat(0, $intLenght - $lenght);
    $test = $repeat . $number;
    echo substr_replace($test, '-', 2, 0) . '<br>';
}

Sortowanie tablicy po kluczy według wartości

Przedz do linku


Parser pobierający dane między dwoma nazwisami

<?php

class InputsParser {

    /**
     * @param string $content
     * @return array
     */
    public static function initParser($content) {
        $inputsArray = [];
        //get all between [] to array     
        preg_match_all('@\[\s*input .*?\]@', $content, $inputsArray);
        return $inputsArray;
    }

}

Slug

<?php

namespace Utils\Slug;

Class Slug {

    public static function slugify($url, $maxLength = 500) {

        $S = array('/ą/', '/ż/', '/ź/', '/ę/', '/ć/', '/ń/', '/ó/', '/ł/', '/ś/', '/Ą/', '/Ż/', '/Ź/', '/Ę/', '/Ć/', '/Ń/', '/Ó/', '/Ł/', '/Ś/');
        $R = array('a', 'z', 'z', 'e', 'c', 'n', 'o', 'l', 's', 'A', 'Z', 'Z', 'E', 'C', 'N', 'O', 'L', 'S');
        $url = preg_replace($S, $R, $url);
        $url = strtolower(trim($url));
        $url = preg_replace('/\?/', '', $url);
        $url = preg_replace('/[^a-z0-9-]/', '-', $url);
        $url = preg_replace('/-+/', "-", $url);
        $url = substr($url, 0, $maxLength);
        return $url;
    }

}

Aktualna data plus liczba dni

<?php

class ConvertIntToDateByDayNumbers {
    
    /**
     * if parameter is integer and is greater than zero adds to actual date number days == $expire otherwise function return default value
     * 
     * @param string $expire
     * @return string
     */
    public static function init(string $expire):string {

        if (!is_numeric($expire) || $expire < 0) {
            return $expire;
        }

        return date('Y-m-d', strtotime("+" . $expire . "days"));
    }

}

Pobranie tekstu między dwoma nawisami []

//get all between [] to array     
preg_match_all('@\[.*?\]@', $this->multiStepForm->getCustomContent(), $inputsString);

Parser tagow inputa do tablicy

<?php

/**
 * Class parse data from string - example:
 * [ input value="asdasd" type="text" name="imie" placeholder="" class="" style="" validators="onlyNumbers, min(3), max(128)" items="1|aaa, 2|bbb" ]
 * Result getParseTags() = array:
    [
        'value' => 'asdasd',
        'type' => 'text',
        'name' => 'imie',
        'placeholder' => '',
        'class' => '',
        'style' => '',
        'validators' => [
            'onlyNumbers' => '',
            'min' => '3',
            'max' => '128'
        ],
        'items' => [
            1 => 'aaa',
            2 => 'bbb'
        ]
    ]
 */
class TagRecognizer {

    /**
     * @var string 
     */
    private $string;

    /**
     * 
     * @param string $string
     */
    public function __construct($string) {
        $this->string = $string;
    }

    /**
     * get array tags
     * 
     * @return array
     */
    public function getParseTags() {
        //get all between example="example" ::: (\w+) creates array $result[1]-----------([^"]*) creates array $result[2]
        preg_match_all('@(\w+)="([^"]*)"@', $this->string, $result);
        //new array created from $result[1](key) => $result[2](Value)
        $arrayTags = array_combine($result[1], $result[2]);

        return $this->parseTags($arrayTags);
    }

    /**
     * parse tags array to new array
     * 
     * @param array $arrayTags
     * 
     * @return array
     */
    private function parseTags(array $arrayTags) {

        $parseArrayTags = [];

        foreach ($arrayTags as $key => $value) {
            //items
            if ($key === 'items') {
                $parseArrayTags[$key] = $this->parseItems($value);
                //validators
            } elseif ($key === 'validators') {
                $parseArrayTags[$key] = $this->parseValidators($value);
                //simple tag
            } else {
                $parseArrayTags[$key] = $value;
            }
        }

        return $parseArrayTags;
    }

    /**
     *  parse items in string
     * 
     * @param string $value
     * 
     * @return array
     */
    private function parseItems($value) {
        $arrInfo = explode("#", $value);

        $newArray = [];
        foreach ($arrInfo as $item) {
            $values = explode("|", $item);
            $newArray[trim($values[0])] = $values[1];
        }

        return $newArray;
    }

    /**
     * parse validators in string
     * 
     * @param string $value
     * 
     * @return array
     */
    private function parseValidators($value) {
        $arrInfo = explode(",", $value);
        $newArray = [];
        foreach ($arrInfo as $item) {

            // if item has () in value - $keyValidatorValue is equal text between this brackets
            if (strpos($item, '(') !== false && strpos($item, ')') !== false) {

                preg_match('@\((.*?)\)@', $item, $match);

                $keyValidatorValue = $match[1];
            } else {
                $keyValidatorValue = '';
            }

            //$newArray[$item] - delete bracket with text and trim $item
            $newArray[trim(preg_replace("@\([^)]+\)@", "", $item))] = $keyValidatorValue;
        }

        return $newArray;
    }

}
<?php

namespace MultiStepFormBundle\Tests\TagRecognizer;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use MultiStepFormBundle\Domain\Tag\Recognizer\TagRecognizer;

class TagRecognizerTest extends WebTestCase {

    /**
     * 
     * @dataProvider dataProvider
     */
    public function testTagRecognizer($expect, $string) {
        $result = new TagRecognizer($string);
        $result = $result->getParseTags();

        return $this->assertEquals($expect, $result);
    }

    public function dataProvider() {
        return [
            [   
                [
                    'value' => 'asdasd',
                    'type' => 'text',
                    'name' => 'imie',
                    'placeholder' => '',
                    'class' => '',
                    'style' => '',
                    'validators' => [
                        'onlyNumbers' => '',
                        'min' => '3',
                        'max' => '128'
                    ],
                    'items' =>[
                        1 => 'aaa',
                        2 => 'bbb'
                    ]
                ] ,
                '[ input value="asdasd" type="text" name="imie" placeholder="" class="" style="" validators="onlyNumbers, min(3), max(128)" items="1|aaa# 2|bbb"      ]'
            ],
            //==========================================================================================================================================================
            //==========================================================================================================================================================
            [   
                [
                    'value' => '12323435',
                    'type' => 'integer',
                    'name' => 'example name',
                    'placeholder' => 'example placeholder',
                    'class' => 'form-controll'
                ],
                '[ input value="12323435" type="integer" name="example name" placeholder="example placeholder" class="form-controll" ]'
            ],
            //==========================================================================================================================================================
            //==========================================================================================================================================================
            [   
                [
            
                    'type' => 'hidden',
                    'id' => 'container',
                    'placeholder' => 'bummmmmm',
                    'class' => 'form-custom',
                    'validators' => [
                        'example' => '',
                        'email' => '',
                        'phone' => '',
                        'lenght' => '200'
                    ],
                ],
                '[ input type="hidden" id="container"  placeholder="bummmmmm" class="form-custom" validators="example, email, phone, lenght(200)" ]'
            ],
            //==========================================================================================================================================================
            //==========================================================================================================================================================
            [   
                [
                    'type' => 'date',
                    'id' => 'data_container',
                    'placeholder' => '2019-01-01',
                    'class' => 'date-custom',
                    'exampleTag' => 'lorem ipsum',
                    'items' =>[
                        1 => 'one',
                        2 => 'two',
                        3 => 'three'
                    ],
                    'validators' => [
                        'date' => '',
                        'lenght' => '202'
                    ],
                ],
                '[ input type="date" id="data_container"  placeholder="2019-01-01" class="date-custom" exampleTag="lorem ipsum" items="1|one# 2|two# 3|three" validators="date, lenght(202)" ]'
            ],
            //==========================================================================================================================================================
            //==========================================================================================================================================================
            [   
                [
                    'name' => 'example_name_value',
                    'otherTag' => 'example_value', 
                    'id' => 'my-id', 
                    'class' => 'my_amazing_class', 
                    
                ],
                '[input name="example_name_value" otherTag="example_value" id="my-id" class="my_amazing_class"]'
            ],
            //==========================================================================================================================================================
            //==========================================================================================================================================================
            [   
                [
                    'name' => 'example_name_value',
                    'otherTag' => 'example_value', 
                    'id' => 'my-id', 
                    'class' => 'my_amazing_class',
                    'validators' => [
                        'custom_validator' => '',
                        'lenght' => '18',
                        'other_validator' => '',
                        'expectedValue' => '12',
                    ]
                ],
                '[input    name="example_name_value"   otherTag="example_value"   id="my-id"   class="my_amazing_class"   validators="custom_validator, lenght(18), other_validator, expectedValue(12)"]'
            ],
            //==========================================================================================================================================================
            //==========================================================================================================================================================
            [   
                [],
                '[    ]'
            ],
            //==========================================================================================================================================================
            //==========================================================================================================================================================
            [   
                [],
                ''
            ],
            //==========================================================================================================================================================
            //==========================================================================================================================================================
            [   
                [],
                '[input]'
            ],
            //==========================================================================================================================================================
            //==========================================================================================================================================================
            [   
                [
                    'name' => 'example_name_value',
                    'otherTag' => 'example_value', 
                    'id' => 'my-id', 
                    'validators' => [
                        'required' => '',
                    ]                    
                ],
                '[input name="example_name_value" otherTag="example_value" id="my-id" validators="required"]'
            ],
            //==========================================================================================================================================================
            //==========================================================================================================================================================
            
        ];
    }

}

?>

Parser inputa

 <?php
$attribs = ' id= "header" class = "foobar" style ="background-color:#fff; color: red; "';
$attribs = 'type="text"      name="janusz"  class="form-control"          onclick="myFunction()"';

$x = new SimpleXMLElement("<element $attribs />");
echo '<pre>';
var_dump($x);
echo '</pre>';

?>

Tuning php

//php.ini
php_value upload_max_filesize 120M //file size
php_value post_max_size 120M
php_value max_execution_time 200
php_value max_input_time 200

Sprawdzanie czy tablica jest pusta

<?php

$array = ['key' => ''];

if (empty(array_filter($array))){
    echo 'empty';
}else{
    echo 'not empty';
}

Array merge

$customReceivers = $this->receiversRepository->findAll();

        if (empty($customReceivers)) {
            return;
        }

        foreach ($customReceivers as $singleReceivers) {
            $receiverConfig = $this->dataProviders[$singleReceivers->getType()];
            array_push($this->receivers, new Receiver(
                $receiverConfig['app'],
                $receiverConfig['account'],
                array_merge($receiverConfig, [
                    'value' => $singleReceivers->getData(),
                ]),
                $receiverConfig['methodName']
            ));
        }

Przykładowa klasa z configiem

namespace App\Domain\Log\Statuses;

class Statuses {

    const STATUS_SUCCESS = 1;
    const STATUS_ERROR = 2;

    private static $types = [
        self::STATUS_SUCCESS => 'success',
        self::STATUS_ERROR => 'error',
    ];

    /**
     * get types
     * 
     * @return array
     */
    public static function getTypes(): array {
        return self::$types;
    }

}

Przekazywanie wybranego klucza tablicy

$array=[
	0 => ['id' => 1,'name' => 'janusz'],
	1 => ['id' => 2,'name' => 'pioter'],

];

var_dump(array_column($array, 'name'));

//array(2) { [0]=> string(6) "janusz" [1]=> string(6) "pioter" }

Short isset w php 7

//  PHP 5.3+
$fruit= isset($_GET['fruit']) ? $_GET['fruit'] : 'banana';

// PHP 7
$fruit = $_GET['fruit'] ?? 'banana';

Funkcja usuwająca folder

function deleteDir($dirPath) {
    if (! is_dir($dirPath)) {
        throw new InvalidArgumentException("$dirPath must be a directory");
    }
    if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
        $dirPath .= '/';
    }
    $files = glob($dirPath . '*', GLOB_MARK);
    foreach ($files as $file) {
        if (is_dir($file)) {
            deleteDir($file);
        } else {
            unlink($file);
        }
    }
    rmdir($dirPath);
}

Funkcja kopiująca folder na serwerze

function copy_directory($source, $dest)
{
    // Check for symlinks
    if (is_link($source)) {
        return symlink(readlink($source), $dest);
    }
    // Simple copy for a file
    if (is_file($source)) {
        return copy($source, $dest);
    }
    // Make destination directory
    if (!is_dir($dest)) {
        mkdir($dest);
    }
    // Loop through the folder
    $dir = dir($source);
    while (false !== $entry = $dir->read()) {
        // Skip pointers
        if ($entry == '.' || $entry == '..') {
            continue;
        }
        // Deep copy directories
        copy_directory("$source/$entry", "$dest/$entry");
    }
    // Clean up
    $dir->close();
    return true;
}

Ładowanie wszystkich zdjęć z folderu

Z np lighboxem:

<?php
$images = glob("{small/*.jpg,*.bmp,*.gif,*.png,*.jpeg}",GLOB_BRACE);
$images_big = glob("{400/*.jpg,*.bmp,*.gif,*.png,*.jpeg}",GLOB_BRACE);?>
<?php foreach (array_combine($images, $images_big) as $image => $image_big): ?>
  <div class="img_item"><img class="slider_img" src="<?php echo $image; ?>" alt=""></div>
  <div class="img_item"><img class="slider_img" src="<?php echo $image_big; ?>" alt=""></div>
<?php endforeach ?>

Ładowanie samych pojedyńczych zdjęć:

<?php
$images = glob("{*.jpg,*.bmp,*.gif,*.png,*.jpeg}",GLOB_BRACE);?>
<?php foreach ($images as $image): ?>
  <div class="img_item"><img class="slider_img" src="<?php echo $image; ?>" alt=""></div>
<?php endforeach ?>

Informacje o statusie domeny

$url = 'http://allegro.pl';
print_r(get_headers($url, 1));
////////////////lub//////////////////
$strona = file_get_contents('http://zalando.pl/');
echo "<pre>";
var_dump($http_response_header);
echo "</pre>";
exit();