PHP code example of nordwerk / contao-teasers-bundle

1. Go to this page and download the library: Download nordwerk/contao-teasers-bundle library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

nordwerk / contao-teasers-bundle example snippets




declare(strict_types=1);

namespace App\Teaser;

use Doctrine\DBAL\ArrayParameterType;
use Doctrine\DBAL\Connection;
use Nordwerk\TeasersBundle\Card\Card;
use Nordwerk\TeasersBundle\Query\TeaserQuery;
use Nordwerk\TeasersBundle\Source\TeaserSourceInterface;
use Symfony\Bundle\SecurityBundle\Security;

final class NewProductsSource implements TeaserSourceInterface
{
    public function __construct(
        private readonly Connection $connection,
        private readonly Security $security,
    ) {
    }

    public function getKey(): string
    {
        return 'new_products';
    }

    public function getLabel(): string
    {
        return 'shop.new_products';
    }

    public function getArchives(): array
    {
        $choices = [];
        foreach ($this->connection->fetchAllKeyValue('SELECT id, title FROM tl_shop_category ORDER BY title') as $id => $title) {
            if ($this->security->isGranted('shop.category.edit', (int) $id)) {
                $choices[(int) $id] = (string) $title;
            }
        }

        return $choices;
    }

    public function fetch(TeaserQuery $query): iterable
    {
        $categories = array_values(array_filter($query->archives, fn (int $id): bool => $this->security->isGranted('shop.category.view', $id)));
        if (!$categories) {
            return;
        }

        $order = match ($query->sort) {
            'date_asc' => 'created_at ASC',
            'title_asc' => 'title ASC',
            default => 'created_at DESC',
        };
        $rows = $this->connection->fetchAllAssociative(
            'SELECT * FROM tl_shop_product WHERE category_id IN (?) AND published=1 AND available=1 AND created_at<=? ORDER BY '.$order.', id DESC LIMIT '.$query->limit,
            [$categories, time()],
            [ArrayParameterType::INTEGER],
        );
        $plain = static fn (string $value): string => html_entity_decode(strip_tags($value), ENT_QUOTES | ENT_HTML5);

        foreach ($rows as $row) {
            yield new Card(
                title: $plain((string) $row['title']),
                text: $plain((string) $row['description']),
                image: $row['image_uuid'] ? (string) $row['image_uuid'] : null,
                link: (string) $row['reader_url'],
                date: (new \DateTimeImmutable())->setTimestamp((int) $row['created_at']),
                price: number_format((int) $row['price_cents'] / 100, 2, ',', '.').' €',
            );
        }
    }
}