<?php

declare(strict_types=1);

/*
 * Copyright (c) 2017-2023 François Kooman <fkooman@tuxed.net>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

namespace fkooman\OAuth\Server;

use fkooman\OAuth\Server\Exception\InsufficientScopeException;
use fkooman\OAuth\Server\Exception\InvalidScopeException;

class Scope
{
    /** @var array<string> */
    private array $scopeTokenList = [];

    public function __construct(string $scope)
    {
        // if the provided parameter, i.e. `$scope` is the empty string, the
        // `explode` call will create an array with one element, the empty
        // string for some reason, so this *works*
        foreach (explode(' ', $scope) as $scopeToken) {
            // scope       = scope-token *( SP scope-token )
            // scope-token = 1*NQCHAR
            // NQCHAR      = %x21 / %x23-5B / %x5D-7E
            if (1 !== preg_match('/^[\x21\x23-\x5B\x5D-\x7E]+$/', $scopeToken)) {
                throw new InvalidScopeException('invalid "scope"');
            }

            $this->scopeTokenList[] = $scopeToken;
        }
    }

    public function __toString(): string
    {
        return implode(' ', $this->scopeTokenList);
    }

    /**
     * @return array<string>
     */
    public function scopeTokenList(): array
    {
        return $this->scopeTokenList;
    }

    /**
     * @param array<string> $scopeList
     *
     * @throws \fkooman\OAuth\Server\Exception\InsufficientScopeException
     */
    public function requireAll(array $scopeList): void
    {
        foreach ($scopeList as $scope) {
            if (!\in_array($scope, $this->scopeTokenList, true)) {
                throw new InsufficientScopeException(sprintf('scope "%s" not granted', $scope));
            }
        }
    }

    public function has(string $scope): bool
    {
        return in_array($scope, $this->scopeTokenList, true);
    }

    /**
     * @param array<string> $scopeList
     */
    public function hasAny(array $scopeList): bool
    {
        foreach ($scopeList as $scope) {
            if (\in_array($scope, $this->scopeTokenList, true)) {
                return true;
            }
        }

        return false;
    }

    /**
     * @param array<string> $scopeList
     *
     * @throws \fkooman\OAuth\Server\Exception\InsufficientScopeException
     */
    public function requireAny(array $scopeList): void
    {
        if (!$this->hasAny($scopeList)) {
            throw new InsufficientScopeException(sprintf('not any of scopes "%s" granted', implode(' ', $scopeList)));
        }
    }

    /**
     * Checks whether we contain *any* of the scopes in the provided scope.
     */
    public function containsAny(self $scope): bool
    {
        foreach ($scope->scopeTokenList() as $scopeToken) {
            if (in_array($scopeToken, $this->scopeTokenList, true)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Checks whether we contain *all* of the scopes in the provided scope.
     */
    public function containsAll(self $scope): bool
    {
        foreach ($scope->scopeTokenList() as $scopeToken) {
            if (!in_array($scopeToken, $this->scopeTokenList, true)) {
                return false;
            }
        }

        return true;
    }

    /**
     * Compare two scopes. We allow different order of scope tokens, e.g
     * 'foo bar' is equal to 'bar foo'. The compare is *case sensitive*.
     */
    public function isEqual(self $scope): bool
    {
        // this is not the nicest solution and probably ineffecient, but does
        // work. PHP doesn't offer a nice way for this, and this seems the
        // easiest to understand approach.
        $ourScope = $this->scopeTokenList();
        $theirScope = $scope->scopeTokenList();
        sort($ourScope);
        sort($theirScope);

        return $ourScope === $theirScope;
    }
}
