Dev BMW

Symfony S3 Service Encapsulation


composer require aws/aws-sdk-php
# .env file
S3_CREDENTIALS_KEY='your key'
S3_CREDENTIALS_SECRET='your secret'
S3_REGION='your region'
S3_VERSION='your version'
S3_ENDPOINT=''
S3_USE_PATH_STYLE_ENDPOINT=''

S3Config.php
<?php

namespace App\Service\S3;

use Symfony\Component\DependencyInjection\Attribute\Autowire;

readonly class S3Config
{
    public function __construct(
        #[Autowire(env: 'S3_CREDENTIALS_KEY')]
        public string $credentialKey,
        #[Autowire(env: 'S3_CREDENTIALS_SECRET')]
        public string $credentialSecret,
        #[Autowire(env: 'S3_REGION')]
        public string $region,
        #[Autowire(env: 'S3_VERSION')]
        public string $version,
        #[Autowire(env: 'S3_ENDPOINT')]
        public string $endpoint,
        #[Autowire(env: 'bool:S3_USE_PATH_STYLE_ENDPOINT')]
        public bool $usePathStyleEndpoint,
    )
    {
    }
}

S3Service.php
<?php

namespace App\Service\S3;

use Aws\Credentials\Credentials;
use Aws\S3\S3Client;

readonly class S3Service
{
    private S3Client $s3Client;

    public function __construct(
        private S3Config $config
    )
    {
        $parameters = [
            'credentials' => new Credentials($this->config->credentialKey, $this->config->credentialSecret),
            'region' => $this->config->region,
            'version' => $this->config->version,
            'use_path_style_endpoint' => $this->config->usePathStyleEndpoint,
        ];
        if (!empty($this->config->endpoint)) {
            $parameters['endpoint'] = $this->config->endpoint;
        }

        $this->s3Client = new S3Client($parameters);
    }

    public function listBuckets(): array
    {
        $buckets = $this->s3Client->listBuckets();
        return $buckets['Buckets'];
    }

    public function putObjectByBody(string $bucket, string $key, string $body): void
    {
        $this->s3Client->putObject([
            'Bucket' => $bucket,
            'Key' => $key,
            'Body' => $body
        ]);
    }

    public function getObject(string $bucket, string $key): ?string
    {
        $result = $this->s3Client->getObject([
            'Bucket' => $bucket,
            'Key' => $key
        ]);

        return $result['Body'] ?? null;
    }
}
1 месяц назад