<?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\Tests;

use fkooman\OAuth\Server\PublicKeySourceInterface;

class TestPublicKeySource implements PublicKeySourceInterface
{
    /**
     * Get Public Key based on Key ID.
     *
     * @return ?string the Public Key, or null if Public Key is not available
     */
    public function fromKeyId(string $keyId): ?string
    {
        // $ php example/generate_key.php
        // Secret Key: k7.sec.tvIJooa5JCo5iR1B.ywNgWJEgzTXe1MNvBRMjLHHQyhBb-8Sl6UfG4pybwAZYIhiqYFZ_GEkQEJrTEQ4iYeiZu_Hce-RhcbMgI-xh9w
        // Public Key: k7.pub.tvIJooa5JCo5iR1B.WCIYqmBWfxhJEBCa0xEOImHombvx3HvkYXGzICPsYfc
        // $ php example/generate_key.php
        // Secret Key: k7.sec.pOzUzYV1_lW1pkTN.IJwY9O6fxs80Fz236EZjU00XR7O-KOt9YehHh-Klin-aGe1RyITjbK8mmfWQ7HUU5DiSUV7CdZu-_1BLTE4G_Q
        // Public Key: k7.pub.pOzUzYV1_lW1pkTN.mhntUciE42yvJpn1kOx1FOQ4klFewnWbvv9QS0xOBv0
        // $ php example/generate_key.php
        // Secret Key: k7.sec.cHaAvfdOUcY_kSE4.W0p9QB5m6b6cHtB7xej8bneNqrjJ5nKjL-A5zTp3oKnmCJpGV7g_gDNNwdmwzJ4o8D2RaGf72ArKgRkUHG8KSw
        // Public Key: k7.pub.cHaAvfdOUcY_kSE4.5giaRle4P4AzTcHZsMyeKPA9kWhn-9gKyoEZFBxvCks

        $publicKeyList = [
            'k7.pub.tvIJooa5JCo5iR1B.WCIYqmBWfxhJEBCa0xEOImHombvx3HvkYXGzICPsYfc',
            'k7.pub.pOzUzYV1_lW1pkTN.mhntUciE42yvJpn1kOx1FOQ4klFewnWbvv9QS0xOBv0',
            'k7.pub.cHaAvfdOUcY_kSE4.5giaRle4P4AzTcHZsMyeKPA9kWhn-9gKyoEZFBxvCks',
        ];

        foreach ($publicKeyList as $pubKey) {
            [,,$xKeyId] = explode('.', $pubKey, 4);
            if ($keyId === $xKeyId) {
                return $pubKey;
            }
        }

        return null;
    }
}
