CategoryQueryHandler.php 2.17 KB
<?php

namespace FootyRoom\Queries\Category;

use FootyRoom\Support\AutoMapper;
use Illuminate\Database\Connection;

class CategoryQueryHandler
{
    /**
     * @var \Illuminate\Database\Connection
     */
    protected $mysql;

    /**
     * Constructor.
     *
     * @param \Illuminate\Database\Connection $mysql
     */
    public function __construct(Connection $mysql)
    {
        $this->mysql = $mysql;
    }

    /**
     * Query handler.
     *
     * @param \FootyRoom\Queries\Category\OneCategoryQuery $query
     *
     * @return \FootyRoom\Queries\Category\Category|null
     */
    public function findOne(OneCategoryQuery $query)
    {
        $builder = $this->mysql

        ->table('wp_term_taxonomy AS taxonomy')
        ->select(
            'terms.name as name',
            'terms.term_id as id',
            'terms.slug as slug',
            'taxonomy.count'
        )
        ->leftJoin('wp_terms as terms', 'terms.term_id', '=', 'taxonomy.term_id')
        ->where('terms.term_group', ForumCategoriesQuery::FORUM_TERM_GROUP);

        if ($query->getCategorySlug()) {
            $builder->where('terms.slug', $query->getCategorySlug());
        }

        $categoryDto = $builder->first();

        if (!$categoryDto) {
            return null;
        }

        return AutoMapper::map($categoryDto, Category::class);
    }

    /**
     * Query handler.
     *
     * @param \FootyRoom\Queries\Category\ForumCategoriesQuery $query
     *
     * @return \FootyRoom\Queries\Category\Category[]
     */
    public function findForumCategories(ForumCategoriesQuery $query)
    {
        $categories = $this->mysql->select(
            'SELECT 
             terms.name as name,
             terms.term_id as id,
             terms.slug as slug,
             taxonomy.count
             FROM wp_term_taxonomy AS taxonomy
             LEFT JOIN wp_terms AS terms ON terms.term_id = taxonomy.term_id
             WHERE term_group = ?',
            [$query->getForumTermGroup()]
        );

        $categoryModels = [];

        foreach ($categories as $category) {
            $categoryModels[] = AutoMapper::map($category, Category::class);
        }

        return $categoryModels;
    }
}