MYMONDAY.ai
서비스스튜디오도구데이터·포맷73CSS 생성기19색상·이미지10인코딩·보안10웹·SEO11개발·데브옵스10파일·내보내기18계산기6가이드

YAML PHP 변환기

YAML 설정이나 데이터 파일을 YAML 1.2 로더가 돌려주는 값에 맞는 타입 속성을 가진 final PHP 클래스로 바꿉니다.

  • 브라우저에서 처리
  • 가입 없음
  • 무료

도구 작업 공간

예제

옵션

문서

---로 구분된 여러 문서가 있는 파일을 배열로 만들지(자동), 항상 배열로 만들지, 첫 문서만 쓸지 정합니다.

YAML 1.1 병합 키: <<: *base는 앵커의 키를 복사하며, 옆에 직접 쓴 키가 우선합니다. 끄면 <<를 일반 키로 둡니다.

YAML 입력

21줄314byte

결과

⌘/Ctrl + Enter로 복사
결과 · Payload.php
<?php

declare(strict_types=1);

final class Payload
{
    public function __construct(
        public int $id,
        public string $status,
        public PayloadCustomer $customer,
        /** @var list<PayloadItem> */
        public array $items,
        public float $total,
        public string $shippedAt,
        public mixed $tracking = null,
    ) {}

    /** @param array<string, mixed> $data */
    public static function fromArray(array $data): self
    {
        return new self(
            id: $data['id'],
            status: $data['status'],
            customer: PayloadCustomer::fromArray($data['customer']),
            items: array_map(static fn ($v) => PayloadItem::fromArray($v), $data['items']),
            total: $data['total'],
            shippedAt: $data['shipped_at'],
            tracking: $data['tracking'] ?? null,
        );
    }

    /** @return array<string, mixed> */
    public function toArray(): array
    {
        return [
            'id' => $this->id,
            'status' => $this->status,
            'customer' => $this->customer->toArray(),
            'items' => array_map(static fn ($v) => $v->toArray(), $this->items),
            'total' => $this->total,
            'shipped_at' => $this->shippedAt,
            'tracking' => $this->tracking,
        ];
    }
}

final class PayloadCustomer
{
    public function __construct(
        public int $id,
        public string $name,
        public string $email,
        public bool $vip,
    ) {}

    /** @param array<string, mixed> $data */
    public static function fromArray(array $data): self
    {
        return new self(
            id: $data['id'],
            name: $data['name'],
            email: $data['email'],
            vip: $data['vip'],
        );
    }

    /** @return array<string, mixed> */
    public function toArray(): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'vip' => $this->vip,
        ];
    }
}

final class PayloadItem
{
    public function __construct(
        public string $sku,
        public string $name,
        public int $qty,
        public float $price,
    ) {}

    /** @param array<string, mixed> $data */
    public static function fromArray(array $data): self
    {
        return new self(
            sku: $data['sku'],
            name: $data['name'],
            qty: $data['qty'],
            price: $data['price'],
        );
    }

    /** @return array<string, mixed> */
    public function toArray(): array
    {
        return [
            'sku' => $this->sku,
            'name' => $this->name,
            'qty' => $this->qty,
            'price' => $this->price,
        ];
    }
}
타입3
크기2.7kB

심포니 Yaml 컴포넌트나 yaml 확장으로 YAML 파일을 읽는 PHP 애플리케이션은 대개 중첩 배열을 돌려받는데, 타입이 있는 클래스가 훨씬 다루기 쉽습니다. 이 변환기는 자바스크립트 yaml 라이브러리(YAML 1.2 코어 스키마)로 YAML을 읽고 앵커와 병합 키를 펼친 뒤, 매핑마다 declare(strict_types=1), 생성자 승격 public 속성, 정적 fromArray, toArray 메서드를 갖춘 final class 하나를 씁니다.

먼저 같은 위치의 값을 하나로 합칩니다. 매핑 목록은 모든 항목의 속성을 합친 항목 클래스 하나가 되고, 일부 항목에 없는 키는 null 기본값이 있는 널 허용 속성이 되며, 배열 속성에는 @var list<PayloadItem> 같은 PHPDoc이 붙어 정적 분석이 원소 타입을 알 수 있습니다. 옵션으로 루트 클래스 이름(기본 Payload)과 선택적 namespace를 정합니다.

예제 세 가지(API 응답, 앵커와 병합 키, 엣지 케이스) 중 하나를 고르거나 내 YAML을 붙여 넣으면 입력하는 동안 PHP 코드가 갱신됩니다. 작업은 브라우저 탭 안에서만 이루어져 업로드가 없고, 입력은 20MiB까지입니다.

사용 방법

  1. YAML 붙여 넣기 또는 예제 고르기

    문서를 붙여 넣거나 .yaml 파일을 편집기에 끌어다 놓으며, 예제 칩으로 시작해도 됩니다. 매핑이나 목록은 루트가 될 수 있지만 스칼라 하나는 클래스로 만들 것이 없어 오류로 표시됩니다.

  2. 루트 클래스 이름과 네임스페이스 정하기

    루트 타입 이름은 PascalCase 클래스 이름이 되어 중첩 클래스의 접두어가 됩니다(PayloadLimits). 네임스페이스를 쓰면 declare(strict_types=1) 뒤에 namespace 줄이 들어가고, 내려받는 파일은 Payload.php처럼 루트 클래스 이름을 따릅니다.

  3. 문서와 병합 키 고르기

    문서가 여러 개인 파일은 자동 모드에서 목록이 되고, 항상 배열은 문서 하나도 배열로 감싸며, 첫 문서만은 첫 문서만 남깁니다. 병합 키(<<) 펼치기는 물려받은 키가 생성자 속성으로 나타날지 정합니다.

  4. 클래스 확인

    루트 클래스가 먼저 나오고 중첩 클래스가 만난 순서대로 이어집니다. ? 타입, mixed 속성, array 독블록이 파일에 대해 아는 내용과 맞는지 확인하세요.

  5. 복사 또는 저장

    코드를 복사하거나 .php 파일로 내려받습니다. 클래스가 한 파일에 연달아 선언되므로, 프로젝트가 파일당 클래스 하나(PSR-4)를 요구하면 나눠서 쓰세요.

작동 원리

YAML 값과 PHP 타입

타입은 파싱된 값에서 정해집니다. YAML 1.2에서는 true와 false만 불리언이라 debug: no는 string입니다. 날짜는 문자열이고, 정수는 int, 소수는 float입니다. 목록은 원소용 독블록이 붙은 array이고, 늘 null뿐이거나 서로 다른 타입이 섞인 위치는 mixed입니다.

널 허용 값에는 ? 접두어가 붙습니다. 널 허용이거나 일부 매핑에 없는 속성은 필수 속성 뒤에 놓이고 기본값이 null인데, PHP는 선택 매개변수 뒤에 필수 매개변수를 둘 수 없기 때문입니다.

YAMLPHP비고
name: apistring
port: 8080int32비트를 넘는 정수도 int
ratio: 0.5float
debug: nostring불리언은 YAML 1.1에서만
enabled: truebool
when: 2026-10-01string코어 스키마에는 타임스탬프 타입이 없음
empty: ~ (단독)mixed = null문자열과 함께 나오면 ?string
tags: [a, b]array와 @var list<string>
list: [1, two]array와 @var list<mixed>
limits: {cpu: 0.5}PayloadLimits경로에서 이름을 만듦
id: 9007199254740993string2^53을 넘으면 정확한 텍스트로 유지하고 알림 표시

fromArray, toArray, 엄격한 타입

fromArray는 각 키를 $data['max-conn']처럼 원래 표기로 읽어 타입이 있는 생성자에 넘깁니다. 값을 형변환하지 않으므로 declare(strict_types=1)에서 타입이 틀린 값은 TypeError를 냅니다. 의도된 동작입니다. 클래스는 보여 준 데이터를 설명하므로 운영에서 어긋나면 바로 드러납니다.

중첩 매핑은 중첩 클래스의 fromArray로, 매핑 목록은 array_map으로 채웁니다. 선택 키는 $data['key'] ?? null을 씁니다. toArray는 중첩 객체를 다시 배열로 바꿔 돌려주므로 yaml_emit이나 json_encode에 넘길 수 있습니다.

이름, 숫자 1.0, 문서

키는 camelCase 속성 이름이 되고 원래 키는 배열에 그대로 남습니다. list나 string 같은 PHP 예약어 이름의 클래스에는 Data가 붙고, this라는 속성은 thisValue가 되며, ASCII 글자가 없는 키는 field가 됩니다.

생성기는 평범한 숫자를 받으므로 ratio: 1.0 하나만 있으면 숫자 1이라 int 속성이 됩니다. 같은 위치 어딘가에 소수가 더해지면 float이 됩니다. 여러 문서는 목록이 되고, 파일에는 루트가 list<PayloadItem>이라는 주석 줄이 생깁니다.

실제 예시

네임스페이스가 있는 작은 설정
입력
name: api
ratio: 0.5
tags: [a, b]
출력
<?php

declare(strict_types=1);

namespace App\Dto;

final class Payload
{
    public function __construct(
        public string $name,
        public float $ratio,
        /** @var list<string> */
        public array $tags,
    ) {}

    /** @param array<string, mixed> $data */
    public static function fromArray(array $data): self
    {
        return new self(
            name: $data['name'],
            ratio: $data['ratio'],
            tags: $data['tags'],
        );
    }

    /** @return array<string, mixed> */
    public function toArray(): array
    {
        return [
            'name' => $this->name,
            'ratio' => $this->ratio,
            'tags' => $this->tags,
        ];
    }
}

네임스페이스를 App\Dto로 정한 경우입니다. 배열 속성은 독블록에 원소 타입을 남깁니다.

예약어, null, 1.0, 섞인 목록
입력
ratio: 1.0
class: x
list: [1, two]
empty: ~
출력
<?php

declare(strict_types=1);

final class Payload
{
    public function __construct(
        public int $ratio,
        public string $class,
        /** @var list<mixed> */
        public array $list,
        public mixed $empty = null,
    ) {}

    /** @param array<string, mixed> $data */
    public static function fromArray(array $data): self
    {
        return new self(
            ratio: $data['ratio'],
            class: $data['class'],
            list: $data['list'],
            empty: $data['empty'] ?? null,
        );
    }

    /** @return array<string, mixed> */
    public function toArray(): array
    {
        return [
            'ratio' => $this->ratio,
            'class' => $this->class,
            'list' => $this->list,
            'empty' => $this->empty,
        ];
    }
}

1.0 하나는 int이고, null은 기본값이 있는 mixed가 되어 생성자 맨 끝으로 가며, 섞인 목록은 mixed 배열입니다.

선택 키가 있는 매핑 목록
입력
items:
  - {k: a, n: 1}
  - {k: b}
출력
<?php

declare(strict_types=1);

final class Payload
{
    public function __construct(
        /** @var list<PayloadItem> */
        public array $items,
    ) {}

    /** @param array<string, mixed> $data */
    public static function fromArray(array $data): self
    {
        return new self(
            items: array_map(static fn ($v) => PayloadItem::fromArray($v), $data['items']),
        );
    }

    /** @return array<string, mixed> */
    public function toArray(): array
    {
        return [
            'items' => array_map(static fn ($v) => $v->toArray(), $this->items),
        ];
    }
}

final class PayloadItem
{
    public function __construct(
        public string $k,
        public ?int $n = null,
    ) {}

    /** @param array<string, mixed> $data */
    public static function fromArray(array $data): self
    {
        return new self(
            k: $data['k'],
            n: $data['n'] ?? null,
        );
    }

    /** @return array<string, mixed> */
    public function toArray(): array
    {
        return [
            'k' => $this->k,
            'n' => $this->n,
        ];
    }
}

두 항목이 PayloadItem 하나를 공유합니다. n은 한쪽에 없어서 null 기본값이 있는 ?int이고 null 병합 연산자로 읽습니다.

문서 두 개가 목록 루트가 됨
입력
id: 1
name: a
---
id: 2
출력
<?php

declare(strict_types=1);

// The root JSON value is list<PayloadItem>

final class PayloadItem
{
    public function __construct(
        public int $id,
        public ?string $name = null,
    ) {}

    /** @param array<string, mixed> $data */
    public static function fromArray(array $data): self
    {
        return new self(
            id: $data['id'],
            name: $data['name'] ?? null,
        );
    }

    /** @return array<string, mixed> */
    public function toArray(): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
        ];
    }
}

자동 모드는 문서 둘을 목록으로 만듭니다. 루트가 목록이라는 주석이 남고 항목 클래스만 생성됩니다.

2^53을 넘는 정수와 정수 값 실수
입력
id: 9007199254740993
ver: 1.0
출력
<?php

declare(strict_types=1);

final class Payload
{
    public function __construct(
        public string $id,
        public int $ver,
    ) {}

    /** @param array<string, mixed> $data */
    public static function fromArray(array $data): self
    {
        return new self(
            id: $data['id'],
            ver: $data['ver'],
        );
    }

    /** @return array<string, mixed> */
    public function toArray(): array
    {
        return [
            'id' => $this->id,
            'ver' => $this->ver,
        ];
    }
}

큰 id는 string이고 정확한 텍스트로 유지했다는 알림이 나옵니다. ver는 생성기가 숫자 1을 보므로 int입니다.

자주 하는 실수

  • fromArray는 형변환하지 않음

    strict_types에서는 int 자리에 문자열이 오면 TypeError가 납니다. YAML 로더가 int 필드에 "8080"이나 1.5를 돌려주면 YAML이나 타입을 고치세요.

  • 1.0 하나는 int 속성이 됨

    생성기가 보는 것은 숫자 1이라서 ver: 1.0은 int가 되고, 나중에 1.5가 오면 TypeError입니다. 샘플에 소수 값을 넣거나 타입을 직접 float로 고치세요.

  • 모두 한 파일에 들어 있음

    모든 클래스가 연달아 쓰입니다. PSR-4 오토로딩은 파일당 클래스 하나가 필요하므로 나누고, 각 파일 맨 위에 declare와 namespace 줄을 두세요.

  • 선택 여부는 여러 매핑을 보고 추정

    일부 매핑에 키가 없거나 null인 속성은 ?type $name = null이 되고, 생성자에서는 이런 매개변수가 필수 매개변수 뒤로 옮겨져 YAML과 순서가 달라질 수 있습니다. 샘플 레코드가 하나면 모든 키가 필수이므로 여러 개를 붙여 넣으세요.

  • 로더마다 YAML 1.1 단어 처리가 다름

    여기서 yes는 string입니다. 일부 PHP YAML 로더는 yes나 0123을 다르게 읽으므로, 쓰는 로더를 확인하거나 텍스트로 남아야 하는 값은 따옴표로 감싸세요.

  • 날짜는 문자열

    YAML 날짜는 string 속성입니다. 날짜 객체가 필요하면 코드에서 DateTimeImmutable로 감싸세요.

자주 묻는 질문

최상위가 목록인 YAML도 되나요?

네. 루트 목록은 항목 클래스와, 루트가 list<PayloadItem>이라는 주석 줄만 생성됩니다. 문서가 여러 개인 파일도 자동 모드에서는 이런 목록이 됩니다.

yes가 왜 string인가요?

YAML 1.2 코어 스키마가 불리언으로 인정하는 것은 true와 false뿐이어서 yes, no, on, off는 그냥 텍스트입니다. 그래서 bool이 아니라 string 타입 속성으로 생성됩니다.

null과 선택 키는 어떻게 처리되나요?

다른 값과 함께 나오는 null은 ? 타입이 됩니다. 일부 매핑에 없거나 null인 키는 null 기본값이 있는 속성이 되고 ?? null로 읽습니다. 늘 null뿐인 위치는 mixed입니다.

병합 키도 펼치나요?

기본값은 펼침이라 <<: *anchor로 물려받은 키가 일반 속성이 됩니다. 병합 키 펼치기를 끄면 <<에서 만든 속성이 대신 나옵니다.

PHP 8이 필요한가요?

네. 생성자 속성 승격, 이름 있는 인자, final class를 쓰므로 PHP 8.0 이상이 필요합니다. list<T> 타입은 독블록에만 있습니다.

클래스 이름을 바꾸고 네임스페이스를 붙일 수 있나요?

네, 루트 타입 이름과 네임스페이스에서 합니다. app config는 AppConfig가 되고 App\Dto 같은 네임스페이스가 declare(strict_types=1) 아래에 들어갑니다.

YAML이 업로드되나요?

아니요. 파싱과 코드 생성은 브라우저 탭 안에서 실행되며 서버로 전송되지 않습니다. 입력은 20MiB까지입니다.

마지막 업데이트: