/ Gists / AW

Gists - AW

On gists

Ajax events on forms (Vue)

AW

vue-form-events.vue #

<template>
  <form
    class="mt-8"
    method="post"
    :id="frmId"
    v-ajax-on-before="() => $emit('onPreloader', true)"
    v-ajax-on-success="() => $emit('onPreloader', false)"
    v-ajax-on-error="() => $emit('onPreloader', false)"
    v-nette-form
    data-ajax-use-router
  >

On gists

AW: Vue in Latte

AW

file.latte #

<aw-alert v-for="flash in {$control->getVueDataVar('flashes')}" :type="flash.type">{_}Je to správně? Zkuste číslo opsat ještě jednou.{/_}</aw-alert>

<template v-for="image in $presenter.voucher.photos" :key="image.id">
  <aw-img src="/assets/temp/enjoyment-1.jpg" class="rounded-ambi" :image="image" size="1230x870x8" />
</template>


<div class="Filters justify-center">
	<ambi-filter-tag 
		v-for="(filter, index) in $controls['filterTagsList'].filters"
		:key="index"
		:filter="filter"
		filter-url
		class="FilterTag -Xs mb-2 lg:mb-4 mr-2 lg:mr-4"
	/>
</div>

On gists

Delete recursively from child to parent

PHP AW

delete-recursively-from-child.ph #

<?php

	private function deleteDuplicateRecursive(Tables\Navigation $duplicateItem)
	{
		/*
		// OLD
		$findDescendants = function(Tables\Navigation $parent, array $stack = [], $level = 1) use (&$findDescendants) {
			$children = $this->navigation->getAdjacencyList($parent->domain_id)->getChildren($parent->id);
			
			foreach ($children as $child) {
				$stack[$level][] = $child;
				$stack = $findDescendants($child, $stack, $level + 1);
			} 
				
			return $stack;
		};

		// mazeme deti odspoda nahoru
		$descendants = $findDescendants($duplicateItem);

		foreach (array_reverse($descendants, true) as $level => $descendantArr) {
			foreach ($descendantArr as $descendant) {
				$this->deleteDuplicate($descendant);
			}
		}
		*/

    // NEW, better, shorter
		$children = $this->navigation->getAdjacencyList($duplicateItem->domain_id)->getChildren($duplicateItem->id);
		foreach ($children as $child) {
			$this->deleteDuplicateRecursive($child);
		}

		// na zaver i roota
		$this->deleteDuplicate($duplicateItem);
	}

On gists

Normalizace dat

PHP AW

normalizace.php #

<?php 

// 1) single fns ..

$data = [
    '400,22 je super cislo a neobsahuje ani @',
    'Symbol @ je bezvič',
    '@@@ nebo XXX?',
    'Tady nic',
];

$NaNicToNeplati = function() {
    return null;
};

$NumberDashToDot = function($value) {
    if (preg_match('~\d+,\d+~', $value)) {
        return str_replace(',', '.', $value);
    }

    return null;
};

$RemoveZavinac = function($value) {
    if (preg_match('~@~', $value)) {
        return str_replace('@', '', $value);
    }

    return null;
};

$RemoveXXX = function($value) {
    if (preg_match('~X~', $value)) {
        return str_replace('X', 'maleX', $value);
    }

    return null;
};

$filters = [
    'NumberDashToDot' => $NumberDashToDot,
    'NaNicToNeplati' => $NaNicToNeplati,
    'RemoveZavinac' => $RemoveZavinac,
    'RemoveXXX' => $RemoveXXX,
];


 $evaluate = function($data, $filters) {
    $results = [];
    foreach ($data as $value) {
        $origValue = $value;
        $result = [
            'met' => [],
            'notMet' => [],
            'transformations' => [],
            'origValue' => $value,
            'finalValue' => null,
        ];

        foreach ($filters as $fnName => $fnClosure) {
            if ($valueNormalized = $fnClosure($value)) {
                $value = $valueNormalized;
                
                $result['met'][] = $fnName;
                $result['transformations'][$fnName] = $valueNormalized;
            } else {
                $result['notMet'][] = $fnName;
            }
        }

        
        $result['finalValue'] = $value;

        $results[] = $result;
    }

    return $results;

};

$results = $evaluate($data, $filters);

echo "<pre>";
print_r($results);
echo "</pre>";



// OOP
class DataTransformer
{
    private $filters;

    public function __construct(array $filters)
    {
        $this->filters = $filters;
    }

    public function transform(array $data): array
    {
        return array_map(function ($value) {
            $result = [
                'met' => [],
                'notMet' => [],
                'transformations' => [],
                'origValue' => $value,
                'finalValue' => null,
            ];

            foreach ($this->filters as $filter) {
                if ($filter->apply($value)) {
                    $result['met'][] = $filter->getName();
                    $result['transformations'][$filter->getName()] = $value;
                } else {
                    $result['notMet'][] = $filter->getName();
                }
            }

            $result['finalValue'] = $value;

            return $result;
        }, $data);
    }
}

interface FilterInterface
{
    public function apply(string &$value): bool;
    public function getName(): string;
}

class NumberDashToDotFilter implements FilterInterface
{
    public function apply(string &$value): bool
    {
        if (preg_match('~\d+,\d+~', $value)) {
            $value = str_replace(',', '.', $value);
            return true;
        }

        return false;
    }

    public function getName(): string
    {
        return 'NumberDashToDot';
    }
}

class RemoveZavinacFilter implements FilterInterface
{
    public function apply(string &$value): bool
    {
        if (strpos($value, '@') !== false) {
            $value = str_replace('@', '', $value);
            return true;
        }

        return false;
    }

    public function getName(): string
    {
        return 'RemoveZavinac';
    }
}

// Přidat další filtry podle potřeby

$data = [
    '400,22 je super cislo a neobsahuje ani @',
    'Symbol @ je bezvič',
    '@@@ nebo XXX?',
    'Tady nic',
];

$filters = [
    new NumberDashToDotFilter(),
    new RemoveZavinacFilter(),
    // Přidat další filtry podle potřeby
];

$transformer = new DataTransformer($filters);
$results = $transformer->transform($data);

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

On gists

Pivot table (2 zpusoby)

MySql MySql - advanced AW

pivot-table.sql #


-- https://diskuse.jakpsatweb.cz/?action=vthread&forum=28&topic=174158
-- Pivotni tabulka

-- Ja
SELECT user_id, (
  SUM(IF (action_type = 'login', 1, 0)) 
) AS 'login', (
  SUM(IF (action_type = 'publish', 1, 0)) 
) AS 'publish', (
  SUM(IF (action_type = 'download', 1, 0)) 
) AS 'download', (
  SUM(IF (action_type = 'upload', 1, 0)) 
) AS 'upload', (
  SUM(IF (action_type = 'comment', 1, 0)) 
) AS 'comment',(
  SUM(IF (action_type = 'share', 1, 0)) 
) AS 'share'
 
FROM ss_stats
GROUP BY user_id
HAVING user_id IS NOT NULL


-- Kajman
SELECT user_id,
       ( Sum(IF (action_type = 'login', pocet, 0)) )    AS 'login',
       ( Sum(IF (action_type = 'publish', pocet, 0)) )  AS 'publish',
       ( Sum(IF (action_type = 'download', pocet, 0)) ) AS 'download',
       ( Sum(IF (action_type = 'upload', pocet, 0)) )   AS 'upload',
       ( Sum(IF (action_type = 'comment', pocet, 0)) )  AS 'comment',
       ( Sum(IF (action_type = 'share', pocet, 0)) )    AS 'share'
FROM   (SELECT user_id,
               action_type,
               Count(*) pocet
        FROM   ss_stats
        GROUP  BY action_type,
                  user_id) pocty
WHERE  user_id IS NOT NULL
GROUP  BY user_id


--- tttt; nejlepsi a nejrychlejsi
SELECT
    user_id,
    logins.count AS 'login', 
    publishes.count AS 'publish', 
    downloads.count AS 'download', 
    uploads.count AS 'upload', 
    "comments".count AS 'comment', 
    shares.count AS 'shares'
FROM 
  users 
  LEFT JOIN (SELECT user_id, COUNT(*) FROM ss_stats WHERE action_type = 'login' GROUP BY user_id) logins USING(user_id)
  LEFT JOIN (SELECT user_id, COUNT(*) FROM ss_stats WHERE action_type = 'publish' GROUP BY user_id) publishes USING(user_id)
  LEFT JOIN (SELECT user_id, COUNT(*) FROM ss_stats WHERE action_type = 'download' GROUP BY user_id) downloads USING(user_id)
  LEFT JOIN (SELECT user_id, COUNT(*) FROM ss_stats WHERE action_type = 'upload' GROUP BY user_id) uploads USING(user_id)
  LEFT JOIN (SELECT user_id, COUNT(*) FROM ss_stats WHERE action_type = 'comment' GROUP BY user_id) "comments" USING(user_id)
  LEFT JOIN (SELECT user_id, COUNT(*) FROM ss_stats WHERE action_type = 'share' GROUP BY user_id) shares USING(user_id)

On gists

Automatické vytvoření komponenty s @autowiringem // AW

Nette-Controls Nette-Tricks AW

auto-create.php #

<?php

	public function createComponentOrderReview()
	{
		return $this->getPresenter()->getControlFactory()->create($this, 'orderReview', [
			'order' => $this->getOrder()
		]);
	}
	
	
	    // from same category
    public function createComponentSameCategoryProducts()
    {
        $config = $this->getCurrentConfig();
        $product = $this->getProduct();
        $component = parent::createComponent($config['category_list_component']);
        $component->setConfig([
            'except_ids' => [
                $product::INHERITED ? $product->product_id : $product->id,
                $product->item__product_id,
                $product->inherit__product_id
            ],
            'navigation_id' => $product->getMainCat()->id,
            'default_filter' => []
        ]);
        return $component;
    }

On gists

Struktura tabulky

AW

struct.php #

<?php
		$description = $this->connection->table('customer_address')->getStructure();
		$description->getCols();

On gists

TinyModal - usage

AW

tpl.latte #

{* POUZITI MODALU  2 zpusoby, inline nebo pres store mimo modal *}
        <div n:if="false" class="mx-auto max-w-lg mb-10 space-y-4">

            <h2 class="text-h3 text-msp-red">@DEV</h2>
            <h2 class="text-h4">Modaly .. nejsou videt, open buttony jsou vyple</h2>
            <tiny-modal store-id="modal1" max-width="1000px">
                <template #default="{ close }">
                    <div class="p-8">
                        CONTENT MODAL 1
                    </div>
                </template>
            </tiny-modal>
    

            <tiny-modal store-id="modal2" max-width="1000px">
                <template #default="{ close }">
                    <div class="p-8">
                        CONTENT MODAL 2
                    </div>
                </template>
            </tiny-modal>

            <tiny-modal max-width="1000px">
                <template #button="{ open }">
                    <button @click="open">Otevřít modál na přímo 3</button>
                </template>
                <template #default="{ close }">
                    <div class="p-8">
                        CONTENT MODAL 3
                    </div>
                </template>
            </tiny-modal>
            <hr />
            <h2 class="text-h4">Buttony mimo modaly</h2>


            <button @click="$store.dispatch('tinyModal/open', { id: 'modal1' })">modal 1 open</button> |
            <button @click="$store.dispatch('tinyModal/open', { id: 'modal2' })">modal 2 open</button>

        </div>

On gists

Money price object

AW

demo.php #

<?php

//App\PriceModule\Model\Currency $currency
// Money\Money $amount

// vytvoreni money objektu
	$amountFrom = $this->currency->convertPrice(
			$this->currency->parsePrice($activeRow->currency_id, $activeRow->amount_from)
		);

// vetsi nebo rovno
$amount->greaterThanOrEqual($amountFrom)

// odecteni
/** @var \Money\Money */
$priceAfterDiscount = $price->getPrice()->subtract($discount)->getAmount(); 

// nastaveni objektu ceny 
$price->setPrice($priceAfterDiscount)

// raw data jako string vcetne haliru napr 50000 // 500kc
/** @var \Money\Money */
$moneyObject->getAmount()

On gists

VUEX store in latte template

Vue.js AW

some.latte #

$store.state.modalForm.formId
$store.dispatch('modalForm/close')


  <a 
    @click="$store.dispatch('modalForm/open', { 
        formId: {$data->button__contact_form_section->contact_form_control_id}, 
        sectionId: {$data->button__contact_form_section_id} 
    })"
    class="Btn Btn--Primary cursor-pointer">
    {$data->button_text}
</a>