UrlGeneratorQuery.php 2.45 KB
<?php

namespace FootyRoom\Queries;

use FootyRoom\Support\MongoClient;
use Illuminate\Database\DatabaseManager;

class UrlGeneratorQuery
{
    /**
     * @var \Illuminate\Database\DatabaseManager
     */
    protected $mysql;

    /**
     * @var \FootyRoom\Support\MongoClient
     */
    protected $mongo;

    /**
     * Constructor.
     *
     * @param \Illuminate\Database\DatabaseManager $mysql
     * @param \FootyRoom\Support\MongoClient $mongo
     */
    public function __construct(DatabaseManager $mysql, MongoClient $mongo)
    {
        $this->mysql = $mysql;
        $this->mongo = $mongo;
    }

    /**
     * Finds needed data to build url to a post.
     *
     * Currently this works for many types of "posts" - le mix posts, pages like transfers-center and previews.
     *
     * @param int $id
     *
     * @return object|null Returned object contains id, slug, type, previewMatchId and category.
     */
    public function findPost($id)
    {
        $post = $this->mysql

        ->select(
            '
            SELECT
            ID as id,
            post_name as slug,
            post_type as type,
            preview.meta_value as previewMatchId,
            t.slug as category
            FROM wp_posts
            LEFT JOIN wp_postmeta AS preview ON preview.post_id = ID AND preview.meta_key = "match_id_preview"
            LEFT JOIN wp_term_relationships AS tr ON tr.object_id = ID
            LEFT JOIN wp_terms AS t ON t.term_id = tr.term_taxonomy_id
            WHERE ID = ?',
            [$id]
        );

        if (!isset($post[0])) {
            return null;
        }

        return $post[0];
    }

    /**
     * Finds needed data to build url to a match.
     *
     * @param int $id
     *
     * @return object|null Returns homeTeam, awayTeam and matchId from mongo matches collection.
     */
    public function findMatch($id)
    {
        $matchDto = $this->mongo->footyroom->matches->findOne(
            ['matchId' => $id],
            ['projection' => ['homeTeam' => 1, 'awayTeam' => 1, 'matchId' => 1]]
        );

        if (!$matchDto) {
            return null;
        }

        return $matchDto;
    }

    /**
     * Finds needed data to build url to a user profile.
     *
     * @param int $id
     *
     * @return object Returns object with username property.
     */
    public function findUser($id)
    {
        return $this->mongo->footyroom->users->findOne(['userId' => $id], ['projection' => ['username' => 1]]);
    }
}