<?php namespace App\Repositories;
/**
 * Copyright 2019 OpenStack Foundation
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/
use Models\OpenId\OpenIdTrustedSite;
use OpenId\Repositories\IOpenIdTrustedSiteRepository;
/**
 * Class DoctrineOpenIdTrustedSiteRepository
 * @package App\Repositories
 */
class DoctrineOpenIdTrustedSiteRepository
    extends ModelDoctrineRepository implements IOpenIdTrustedSiteRepository
{

    /**
     * @return string
     */
    protected function getBaseEntity()
    {
        return OpenIdTrustedSite::class;
    }


    /**
     * @param int $user_id
     * @param array $sub_domains
     * @param array $data
     * @return array
     */
    public function getMatchingOnesByUserId(int $user_id, array $sub_domains, array $data)
    {
        $query =  $this->getEntityManager()
            ->createQueryBuilder()
            ->select("e")
            ->from($this->getBaseEntity(), "e")
            ->join("e.owner", "owner")
            ->where("owner.id = (:user_id)")
            ->setParameter("user_id", $user_id);

        //add or condition for all given sub-domains
        if (count($sub_domains)) {

            $sub_query = '';
            foreach ($sub_domains as $sub_domain) {
                if(!empty($sub_query))
                    $sub_query .= ' or ';
                $sub_query .= " e.realm = '".$sub_domain."' ";
            }

            $query = $query->andWhere($sub_query);
        }

        //add conditions for all possible pre approved data
        foreach ($data as $value) {
            $query = $query->andWhere("e.data LIKE '%" . $value . "%'");
        }
        return $query->getQuery()
            ->getResult();
    }
}