<?php

namespace Concrete\Core\Entity\OAuth;

use Concrete\Core\Entity\Express\EntityRepository;
use League\OAuth2\Server\Entities\ClientEntityInterface;
use League\OAuth2\Server\Exception\OAuthServerException;
use League\OAuth2\Server\Repositories\ClientRepositoryInterface;

class ClientRepository extends EntityRepository implements ClientRepositoryInterface
{

    /**
     * Get a client.
     *
     * @param string $clientIdentifier The client's identifier
     * @param string $grantType The grant type used
     * @param null|string $clientSecret The client's secret (if sent)
     * @param bool $mustValidateSecret If true the client must attempt to validate the secret if the client
     *                                        is confidential
     *
     * @return ClientEntityInterface
     */
    public function getClientEntity($clientIdentifier, $grantType, $clientSecret = null, $mustValidateSecret = true)
    {
        $client = $this->findOneBy(['clientKey' => $clientIdentifier]);

        // Handle client not found
        if (!$client) {
            throw OAuthServerException::invalidClient();
        }

        // Handle validation
        if ($mustValidateSecret && !password_verify($clientSecret, $client->getClientSecret())) {
            throw OAuthServerException::invalidClient();
        }

        return $client;
    }

    /**
     * @inheritdoc
     * @return \Concrete\Core\Entity\OAuth\Client
     */
    public function find($id, $lockMode = null, $lockVersion = null)
    {
        return parent::find($id, $lockMode, $lockVersion); // TODO: Change the autogenerated stub
    }

}
