Skip to content

Docker Compose Validator — PHP source

Validate a compose file in the browser: image or build per service, port syntax and ranges, environment shape, volumes, and the depends_on graph with cycle detection. Runs locally with a shareable link.

This is the PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.

<?php
// compose-validator — structural checks for a Docker Compose file. PHP port
// (canonical TS: src/lib/compose-validator.ts; Go twin: cli/compose-validator).
// Checks: root/services mappings, per-service image or build, port syntax
// ("8080", "80:8080", "127.0.0.1:80:8080", "6053:53/udp"), environment shape
// (mapping or KEY=value list), volumes lists, depends_on references and
// acyclicity — same rules, paths and message texts as the TS contract. PHP has
// no YAML parser in stdlib, so, like every port in this set, a minimal
// hand-rolled parser covers the compose subset: block mappings/sequences,
// single-line flow collections, quoted and plain scalars, comments.
// Anchors/aliases/merge keys, block scalars (| >), multi-line plain scalars
// and multi-document streams are outside the subset. PHP arrays cannot tell an
// empty mapping from an empty list, so an empty {} parses as a list. Never
// throws — parse errors travel in ["error"].

function compose_plain(string $t)
{
    if ($t === '' || $t === '~' || $t === 'null' || $t === 'Null' || $t === 'NULL') return null;
    if ($t === 'true' || $t === 'True' || $t === 'TRUE') return true;
    if ($t === 'false' || $t === 'False' || $t === 'FALSE') return false;
    if (preg_match('/^[-+]?[0-9]+$/', $t)) return intval($t);
    if (preg_match('/^[-+]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][-+]?[0-9]+)?$/', $t)) return floatval($t);
    return $t;
}

// Quoted scalar at $s[$i]; returns [value, next index]. "..." honors
// escapes, '...' doubles the quote.
function compose_quoted(string $s, int $i): array
{
    $q = $s[$i];
    $i += 1;
    $out = '';
    while ($i < strlen($s)) {
        $ch = $s[$i];
        if ($q === '"' && $ch === '\\') {
            $nxt = $i + 1 < strlen($s) ? $s[$i + 1] : '';
            $out .= match ($nxt) { 'n' => "\n", 't' => "\t", 'r' => "\r", default => $nxt };
            $i += 2;
        } elseif ($ch === $q) {
            if ($q === "'" && ($s[$i + 1] ?? '') === "'") { $out .= "'"; $i += 2; }
            else return [$out, $i + 1];
        } else {
            $out .= $ch;
            $i += 1;
        }
    }
    throw new RuntimeException('Invalid YAML: unterminated quoted scalar');
}

// One flow node at $s[$i]; returns [value, next index].
function compose_flow(string $s, int $i): array
{
    while (($s[$i] ?? '') === ' ') $i += 1;
    if (($s[$i] ?? '') === '[') {
        $out = [];
        $i += 1;
        for (;;) {
            while (($s[$i] ?? '') === ' ') $i += 1;
            if ($i >= strlen($s)) throw new RuntimeException('Invalid YAML: unterminated flow sequence');
            if ($s[$i] === ']') return [$out, $i + 1];
            [$v, $i] = compose_flow($s, $i);
            $out[] = $v;
            while (($s[$i] ?? '') === ' ' || ($s[$i] ?? '') === ',') $i += 1;
        }
    }
    if (($s[$i] ?? '') === '{') {
        $out = [];
        $i += 1;
        for (;;) {
            while (($s[$i] ?? '') === ' ') $i += 1;
            if ($i >= strlen($s)) throw new RuntimeException('Invalid YAML: unterminated flow mapping');
            if ($s[$i] === '}') return [$out, $i + 1];
            if ($s[$i] === '"' || $s[$i] === "'") {
                [$k, $i] = compose_quoted($s, $i);
            } else {
                $j = $i;
                while ($j < strlen($s) && $s[$j] !== ':' && $s[$j] !== ',' && $s[$j] !== '}') $j += 1;
                if (($s[$j] ?? '') !== ':') throw new RuntimeException('Invalid YAML: flow mapping entry without a colon');
                $k = trim(substr($s, $i, $j - $i));
                $i = $j + 1;
            }
            while (($s[$i] ?? '') === ' ') $i += 1;
            $v = null;
            if ($i < strlen($s) && $s[$i] !== ',' && $s[$i] !== '}') [$v, $i] = compose_flow($s, $i);
            $out[$k] = $v;
            while (($s[$i] ?? '') === ' ' || ($s[$i] ?? '') === ',') $i += 1;
        }
    }
    if (($s[$i] ?? '') === '"' || ($s[$i] ?? '') === "'") return compose_quoted($s, $i);
    $j = $i;
    while ($j < strlen($s) && $s[$j] !== ',' && $s[$j] !== ']' && $s[$j] !== '}') $j += 1;
    return [compose_plain(trim(substr($s, $i, $j - $i))), $j];
}

// `key: rest` split; null when the line is not a mapping entry. The first
// colon followed by a space (or ending the line) wins; quoted keys first.
function compose_key_split(string $s): ?array
{
    if ($s !== '' && ($s[0] === '"' || $s[0] === "'")) {
        try {
            [$key, $j] = compose_quoted($s, 0);
        } catch (RuntimeException $e) {
            return null;
        }
        $rest = ltrim(substr($s, $j), ' ');
        return $rest !== '' && $rest[0] === ':' ? [$key, substr($rest, 1)] : null;
    }
    for ($j = 0, $n = strlen($s); $j < $n; $j++) {
        if ($s[$j] === ':' && ($j + 1 === $n || $s[$j + 1] === ' ')) {
            return [rtrim(substr($s, 0, $j)), substr($s, $j + 1)];
        }
    }
    return null;
}

function compose_content_lines(string $text): array
{
    $out = [];
    foreach (explode("\n", $text) as $raw) {
        $crlf = substr($raw, -1) === "\r" ? substr($raw, 0, -1) : $raw;
        $indented = ltrim($crlf, ' ');
        $indent = strlen($crlf) - strlen($indented);
        $body = rtrim($indented);
        if ($body === '' || $body[0] === '#' || $body[0] === '%' || $body === '---') continue;
        if (str_contains(substr($crlf, 0, $indent), "\t")) throw new RuntimeException('Invalid YAML: tab in indentation');
        $out[] = [$indent, $body];
    }
    return $out;
}

function compose_is_item(string $s): bool
{
    return $s === '-' || str_starts_with($s, '- ');
}

// The node whose first line is $ls[$i] at the given indent; [value, next].
function compose_block_at(array $ls, int $i, int $indent): array
{
    if (compose_is_item($ls[$i][1])) {
        $out = [];
        while ($i < count($ls) && $ls[$i][0] === $indent && compose_is_item($ls[$i][1])) {
            $content = substr($ls[$i][1], 2);
            if (trim($content) === '' || str_starts_with(ltrim($content), '#')) {
                $i += 1;
                if ($i < count($ls) && $ls[$i][0] > $indent) [$v, $i] = compose_block_at($ls, $i, $ls[$i][0]);
                else $v = null;
            } else {
                $ls[$i] = [$indent + 2, $content];
                [$v, $i] = compose_block_at($ls, $i, $indent + 2);
            }
            $out[] = $v;
        }
        return [$out, $i];
    }
    if (compose_key_split($ls[$i][1]) === null) return [compose_inline_value($ls[$i][1]), $i + 1];
    $out = [];
    while ($i < count($ls) && $ls[$i][0] === $indent && !compose_is_item($ls[$i][1])
           && ($kv = compose_key_split($ls[$i][1])) !== null) {
        [$key, $rest0] = $kv;
        $rest = trim($rest0);
        $i += 1;
        if ($rest !== '') $out[$key] = compose_inline_value($rest);
        elseif ($i < count($ls) && $ls[$i][0] > $indent) { [$v, $i] = compose_block_at($ls, $i, $ls[$i][0]); $out[$key] = $v; }
        elseif ($i < count($ls) && $ls[$i][0] === $indent && compose_is_item($ls[$i][1])) { [$v, $i] = compose_block_at($ls, $i, $indent); $out[$key] = $v; }
        else $out[$key] = null;
    }
    return [$out, $i];
}

// The value part of `key: value` — flow, quoted, or plain (comment cut).
function compose_inline_value(string $rest)
{
    $c0 = $rest[0] ?? '';
    if ($c0 === '[' || $c0 === '{') {
        [$v, $j] = compose_flow($rest, 0);
        if (str_replace([' ', '#'], '', substr($rest, $j)) !== '') {
            throw new RuntimeException('Invalid YAML: trailing content after flow value');
        }
        return $v;
    }
    if ($c0 === '"' || $c0 === "'") {
        [$v, $j] = compose_quoted($rest, 0);
        if (str_replace([' ', '#'], '', substr($rest, $j)) !== '') {
            throw new RuntimeException('Invalid YAML: trailing content after quoted value');
        }
        return $v;
    }
    $cut = strpos($rest, ' #');
    return compose_plain(trim($cut === false ? $rest : substr($rest, 0, $cut)));
}

// The minimal parser: text → tree (assoc arrays keep document order).
function compose_parse_yaml(string $text)
{
    $ls = compose_content_lines($text);
    if ($ls === []) return null;
    [$v, $i] = compose_block_at($ls, 0, $ls[0][0]);
    if ($i !== count($ls)) throw new RuntimeException('Invalid YAML: inconsistent indentation');
    return $v;
}

function compose_is_map($v): bool
{
    return is_array($v) && !array_is_list($v);
}

function compose_is_seq($v): bool
{
    return is_array($v) && array_is_list($v);
}

// JavaScript String(number) for the values the messages can hit.
function compose_num_text($v): string
{
    if (is_int($v)) return (string) $v;
    if (!is_finite($v)) return 'null';
    return floor($v) == $v ? sprintf('%.0f', $v) : json_encode($v);
}

// TS String(value) form for depends_on coercion and messages.
function compose_ts_str($v): string
{
    if ($v === null) return 'null';
    if ($v === true) return 'true';
    if ($v === false) return 'false';
    if (is_int($v) || is_float($v)) return compose_num_text($v);
    if (is_string($v)) return $v;
    if (compose_is_seq($v)) return implode(',', array_map('compose_ts_str', $v));
    return '[object Object]';
}

// One ports entry; an issue string or null. "8080", "80:8080",
// "127.0.0.1:80:8080", "::1:8080:80", "6053:53/udp" all pass.
function compose_port_issue($entry): ?string
{
    if (is_bool($entry)) return 'port must be a string or integer';
    if (is_int($entry) || is_float($entry)) {
        if (is_float($entry) && (!is_finite($entry) || floor($entry) != $entry)) {
            return 'port must be a string or integer';
        }
        if ($entry < 0 || $entry > 65535) return 'port ' . compose_num_text($entry) . ' out of range 0-65535';
        return null;
    }
    if (!is_string($entry)) return 'port must be a string or integer';
    $slash = strpos($entry, '/');
    $proto = $slash === false ? '' : substr($entry, $slash + 1);
    if ($proto !== '' && $proto !== 'tcp' && $proto !== 'udp') {
        return "unknown protocol \"$proto\" (use tcp or udp)";
    }
    $body = $proto === '' ? $entry : substr($entry, 0, $slash);
    $parts = explode(':', $body);
    // Host forms (localhost, IPv6 like ::1) carry non-numeric parts anywhere.
    foreach ($parts as $p) if (!preg_match('/^[0-9]+$/', $p)) return null;
    if (count($parts) > 3) return 'port must have 1-3 colon-separated parts';
    foreach ($parts as $p) if ((int) $p > 65535) return "port $p out of range 0-65535";
    return null;
}

// Walk the document; append issues in TS order (root, services, per-service
// in document order, then depends_on cycle detection).
function compose_check($root): array
{
    $out = [];
    $push = function (string $path, string $message) use (&$out): void {
        $out[] = ['path' => $path, 'message' => $message];
    };
    if (!compose_is_map($root)) {
        $push('$', 'compose root must be a mapping');
        return $out;
    }
    $services = $root['services'] ?? null;
    if (!compose_is_map($services)) {
        $push('$.services', 'missing or invalid "services" mapping');
        return $out;
    }
    $ids = array_keys($services);
    if ($ids === []) $push('$.services', 'services must not be empty');
    foreach ($ids as $sid) {
        $svc = $services[$sid];
        $at = '$.services.' . $sid;
        if (!compose_is_map($svc)) {
            $push($at, 'service must be a mapping');
            continue;
        }
        if (!array_key_exists('image', $svc) && !array_key_exists('build', $svc)) {
            $push($at, 'service needs image or build');
        }
        if (array_key_exists('ports', $svc)) {
            $ports = $svc['ports'];
            if (!compose_is_seq($ports)) {
                $push($at . '.ports', 'ports must be a list');
            } else {
                foreach ($ports as $pi => $p) {
                    $m = compose_port_issue($p);
                    if ($m !== null) $push($at . '.ports[' . $pi . ']', $m);
                }
            }
        }
        if (array_key_exists('environment', $svc)) {
            $env = $svc['environment'];
            if (compose_is_map($env)) {
                foreach ($env as $k => $v) {
                    if ($v !== null && !is_string($v) && !is_int($v) && !is_float($v) && !is_bool($v)) {
                        $push($at . '.environment.' . $k, 'environment values must be scalars');
                    }
                }
            } elseif (compose_is_seq($env)) {
                foreach ($env as $ei => $e) {
                    if (!is_string($e) || preg_match('/^[^=]+=.*/s', $e) !== 1) {
                        $push($at . '.environment[' . $ei . ']', 'list environment entries must look like KEY=value');
                    }
                }
            } else {
                $push($at . '.environment', 'environment must be a mapping or a list');
            }
        }
        if (array_key_exists('volumes', $svc) && !compose_is_seq($svc['volumes'])) {
            $push($at . '.volumes', 'volumes must be a list');
        }
        if (array_key_exists('depends_on', $svc)) {
            $dep = $svc['depends_on'];
            if (!compose_is_seq($dep) && !is_string($dep) && !compose_is_map($dep)) {
                $push($at . '.depends_on', 'depends_on must be a string, list or mapping');
            } else {
                $names = compose_is_map($dep) ? array_keys($dep)
                    : (compose_is_seq($dep) ? array_map('compose_ts_str', $dep) : [$dep]);
                foreach ($names as $ni => $n) {
                    if (!array_key_exists($n, $services)) {
                        $push($at . '.depends_on[' . $ni . ']', "unknown service \"$n\"");
                    }
                }
            }
        }
    }

    // depends_on cycle detection (map-form conditions do not affect the graph).
    $color = [];
    $visit = null;
    $visit = function ($sid, array $stack) use (&$visit, &$color, $services, $push): void {
        $c = $color[$sid] ?? null;
        if ($c === 2) return;
        if ($c === 1) {
            $chain = array_slice($stack, array_search($sid, $stack, true));
            $chain[] = $sid;
            $push('$.services', 'depends_on cycle: ' . implode(' -> ', $chain));
            return;
        }
        $color[$sid] = 1;
        $svc = $services[$sid] ?? null;
        if (compose_is_map($svc) && array_key_exists('depends_on', $svc)) {
            $raw = $svc['depends_on'];
            if (is_string($raw)) $names = [$raw];
            elseif (compose_is_seq($raw)) {
                $names = [];
                foreach ($raw as $e) if (is_string($e)) $names[] = $e;
            }
            elseif (compose_is_map($raw)) $names = array_keys($raw);
            else $names = [];
            foreach ($names as $n) {
                if (array_key_exists($n, $services)) $visit($n, array_merge($stack, [$sid]));
            }
        }
        $color[$sid] = 2;
    };
    foreach ($ids as $sid) $visit($sid, []);
    return $out;
}

// Validate a Docker Compose file → ['valid' =>, 'issues' =>, 'error' =>].
function validate_compose(string $raw): array
{
    if (trim($raw) === '') {
        return ['valid' => false, 'issues' => [], 'error' => 'A compose document is required'];
    }
    try {
        $root = compose_parse_yaml($raw);
    } catch (RuntimeException $e) {
        return ['valid' => false, 'issues' => [], 'error' => $e->getMessage()];
    }
    $issues = compose_check($root);
    return ['valid' => $issues === [], 'issues' => $issues, 'error' => null];
}

// Example:
// validate_compose("services:\n  web:\n    image: nginx:1.25\n    ports:\n      - \"8080:80\"\n  db:\n    image: postgres:16\n    depends_on: web")["valid"]
// → true
// validate_compose("services:\n  web:\n    image: nginx\n    ports: [\"99999\"]")["issues"]
// → [["path" => "$.services.web.ports[0]", "message" => "port 99999 out of range 0-65535"]]
// validate_compose("services:\n  a:\n    image: x\n    depends_on: b\n  b:\n    image: y\n    depends_on: a")["issues"]
// → [["path" => "$.services", "message" => "depends_on cycle: a -> b -> a"]]

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →