Skip to content

인터페이스 레퍼런스

Contracts 모듈(TcpdfNext\Contracts)은 모든 TCPDF-Next 모듈이 프로그래밍하는 공유 인터페이스를 정의합니다. 구체 클래스 대신 계약에 의존함으로써 테스트 더블을 대체하고, 대안 구현을 만들고, 메이저 버전 간 안정적인 퍼블릭 API를 유지할 수 있습니다.


PdfDocumentInterface

네임스페이스: TcpdfNext\Contracts\PdfDocumentInterface

Document가 구현하는 기본 API 계약입니다. 이 인터페이스를 충족하는 모든 클래스는 내장 문서 모델의 드롭인 대체품으로 사용할 수 있습니다.

메서드

pageSize(PageSize $size): static
새 페이지의 기본 페이지 크기를 설정합니다.
orientation(Orientation $orientation): static
기본 페이지 방향을 설정합니다.
margin(Margin $margin): static
기본 페이지 여백을 설정합니다.
metadata(?string $title = null, ?string $author = null, ?string $subject = null, ?string $keywords = null, ?string $creator = null): static
문서 수준 메타데이터를 설정합니다. 모든 파라미터는 선택사항이며, 설정하려는 것만 전달합니다.
addPage(?PageSize $pageSize = null, ?Orientation $orientation = null): static
새 페이지를 추가하며, 이 페이지의 기본값을 선택적으로 재정의합니다.
font(string $family, float $size = 12.0, string $style = ''): static
패밀리 이름, 크기, 스타일로 폰트를 선택합니다.
text(string $content): static
현재 커서 위치에 한 줄의 텍스트를 작성합니다.
output(OutputDestination $destination = OutputDestination::String, ?string $filename = null, ?string $path = null): string|bool
선택한 대상으로 PDF를 렌더링합니다.
currentPage(): int
현재 페이지 번호(1-기반)를 반환합니다.
pageCount(): int
총 페이지 수를 반환합니다.

예제

php
use TcpdfNext\Contracts\PdfDocumentInterface;
use TcpdfNext\Contracts\OutputDestination;

function generateReport(PdfDocumentInterface $pdf): string
{
    return $pdf
        ->addPage()
        ->font('Helvetica', size: 14)
        ->text('Quarterly Report')
        ->output(OutputDestination::String);
}

FontManagerInterface

네임스페이스: TcpdfNext\Contracts\FontManagerInterface

폰트 로딩, 등록, 서브셋팅, 메트릭 조회를 정의합니다. 내장 FontManager가 이 인터페이스를 구현하지만, 특수한 폰트 소스를 위한 커스텀 구현을 제공할 수 있습니다.

메서드

registerFont(string $path, string $alias = ''): static
TrueType 또는 OpenType 폰트 파일을 등록합니다. alias가 비어있으면 파일의 폰트 패밀리 이름이 사용됩니다.
hasFont(string $family, string $style = ''): bool
폰트 패밀리 및 스타일 조합이 사용 가능한지 확인합니다.
getFont(string $family, string $style = ''): FontInfo
지정된 폰트의 메트릭을 가진 읽기 전용 FontInfo 객체를 반환합니다.
stringWidth(string $text, string $family, float $size, string $style = ''): float
사용자 단위로 문자열의 너비를 계산합니다.
subset(string $family, string $style, string $chars): string
지정된 문자에 필요한 글리프만 포함하는 서브셋 폰트 바이너리를 생성합니다.
registeredFamilies(): array
등록된 모든 폰트 패밀리 이름 목록을 반환합니다.

예제

php
use TcpdfNext\Contracts\FontManagerInterface;

function addCustomFonts(FontManagerInterface $fonts): void
{
    $fonts->registerFont('/fonts/NotoSans-Regular.ttf', 'NotoSans');
    $fonts->registerFont('/fonts/NotoSans-Bold.ttf', 'NotoSans');

    if ($fonts->hasFont('NotoSans', 'B')) {
        $info = $fonts->getFont('NotoSans', 'B');
        echo "Ascender: {$info->ascender}";
    }
}

SignerInterface

네임스페이스: TcpdfNext\Contracts\SignerInterface

모든 디지털 서명 제공자를 위한 계약을 정의합니다. 소프트웨어 인증서, 클라우드 기반 키 볼트, 하드웨어 보안 모듈(HSM)과 통합하려면 이 인터페이스를 구현합니다.

메서드

sign(string $data): string
주어진 데이터에 서명하고 원시 CMS/CAdES 서명 바이트를 반환합니다.
certificate(): string
DER 인코딩된 서명 인증서를 반환합니다.
chain(): array
DER 인코딩된 중간 인증서 배열을 반환합니다 (서명자에서 루트까지).
estimatedSize(): int
서명의 추정 최대 크기(바이트)를 반환합니다. ByteRange 플레이스홀더를 사전 할당하는 데 사용됩니다.
algorithm(): string
서명 알고리즘 OID 또는 이름(예: 'sha256WithRSAEncryption')을 반환합니다.

예제

php
use TcpdfNext\Contracts\SignerInterface;

class FileSigner implements SignerInterface
{
    public function __construct(
        private readonly string $certPath,
        private readonly string $keyPath,
        private readonly string $password,
    ) {}

    public function sign(string $data): string
    {
        $cert = file_get_contents($this->certPath);
        $key = openssl_pkey_get_private(
            file_get_contents($this->keyPath),
            $this->password,
        );
        openssl_pkcs7_sign(/* ... */);
        // 원시 서명 바이트 반환
    }

    public function certificate(): string { /* ... */ }
    public function chain(): array { return []; }
    public function estimatedSize(): int { return 8192; }
    public function algorithm(): string { return 'sha256WithRSAEncryption'; }
}

HsmSignerInterface

네임스페이스: TcpdfNext\Contracts\HsmSignerInterface

개인 키를 절대 노출하지 않는 하드웨어 보안 모듈을 위해 SignerInterface를 확장합니다. 원시 데이터에 서명하는 대신 HSM이 사전 계산된 다이제스트에 서명합니다.

메서드

SignerInterface의 모든 메서드, 추가:

signDigest(string $digest, string $algorithm): string
사전 계산된 메시지 다이제스트에 서명합니다. algorithm 파라미터는 사용된 해시를 식별합니다(예: 'sha256').

예제

php
use TcpdfNext\Contracts\HsmSignerInterface;

class AwsCloudHsmSigner implements HsmSignerInterface
{
    public function __construct(
        private readonly string $keyId,
        private readonly AwsKmsClient $kms,
        private readonly string $certPem,
    ) {}

    public function sign(string $data): string
    {
        $digest = hash('sha256', $data, binary: true);
        return $this->signDigest($digest, 'sha256');
    }

    public function signDigest(string $digest, string $algorithm): string
    {
        $result = $this->kms->sign([
            'KeyId' => $this->keyId,
            'Message' => $digest,
            'MessageType' => 'DIGEST',
            'SigningAlgorithm' => 'RSASSA_PKCS1_V1_5_SHA_256',
        ]);
        return $result['Signature'];
    }

    public function certificate(): string { return $this->certPem; }
    public function chain(): array { return []; }
    public function estimatedSize(): int { return 16384; }
    public function algorithm(): string { return 'sha256WithRSAEncryption'; }
}

테스트를 위한 인터페이스 활용

네 가지 인터페이스 모두 PHPUnit이나 Mockery로 쉽게 모킹할 수 있도록 설계되었습니다.

php
use PHPUnit\Framework\TestCase;
use TcpdfNext\Contracts\FontManagerInterface;

class TextRendererTest extends TestCase
{
    public function testCalculatesWidth(): void
    {
        $fonts = $this->createMock(FontManagerInterface::class);
        $fonts->method('hasFont')->willReturn(true);
        $fonts->method('stringWidth')
            ->with('Hello', 'Helvetica', 12.0, '')
            ->willReturn(26.64);

        $renderer = new TextRenderer($fonts);
        $this->assertEqualsWithDelta(26.64, $renderer->width('Hello'), 0.01);
    }
}

참고

LGPL-3.0-or-later 라이선스로 배포됩니다.