PHP code example of moselwal / secret-resolver

1. Go to this page and download the library: Download moselwal/secret-resolver library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

moselwal / secret-resolver example snippets




declare(strict_types=1);

namespace MyVendor\MyExtension\Infrastructure\Provider;

use Moselwal\SecretResolver\Domain\Contract\SecretProviderInterface;
use Moselwal\SecretResolver\Domain\ValueObject\SecretKey;

final readonly class VaultSecretProvider implements SecretProviderInterface
{
    public function __construct(
        private VaultClient $client,
    ) {}

    public function getName(): string
    {
        // Return a unique provider name for extended key format targeting.
        // Users can then write %secret(vault:kv-v2/db.password)%
        // Return '' to participate only in the cascade (simple keys).
        return 'vault';
    }

    public function supports(SecretKey $key): bool
    {
        // For extended keys targeting this provider, check if the secret exists.
        // For cascade (simple keys), decide if this provider should attempt resolution.
        if ($key->isExtended()) {
            $path = $key->getSecretPath() ?? $key->getKeyName();
            return $this->client->secretExists($path);
        }

        // In cascade mode, optionally check by key name
        return $this->client->secretExists($key->lowerCase);
    }

    public function resolve(SecretKey $key): ?string
    {
        $path = $key->isExtended()
            ? ($key->getSecretPath() ?? $key->getKeyName())
            : $key->lowerCase;

        try {
            $value = $this->client->readSecret($path);
        } catch (\Throwable) {
            return null; // Fallback to next provider in cascade
        }

        return $value !== '' ? $value : null;
    }

    public static function priority(): int
    {
        // Higher priority = checked first.
        // Built-in: FileEnv=30, RunSecrets=20
        return 40; // Vault is checked before file-based providers
    }
}