/ Gists / PHP

Gists - PHP

On gists

Collection (filter, map, sort ... in one)

PHP Libs PHP

Collection.php #

<?php

/* https://betterprogramming.pub/how-to-make-your-php-code-beautiful-with-chainable-methods-83d8832b1b16 */

class Collection
{
    private $array;
    public function __construct($array)
    {
        $this->array = $array;
    }
    public function filter($callback)
    {
        $this->array = array_filter($this->array, $callback);
        return $this;
    }
    public function map($callback)
    {
        $this->array = array_map($callback, $this->array);
        return $this;
    }
    public function sort($callback)
    {
        usort($this->array, $callback);
        return $this;
    }
    public function execute()
    {
        return $this->array;
    }
}


$characters = new Collection([
    'Maggie Simpson',
    'Edna Krabappel',
    'Marge Simpson',
    'Lisa Simpson',
    'Moe Szyslak',
    'Waylon Smithers',
    'Homer Simpson',
    'Bart Simpson'
]);
$simpsons = $characters
    ->filter(function ($character) {
        return preg_match('/^.+\sSimpson$/', $character);
    })
    ->map(function ($character) {
        return str_replace(' Simpson', '', $character);
    })
    ->sort(function ($a, $b) {
        return strcasecmp($a, $b);
    })
    ->execute();
var_dump($simpsons); // ['Bart', 'Homer', 'Lisa', 'Maggie', 'Marge']

On gists

Kometa comments - more ways to refactor

Refactoring PHP

comments.php #

<?php

//  if hell
if ($commentRow->type == 'forum')
{
    $baseUrl = '/diskuse';
}

if ($commentRow->type == 'clanek')
{
    $baseUrl = '/clanky/' . \dibi::fetchSingle('SELECT seo FROM clanky WHERE id = %i', $commentRow->rellID);
}

if ($commentRow->type == 'zapas')
{
    $baseUrl = '/zapas/' .  $commentRow->rellID;
}

if ($commentRow->type == 'stranka')
{
    $baseUrl = '/' . \dibi::fetchSingle('SELECT url FROM navigace WHERE id = %i', $commentRow->rellID);
}

\Redirect::url($baseUrl .'?l='.$newPageNo.'&parentNode='.$commentRow->parent_sibling_id.'#cmt-'.$commentRow->id);


// map table
$baseUrlMap = [
    'forum' => '/diskuse',
    'clanek' => '/clanky/' . \dibi::fetchSingle('SELECT seo FROM clanky WHERE id = %i', $commentRow->rellID),
    'zapas' => '/zapas/' .  $commentRow->rellID,
    'stranka' => '/' . \dibi::fetchSingle('SELECT url FROM navigace WHERE id = %i', $commentRow->rellID),
];

$baseUrl = '';

if (isset($baseUrlMap[$commentRow->type])) {
    $baseUrl = $baseUrlMap[$commentRow->type];
}



// 3 callback fns
$baseUrlMap = [
    'forum' => '/diskuse',
    'clanek' => function() use ($commentRow) {
        return '/clanky/' . \dibi::fetchSingle('SELECT seo FROM clanky WHERE id = %i', $commentRow->rellID);
    },
    'zapas' => function() use ($commentRow) {
        return '/zapas/' . $commentRow->rellID;
    },
    'stranka' => function() use ($commentRow) {
        return '/' . \dibi::fetchSingle('SELECT url FROM navigace WHERE id = %i', $commentRow->rellID);
    },
];

$baseUrl = '';

if (isset($baseUrlMap[$commentRow->type])) {
    if (is_callable($baseUrlMap[$commentRow->type])) {
        $baseUrl = $baseUrlMap[$commentRow->type]();
    } else {
        $baseUrl = $baseUrlMap[$commentRow->type];
    }
}



// Factories

$baseUrl = '';

interface UrlGenerator {
    public function generateUrl($commentRow);
}

class ForumUrlGenerator implements UrlGenerator {
    public function generateUrl($commentRow) {
        return '/diskuse';
    }
}

class ClanekUrlGenerator implements UrlGenerator {
    public function generateUrl($commentRow) {
        return '/clanky/' . \dibi::fetchSingle('SELECT seo FROM clanky WHERE id = %i', $commentRow->rellID);
    }
}

class ZapasUrlGenerator implements UrlGenerator {
    public function generateUrl($commentRow) {
        return '/zapas/' .  $commentRow->rellID;
    }
}

class StrankaUrlGenerator implements UrlGenerator {
    public function generateUrl($commentRow) {
        return '/' . \dibi::fetchSingle('SELECT url FROM navigace WHERE id = %i', $commentRow->rellID);
    }
}

$generators = [
    'forum' => new ForumUrlGenerator(),
    'clanek' => new ClanekUrlGenerator(),
    'zapas' => new ZapasUrlGenerator(),
    'stranka' => new StrankaUrlGenerator(),
];

$commentType = $commentRow->type;
if (isset($generators[$commentType])) {
    $baseUrl = $generators[$commentType]->generateUrl($commentRow);
}


// fns for all with argument
$baseUrlMap = [
    'forum' => function($row) {
        return '/diskuse';
    },
    'clanek' => function($row) {
        return '/clanky/' . \dibi::fetchSingle('SELECT seo FROM clanky WHERE id = %i', $row->rellID);
    },
    'zapas' => function($row) {
        return '/zapas/' .  $row->rellID;
    },
    'stranka' => function($row) {
        return '/' . \dibi::fetchSingle('SELECT url FROM navigace WHERE id = %i', $row->rellID);
    },
];

$commentType = $commentRow->type;
if (isset($baseUrlMap[$commentType])) {
    $baseUrl = $baseUrlMap[$commentType]($commentRow);
}



// FactoryGenerator

interface UrlGenerator {
    public function generateUrl($commentRow);
}

class ForumUrlGenerator implements UrlGenerator {
    public function generateUrl($commentRow) {
        return '/diskuse';
    }
}

class ClanekUrlGenerator implements UrlGenerator {
    public function generateUrl($commentRow) {
        return '/clanky/' . \dibi::fetchSingle('SELECT seo FROM clanky WHERE id = %i', $commentRow->rellID);
    }
}

class ZapasUrlGenerator implements UrlGenerator {
    public function generateUrl($commentRow) {
        return '/zapas/' .  $commentRow->rellID;
    }
}

class StrankaUrlGenerator implements UrlGenerator {
    public function generateUrl($commentRow) {
        return '/' . \dibi::fetchSingle('SELECT url FROM navigace WHERE id = %i', $commentRow->rellID);
    }
}

class UrlGeneratorFactory {
    public static function createGenerator($type): UrlGenerator {
        $generators = [
            'forum' => new ForumUrlGenerator(),
            'clanek' => new ClanekUrlGenerator(),
            'zapas' => new ZapasUrlGenerator(),
            'stranka' => new StrankaUrlGenerator(),
        ];

        return $generators[$type] ?? null;
    }
}

$commentType = $commentRow->type;
$generator = UrlGeneratorFactory::createGenerator($commentType);

if ($generator) {
    $baseUrl = $generator->generateUrl($commentRow);
}


// Dalsi o neco lepsi
class UrlGeneratorFactory {
    public static function createGenerator($type): ?UrlGenerator {
        $generators = [
            'forum' => function () {
                return new ForumUrlGenerator();
            },
            'clanek' => function () {
                return new ClanekUrlGenerator();
            },
            'zapas' => function () {
                return new ZapasUrlGenerator();
            },
            'stranka' => function () {
                return new StrankaUrlGenerator();
            },
        ];

        return $generators[$type] ? $generators[$type]() : null;
    }
}

$commentType = $commentRow->type;
$generator = UrlGeneratorFactory::createGenerator($commentType);

if ($generator) {
    $baseUrl = $generator->generateUrl($commentRow);
}



// Moje verze, lazy, nejefektivnejsi

class UrlGeneratorFactory {
    public static function createGenerator($type): ?UrlGenerator {
        $generators = [
            'forum' => ForumUrlGenerator::class,
            'clanek' => ClanekUrlGenerator::class,
            'zapas' => ZapasUrlGenerator::class,
            'stranka' => StrankaUrlGenerator::class,
        ];

        if (isset($generators[$type])) {
            return new $generators[$type]();
        }

        return null;
    }
}

$commentType = $commentRow->type;
$generator = UrlGeneratorFactory::createGenerator($commentType);

if ($generator) {
    $baseUrl = $generator->generateUrl($commentRow);
}




// Claude 3.5
// Strategy pattern
<?php

interface CommentRedirectStrategy {
    public function getBaseUrl(object $commentRow): string;
}

class ForumRedirectStrategy implements CommentRedirectStrategy {
    public function getBaseUrl(object $commentRow): string {
        return '/diskuse';
    }
}

class ArticleRedirectStrategy implements CommentRedirectStrategy {
    public function getBaseUrl(object $commentRow): string {
        return '/clanky/' . \dibi::fetchSingle('SELECT seo FROM clanky WHERE id = %i', $commentRow->rellID);
    }
}

class MatchRedirectStrategy implements CommentRedirectStrategy {
    public function getBaseUrl(object $commentRow): string {
        return '/zapas/' . $commentRow->rellID;
    }
}

class PageRedirectStrategy implements CommentRedirectStrategy {
    public function getBaseUrl(object $commentRow): string {
        return '/' . \dibi::fetchSingle('SELECT url FROM navigace WHERE id = %i', $commentRow->rellID);
    }
}

class CommentRedirectHandler {
    private array $strategies = [];

    public function addStrategy(string $type, string $strategyClass): void {
        if (!is_subclass_of($strategyClass, CommentRedirectStrategy::class)) {
            throw new \InvalidArgumentException("$strategyClass musí implementovat CommentRedirectStrategy");
        }
        $this->strategies[$type] = $strategyClass;
    }

    public function redirect(object $commentRow, int $newPageNo): void {
        if (!isset($this->strategies[$commentRow->type])) {
            throw new \InvalidArgumentException("Neznámý typ komentáře: {$commentRow->type}");
        }

        $strategyClass = $this->strategies[$commentRow->type];
        $strategy = new $strategyClass(); // Vytvoření instance až když je potřeba
        $baseUrl = $strategy->getBaseUrl($commentRow);

        $redirectUrl = sprintf(
            '%s?l=%d&parentNode=%d#cmt-%d',
            $baseUrl,
            $newPageNo,
            $commentRow->parent_sibling_id,
            $commentRow->id
        );

        \Redirect::url($redirectUrl);
    }
}

// Použití:
$handler = new CommentRedirectHandler();
$handler->addStrategy('forum', ForumRedirectStrategy::class);
$handler->addStrategy('clanek', ArticleRedirectStrategy::class);
$handler->addStrategy('zapas', MatchRedirectStrategy::class);
$handler->addStrategy('stranka', PageRedirectStrategy::class);

// Při zpracování komentáře:
$handler->redirect($commentRow, $newPageNo);




// slozitejsi vic tovaren
<?php

interface CommentRedirectStrategy {
    public function getBaseUrl(object $commentRow): string;
}

class ForumRedirectStrategy implements CommentRedirectStrategy {
    public function getBaseUrl(object $commentRow): string {
        return '/diskuse';
    }
}

class ArticleRedirectStrategy implements CommentRedirectStrategy {
    public function getBaseUrl(object $commentRow): string {
        return '/clanky/' . \dibi::fetchSingle('SELECT seo FROM clanky WHERE id = %i', $commentRow->rellID);
    }
}

class MatchRedirectStrategy implements CommentRedirectStrategy {
    public function getBaseUrl(object $commentRow): string {
        return '/zapas/' . $commentRow->rellID;
    }
}

class PageRedirectStrategy implements CommentRedirectStrategy {
    public function getBaseUrl(object $commentRow): string {
        return '/' . \dibi::fetchSingle('SELECT url FROM navigace WHERE id = %i', $commentRow->rellID);
    }
}

class CommentRedirectStrategyFactory {
    private array $strategies = [
        'forum' => ForumRedirectStrategy::class,
        'clanek' => ArticleRedirectStrategy::class,
        'zapas' => MatchRedirectStrategy::class,
        'stranka' => PageRedirectStrategy::class,
    ];

    public function createStrategy(string $type): CommentRedirectStrategy {
        if (!isset($this->strategies[$type])) {
            throw new \InvalidArgumentException("Neznámý typ komentáře: {$type}");
        }

        $strategyClass = $this->strategies[$type];
        return new $strategyClass();
    }
}

class CommentRedirectHandler {
    private CommentRedirectStrategyFactory $factory;

    public function __construct(CommentRedirectStrategyFactory $factory) {
        $this->factory = $factory;
    }

    public function redirect(object $commentRow, int $newPageNo): void {
        $strategy = $this->factory->createStrategy($commentRow->type);
        $baseUrl = $strategy->getBaseUrl($commentRow);

        $redirectUrl = sprintf(
            '%s?l=%d&parentNode=%d#cmt-%d',
            $baseUrl,
            $newPageNo,
            $commentRow->parent_sibling_id,
            $commentRow->id
        );

        \Redirect::url($redirectUrl);
    }
}

// Použití:
$factory = new CommentRedirectStrategyFactory();
$handler = new CommentRedirectHandler($factory);

// Při zpracování komentáře:
$handler->redirect($commentRow, $newPageNo);

On gists

lambda usort sorting

PHP

sort.php #

<?php
$x = [
	[
		'name' => 'BBB',
		'pts' => 30,
	],
	[
		'name' => 'AAA',
		'pts' => 90,
	],
	[
		'name' => 'CCC',
		'pts' => 40,
	]
];

usort($x, sortBy('pts', 'DESC')); // Změna zde - přidán parametr pro směr řazení

function sortBy($k, $sortOrder = 'ASC') // Změna zde - přidán druhý parametr s výchozí hodnotou ASC
{
	return function($a, $b) use ($k, $sortOrder)
	{
		$result = $a[$k] <=> $b[$k];
		return ($sortOrder === 'ASC') ? $result : -$result; // Změna zde - záporná hodnota pro DESC řazení
	};
}

echo "<pre>";
print_r($x);



//  2 way


function customSort($a, $b, $key, $sortOrder) {
    return $sortOrder === 'ASC' ? ($a[$key] <=> $b[$key]) : ($b[$key] <=> $a[$key]);
}

$key = 'name'; // Změňte podle sloupce, podle kterého chcete řadit
$sortOrder = 'ASC'; // Změňte na 'DESC' pro sestupné řazení

usort($x, function($a, $b) use ($key, $sortOrder) {
    return customSort($a, $b, $key, $sortOrder);
});

echo "<pre>";
print_r($x);

On gists

array_walk_recursive

PHP

demo.php #

<?php

$data = array(
    array('id' => 1, 'name' => 'John', 'children' => array('Alice', 'Bob')),
    array('id' => 2, 'name' => 'Jane', 'children' => array('Charlie', 'David')),
);

function add_last_name(&$value, $key) {
    if ($key === 'name') {
        $value .= ' Doe';
    }
}

array_walk_recursive($data, 'add_last_name');

print_r($data);

/*

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => John Doe
            [children] => Array
                (
                    [0] => Alice Doe
                    [1] => Bob Doe
                )
        )
    [1] => Array
        (
            [id] => 2
            [name] => Jane Doe
            [children] => Array
                (
                    [0] => Charlie Doe
                    [1] => David Doe
                )
        )
)


*/

On gists

PHP nested value in multi array with own separator

PHP Libs PHP

fn.php #

<?php

function getNestedValue($array, $path, $separator = '.') {
    $keys = explode($separator, $path);
    
    foreach ($keys as $key) {
        if (isset($array[$key])) {
            $array = $array[$key];
        } else {
            return null; // nebo hodnotu podle vašich potřeb
        }
    }
    
    return $array;
}


$x = [
    'a' => [
        'b' => [
            'c' => 'FINAL C ... ;)'
        ],
    ],
];

echo getNestedValue($x, 'a.b.c');

On gists

PHP iterator (Record OOP class)

PHP

Record1.php #

<?php

class Record {
    private $data = [];
    private $currentIndex = 0;

    public function addRecord($value) {
        $this->data[] = $value;
    }

    public function getRecord() {
        if ($this->currentIndex < count($this->data)) {
            $record = $this->data[$this->currentIndex];
            $this->currentIndex++;
            return $record;
        } else {
            return null;
        }
    }
}

// Vytvoření instance třídy
$recordKeeper = new Record();

// Přidání záznamů
$recordKeeper->addRecord("John");
$recordKeeper->addRecord(30);
$recordKeeper->addRecord("New York");

// Získání a postupné procházení všech záznamů pomocí cyklu foreach a metody getRecord()
echo "All records:<br>";
while ($record = $recordKeeper->getRecord()) {
    echo $record . "<br>";
}

On gists

PHP - Yield

PHP

example.php #

<?php

function generatorFunction() {
    yield 1;
    yield 2;
    yield 3;
}

// Použití generátoru
$generator = generatorFunction();

foreach ($generator as $value) {
    echo $value . ' ';
}

// Výstup: 1 2 3


/* -----------------------------  */


names.txt 
===
John Doe
Jane Smith
Bob Johnson
Alice Williams
... (a mnoho dalších jmen)



function readNamesFromFile($filename) {
    $file = fopen($filename, 'r');
    if (!$file) {
        throw new Exception("Nepodařilo se otevřít soubor.");
    }

    while (($line = fgets($file)) !== false) {
        yield trim($line);
    }

    fclose($file);
}

// Použití generátoru pro zpracování jmen ze souboru
$generator = readNamesFromFile('names.txt');

foreach ($generator as $name) {
    // Provádění operace s každým jménem
    echo "Hello, $name!" . PHP_EOL;
}


/* -----------------------------  */


function randomDataGenerator($count) {
    for ($i = 0; $i < $count; $i++) {
        yield rand(1, 100); // Generujeme náhodné číslo v rozmezí 1 až 100
    }
}

// Generujeme 10 náhodných čísel
$generator = randomDataGenerator(10);

foreach ($generator as $number) {
    // Provádění operace s každým náhodným číslem
    echo $number . ' ';
}


/* -----------------------------  */


function searchValueInArray(array $array, $value) {
    foreach ($array as $item) {
        if (in_array($value, $item)) {
            yield $item;
        }
    }
}

// Příklad použití:

$data = array(
    array('id' => 1, 'name' => 'John'),
    array('id' => 2, 'name' => 'Jane'),
    array('id' => 3, 'name' => 'Bob'),
    array('id' => 4, 'name' => 'Alice')
);

$searchValue = 'Bob';

foreach (searchValueInArray($data, $searchValue) as $result) {
    echo "Hodnota nalezena: " . $result['name'] . "\n";
}

On gists

sort.php

PHP

sort.php #

public function sortInCurrentLanguage(array $items)
	{
		$oldLocale = setlocale(LC_ALL, 0);
		setlocale (LC_ALL, 'cs_CZ.UTF-8');
		uasort($items, 'strcoll');
		setlocale (LC_ALL, $oldLocale);

		

On gists

Sort in current language

PHP Libs PHP

sort.php #

<?php

public function sortInCurrentLanguage(array $items)
{
		$oldLocale = setlocale(LC_ALL, 0);
		setlocale (LC_ALL, 'cs_CZ.UTF-8');
		uasort($items, 'strcoll');
		setlocale (LC_ALL, $oldLocale);

}

On gists

Fake visitor u productu ;)

PHP

fake-visitor-by-gtp.php #

<?php
session_start();

// Interval v sekundách, po kterém se změní počet prohlížejících
$interval = 10; // Například každých 10 sekund

// Kontrola, zda již byl počet prohlížejících inicializován v session
if (!isset($_SESSION['prohlizeloLidi'])) {
  // Pokud ne, vygenerujte falešný počet prohlížejících (např. 65)
  $_SESSION['prohlizeloLidi'] = 65;
  $_SESSION['lastUpdate'] = time(); // Poslední aktualizace na aktuální čas
}

// Získání počtu prohlížejících z session
$prohlizeloLidi = $_SESSION['prohlizeloLidi'];

// Získání času poslední aktualizace
$lastUpdate = $_SESSION['lastUpdate'];

// Aktuální čas
$currentTime = time();

// Počet sekund od poslední aktualizace
$secondsSinceLastUpdate = $currentTime - $lastUpdate;

// Změna počtu prohlížejících po uplynutí intervalu
if ($secondsSinceLastUpdate >= $interval) {
  // Generování náhodného směru změny (-1 pro snížení, 1 pro zvýšení)
  $changeDirection = rand(0, 1) === 0 ? -1 : 1;

  // Generování náhodného počtu prohlížejících, který se přičte nebo odečte od aktuálního počtu
  $changeAmount = rand(1, 5); // Například změna o 1 až 5 prohlížejících

  // Nový počet prohlížejících
  $prohlizeloLidi += $changeDirection * $changeAmount;

  // Ošetření, aby počet neklesl pod nulu
  if ($prohlizeloLidi < 0) {
    $prohlizeloLidi = 0;
  }

  // Aktualizace posledního aktualizovaného času
  $_SESSION['lastUpdate'] = $currentTime;
}

// Uložení nového počtu prohlížejících do session
$_SESSION['prohlizeloLidi'] = $prohlizeloLidi;

// Vypsání informace
echo "Toto zboží si právě prohlíží $prohlizeloLidi lidí.";

// Ukončení session
session_write_close();
?>