Tutorials

Symfony: Automate Brand Asset Import for Professional Proposals with AI Extractor

Symfony: Automate Brand Asset Import for Professional Proposals with AI Extractor

A proposal can have sound pricing, a clear scope, and a strong argument, yet still look unfinished because someone copied the wrong logo into the template. Reports suffer the same problem: branding becomes a small manual task repeated indefinitely.

We will build a Symfony workflow that extracts a client’s visual identity, validates selected assets, stages a revision for review, and renders branded HTML proposals or reports. The important production boundary is approval: evidence-based extraction supplies candidates; your application decides what becomes customer-facing.

Get access and copy the service token

  1. Register or sign in.
  2. Open the Brand Kit Extractor service and plan page, choose an available Free, Plus, or Pro plan, and complete activation.
  3. Open the official documentation. Find the Service token panel and copy the service-scoped token.

This service requires authentication. Regenerating its token revokes the previous active token, so coordinate rotation with deployed applications. Supported authentication methods are Bearer authentication, the X-API-Token header, and a token query parameter. We use Bearer authentication to keep credentials out of URLs.

The exact operation is POST https://ai.mihajlo.mk/api/brand-kit-extractor/v1/extract-brand-kit. Its JSON request contains url. Start with this minimal connectivity check, replacing the placeholder locally:

curl --connect-timeout 5 --max-time 30 --fail-with-body \
  https://ai.mihajlo.mk/api/brand-kit-extractor/v1/extract-brand-kit \
  -H 'Authorization: Bearer YOUR_SERVICE_TOKEN' \
  -H 'Content-Type: application/json' \
  --data '{"url":"https://example.com"}'

A reachable endpoint does not guarantee that a particular website yields useful assets. Inspect the response against the documentation before configuring the mapping below. Never paste a real token into shared terminal transcripts.

Create the project and define its boundaries

Use PHP 8.3 or later, Composer, and Symfony 7.4. PHPUnit 11.5 supports this PHP baseline. Commit the dependency lock file.

composer create-project symfony/skeleton:"7.4.*" brand-proposals
cd brand-proposals
composer require symfony/http-client:"7.4.*" symfony/twig-bundle:"7.4.*" \
  symfony/monolog-bundle:"^3.10"
composer require --dev phpunit/phpunit:"^11.5"
install -d -m 700 var/brands
mkdir -p src/Brand src/Command templates tests

Store the credential in the project’s uncommitted .env.local. Production should inject the same variable through its secret manager.

BRAND_KIT_TOKEN=YOUR_SERVICE_TOKEN

The project has five application files: src/Brand/Client.php, src/Brand/Mapper.php, src/Command/BrandCommand.php, config/brand-map.json, and templates/document.html.twig. Imports run through a staff-only console command, keeping extraction outside document rendering. Messenger would add little value for this small, operator-driven workflow.

Approved manifests are local immutable revisions. Logo and imagery URLs remain references; this implementation does not download binaries or promise archival reproduction. Browsers retrieve approved images when displaying documents. It deliberately avoids introducing a server-side PDF renderer that could fetch arbitrary remote resources.

Configure the response boundary without guessing its schema

The supplied contract names the returned categories, but does not specify their JSON property paths or nested shapes. Consequently, hardcoding plausible provider fields would be misleading. Configure pointers from an actual documented response instead.

Create config/brand-map.json using this application-owned format. Replace every placeholder with a JSON pointer to a scalar value in the real response. Lists contain pointers to individual strings; CSS variable names are your approved local names.

{
  "name": "/REPLACE_WITH_BRAND_NAME_POINTER",
  "logos": ["/REPLACE_WITH_LOGO_URL_POINTER"],
  "colors": ["/REPLACE_WITH_HEX_COLOR_POINTER"],
  "fonts": ["/REPLACE_WITH_FONT_FAMILY_POINTER"],
  "imagery": [],
  "social": [],
  "css": {
    "--proposal-accent": "/REPLACE_WITH_CSS_COLOR_VALUE_POINTER"
  }
}

Add imagery and social-profile pointers when available. Select CSS values from the returned CSS variables. Empty optional collections mean “not imported,” not “absent from the website.” This adapter accepts six-digit hexadecimal colors and plain font-family names; unsupported formats fail until deliberately normalized. Unknown response data never enters storage.

Append these service definitions to config/services.yaml, preserving the skeleton’s existing defaults and application resource registration:

services:
    App\Brand\Client:
        arguments:
            $token: '%env(BRAND_KIT_TOKEN)%'

    App\Command\BrandCommand:
        arguments:
            $projectDir: '%kernel.project_dir%'

Bound the HTTP request and make failures actionable

The client uses HttpClientInterface through dependency injection. Its inactivity timeout bounds connection stalls and stalled reads; the total deadline bounds the complete operation. Streaming limits response size before JSON decoding.

<?php
// src/Brand/Client.php
namespace App\Brand;

use Psr\Log\LoggerInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;

final class Client
{
    public function __construct(
        private HttpClientInterface $http,
        private LoggerInterface $logger,
        private string $token,
    ) {}

    public function extract(string $url): array
    {
        Mapper::https($url);
        $response = null;

        try {
            $response = $this->http->request('POST',
                'https://ai.mihajlo.mk/api/brand-kit-extractor/v1/extract-brand-kit',
                [
                    'auth_bearer' => $this->token,
                    'json' => ['url' => $url],
                    'timeout' => 5,
                    'max_duration' => 30,
                    'max_redirects' => 0,
                    'buffer' => false,
                ]
            );

            $status = $response->getStatusCode();
            if ($status < 200 || $status >= 300) {
                $state = match (true) {
                    $status === 429 => 'quota',
                    in_array($status, [401, 403], true) => 'authentication',
                    $status >= 500 => 'provider',
                    default => 'request',
                };
                $retry = $response->getHeaders(false)['retry-after'][0] ?? null;
                $this->logger->warning('brand.extract.failed', [
                    'state' => $state,
                    'status' => $status,
                    'retry_after' => is_string($retry)
                        ? substr($retry, 0, 80) : null,
                ]);
                throw new \RuntimeException($state, $status);
            }

            $body = '';
            foreach ($this->http->stream($response) as $chunk) {
                $body .= $chunk->getContent();
                if (strlen($body) > 2_000_000) {
                    throw new \RuntimeException('response_size');
                }
            }

            $data = json_decode($body, true, 64, JSON_THROW_ON_ERROR);
            if (!is_array($data)) {
                throw new \RuntimeException('response_shape');
            }
            return $data;
        } catch (TransportExceptionInterface $e) {
            $this->logger->warning('brand.extract.failed', [
                'state' => 'transport',
            ]);
            throw new \RuntimeException('transport', 0, $e);
        } finally {
            $response?->cancel();
        }
    }
}

There are no automatic retries. The contract supplies no idempotency guarantee, so a lost response may still represent a completed, billable extraction. Fix authentication and request failures before rerunning. For quota failures, honor Retry-After when supplied and check plan availability. Retry transient failures deliberately with increasing delays; never wrap this command in an unlimited restart loop.

Validate the domain model before persistence

The mapper verifies every selected value. It rejects executable URL schemes, credentials in URLs, arbitrary CSS, and font names containing CSS syntax. HTTPS validation establishes syntax and transport policy; it does not prove asset ownership or public DNS resolution. Staff review must verify provenance.

<?php
// src/Brand/Mapper.php
namespace App\Brand;

final class Mapper
{
    public static function https(string $value): string
    {
        $parts = parse_url($value);
        if (strlen($value) > 2048
            || !filter_var($value, FILTER_VALIDATE_URL)
            || ($parts['scheme'] ?? '') !== 'https'
            || isset($parts['user']) || isset($parts['pass'])) {
            throw new \InvalidArgumentException('https_url');
        }
        return $value;
    }

    public function map(array $raw, array $spec): array
    {
        $pick = static function (string $pointer) use ($raw): string {
            if (!str_starts_with($pointer, '/')) {
                throw new \InvalidArgumentException('pointer');
            }
            $value = $raw;
            foreach (explode('/', substr($pointer, 1)) as $part) {
                $key = str_replace(['~1', '~0'], ['/', '~'], $part);
                if (!is_array($value) || !array_key_exists($key, $value)) {
                    throw new \InvalidArgumentException('missing_value');
                }
                $value = $value[$key];
            }
            if (!is_string($value) || $value === '') {
                throw new \InvalidArgumentException('scalar');
            }
            return $value;
        };

        $color = static function (string $value): string {
            if (!preg_match('/\A#[0-9a-fA-F]{6}\z/', $value)) {
                throw new \InvalidArgumentException('color');
            }
            return strtolower($value);
        };

        $brand = ['name' => $pick($spec['name'])];
        if (strlen($brand['name']) > 160
            || preg_match('/[\x00-\x1f\x7f]/', $brand['name'])) {
            throw new \InvalidArgumentException('name');
        }

        foreach (['logos', 'colors', 'fonts', 'imagery', 'social'] as $field) {
            $paths = $spec[$field];
            if (!is_array($paths) || !array_is_list($paths)
                || count($paths) > 32) {
                throw new \InvalidArgumentException('collection');
            }
            $brand[$field] = [];
            foreach ($paths as $path) {
                $value = $pick($path);
                if ($field === 'colors') {
                    $value = $color($value);
                } elseif ($field === 'fonts') {
                    if (!preg_match('/\A[A-Za-z0-9 _-]{1,80}\z/', $value)) {
                        throw new \InvalidArgumentException('font');
                    }
                } else {
                    $value = self::https($value);
                }
                $brand[$field][] = $value;
            }
        }

        foreach (['logos', 'colors', 'fonts'] as $required) {
            if (!$brand[$required]) {
                throw new \InvalidArgumentException('incomplete_brand');
            }
        }

        if (!is_array($spec['css']) || count($spec['css']) > 32) {
            throw new \InvalidArgumentException('css');
        }
        $brand['css'] = [];
        foreach ($spec['css'] as $name => $path) {
            if (!preg_match('/\A--[a-z][a-z0-9-]{0,62}\z/', $name)) {
                throw new \InvalidArgumentException('css_name');
            }
            $brand['css'][$name] = $color($pick($path));
        }
        return $brand;
    }
}

Stage, approve, and render explicit revisions

One command supports three operations. Import failures leave existing approvals untouched. Approval displays the complete manifest and requires an affirmative response. Rendering names a revision explicitly, preventing a later import from silently changing an issued proposal.

<?php
// src/Command/BrandCommand.php
namespace App\Command;

use App\Brand\{Client, Mapper};
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\{InputArgument, InputInterface};
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Twig\Environment;

#[AsCommand(name: 'app:brand')]
final class BrandCommand extends Command
{
    public function __construct(
        private Client $client,
        private Mapper $mapper,
        private Environment $twig,
        private LoggerInterface $logger,
        private string $projectDir,
    ) {
        parent::__construct();
    }

    protected function configure(): void
    {
        $this->addArgument('action', InputArgument::REQUIRED)
            ->addArgument('value', InputArgument::REQUIRED)
            ->addArgument('document', InputArgument::OPTIONAL);
    }

    private function read(string $path): array
    {
        $data = json_decode(file_get_contents($path), true, 64,
            JSON_THROW_ON_ERROR);
        if (!is_array($data)) {
            throw new \RuntimeException('document_shape');
        }
        return $data;
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $dir = $this->projectDir.'/var/brands';
        $action = $input->getArgument('action');
        $value = $input->getArgument('value');

        try {
            if ($action === 'import') {
                $brand = $this->mapper->map(
                    $this->client->extract($value),
                    $this->read($this->projectDir.'/config/brand-map.json')
                );
                $json = json_encode([
                    'source' => $value,
                    'extracted_at' => gmdate(DATE_ATOM),
                    'brand' => $brand,
                ], JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT);
                $value = hash('sha256', $json);
                $temporary = tempnam($dir, 'stage-');
                if ($temporary === false) {
                    throw new \RuntimeException('storage');
                }
                try {
                    if (file_put_contents($temporary, $json) !== strlen($json)
                        || !rename($temporary, "$dir/pending-$value.json")) {
                        throw new \RuntimeException('storage');
                    }
                } finally {
                    if (is_file($temporary)) {
                        unlink($temporary);
                    }
                }
                $output->writeln($value);
            } else {
                if (!preg_match('/\A[a-f0-9]{64}\z/', $value)) {
                    throw new \InvalidArgumentException('revision');
                }
                if ($action === 'approve') {
                    $pending = "$dir/pending-$value.json";
                    $snapshot = $this->read($pending);
                    $io = new SymfonyStyle($input, $output);
                    $io->text(json_encode($snapshot, JSON_PRETTY_PRINT));
                    if (!$io->confirm('Verified identity, rights and asset URLs?', false)) {
                        return Command::FAILURE;
                    }
                    if (!rename($pending, "$dir/approved-$value.json")) {
                        throw new \RuntimeException('storage');
                    }
                } elseif ($action === 'render') {
                    $snapshot = $this->read("$dir/approved-$value.json");
                    $document = $this->read($input->getArgument('document'));
                    foreach (['title', 'summary'] as $field) {
                        if (!is_string($document[$field] ?? null)
                            || strlen($document[$field]) > 20000) {
                            throw new \InvalidArgumentException('document');
                        }
                    }
                    $output->write($this->twig->render('document.html.twig', [
                        'brand' => $snapshot['brand'],
                        'document' => $document,
                    ]));
                } else {
                    throw new \InvalidArgumentException('action');
                }
            }
            $this->logger->info('brand.operation.completed', [
                'action' => $action, 'revision' => $value,
            ]);
            return Command::SUCCESS;
        } catch (\Throwable $e) {
            $this->logger->error('brand.operation.failed', [
                'action' => $action, 'error_class' => $e::class,
            ]);
            $output->getErrorOutput()->writeln('Brand operation failed.');
            return Command::FAILURE;
        }
    }
}

Use this escaped Twig template. Fonts are declared without remote font downloads; unavailable families fall back locally. Extracting a font name grants no license to distribute its font files.

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>{{ document.title }}</title>
<style>
:root {
{% for name, value in brand.css %}
  {{ name }}: {{ value }};
{% endfor %}
}
body { max-width: 50rem; margin: 3rem auto;
  font-family: "{{ brand.fonts[0] }}", sans-serif; }
h1 { color: {{ brand.colors[0] }}; }
img { max-width: 12rem; max-height: 8rem; }
</style>
<body>
<img src="{{ brand.logos[0] }}" alt="{{ brand.name }}" referrerpolicy="no-referrer">
<p>Prepared for {{ brand.name }}</p>
<h1>{{ document.title }}</h1>
<p>{{ document.summary }}</p>
{% for url in brand.imagery %}
<p><a href="{{ url }}" rel="noreferrer">Approved imagery reference</a></p>
{% endfor %}
{% for url in brand.social %}
<p><a href="{{ url }}" rel="noreferrer">Verified social profile</a></p>
{% endfor %}
</body>
</html>

Test failures before deploying

These deterministic tests exercise the real HTTP boundary without credentials. The response properties below are explicitly fictional test data, not a claimed provider schema.

<?php
// tests/BrandTest.php
namespace App\Tests;

use App\Brand\{Client, Mapper};
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\MockResponse;

final class BrandTest extends TestCase
{
    public function testRequestContract(): void
    {
        $http = new MockHttpClient(function ($method, $url, $options) {
            self::assertSame('POST', $method);
            self::assertSame(
                'https://ai.mihajlo.mk/api/brand-kit-extractor/v1/extract-brand-kit',
                $url
            );
            self::assertSame(['url' => 'https://example.com'],
                json_decode($options['body'], true));
            return new MockResponse('{"fixture":"ok"}');
        });
        self::assertSame(['fixture' => 'ok'],
            (new Client($http, new NullLogger(), 'TEST_TOKEN'))
                ->extract('https://example.com'));
    }

    public function testQuotaDoesNotRetry(): void
    {
        $http = new MockHttpClient([
            new MockResponse('', ['http_code' => 429]),
        ]);
        try {
            (new Client($http, new NullLogger(), 'TEST_TOKEN'))
                ->extract('https://example.com');
            self::fail('Expected rejection');
        } catch (\RuntimeException $e) {
            self::assertSame(429, $e->getCode());
        }
        self::assertSame(1, $http->getRequestsCount());
    }

    public function testUnsafeAssetIsRejected(): void
    {
        $this->expectException(\InvalidArgumentException::class);
        (new Mapper())->map(
            ['label' => 'Example', 'asset' => 'javascript:alert(1)'],
            ['name' => '/label', 'logos' => ['/asset']]
        );
    }
}

Before release, extend fixtures with your documented response, missing pointers, malformed colors, invalid JSON, and transport failures. A changed provider shape should stop imports visibly.

vendor/bin/phpunit --bootstrap vendor/autoload.php tests
php bin/console lint:yaml config
php bin/console lint:twig templates
php bin/console app:brand import https://example.com
php bin/console app:brand approve REVISION_HASH
php bin/console app:brand render REVISION_HASH proposal.json > proposal.html

Create proposal.json with string fields title and summary; a report uses the same rendering path. Replace REVISION_HASH with the import output.

Deploy and verify the actual document

Keep var/brands outside the public web root, writable only by the application account, backed up, and persistent across deployments. This filesystem design assumes one host and trusted staff access. Multiple writers need coordinated storage before scaling.

Logs record outcomes and revisions without response bodies or tokens. Watch quota, authentication, transport, and failed-import events. After token rotation, restart long-running application processes. Common failures are inactive plans, revoked credentials, unavailable source sites, and mapping drift; none should invalidate an approved revision.

  • Confirm activation and token injection in the deployed environment.
  • Import a real client site and inspect every selected asset and source.
  • Approve only assets whose identity and usage rights you verified.
  • Render both a proposal and report; inspect escaping, colors, logo loading, and font fallback.
  • Simulate a failed import and confirm the previous revision still renders.
  • Check browser print output and retain the revision identifier with issued documents.

The useful automation is not simply finding a logo. It is turning website evidence into a validated, reviewable branding decision that your document generator can reuse tomorrow.

Blog author portrait

Mihajlo

I’m Mihajlo — a developer driven by curiosity, discipline, and the constant urge to create something meaningful. I share insights, tutorials, and free services to help others simplify their work and grow in the ever-evolving world of software and AI.