Skip to content

AI Code Explainer — PHP source

Paste any code snippet and get a plain-language explanation from an LLM — beginner, developer, or expert depth — with your own free Groq key, straight from your browser.

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

<?php
/**
 * code-explainer — language guessing, depth-graded prompts, reply cleanup.
 *
 * Language: PHP 7.4+ (standard library only).
 * CosmoDev polyglot showcase port of the `code-explainer` tool, ported from
 * src/lib/code-explainer.ts (the canonical TypeScript implementation).
 *
 * Why this file exists: the whole explainer pipeline is three pure functions —
 * guess the language, build a depth-graded chat prompt, strip code fences from
 * the reply. PCRE (preg_*) speaks the TS regex dialect almost natively, so the
 * heuristics port verbatim with only delimiter and modifier syntax changes.
 *
 * display source — part of CosmoDev's polyglot tool pages.
 */

declare(strict_types=1);

const CE_MAX_CODE_CHARS = 12000;

/** Per-level explanation contract, verbatim from the TS lib. */
const CE_LEVEL_CONTRACT = [
    'beginner' => 'Explain for a smart newcomer: no unexplained jargon, short sentences, one everyday analogy if it helps. Say what it does first, then how, step by step.',
    'developer' => 'Explain for a working developer: concise and practical. Lead with what it does, then the flow, the patterns used, and the pitfalls an editor should catch.',
    'expert' => 'Explain for an expert: dense and precise. Cover invariants, complexity, edge cases, and anything subtle an experienced reviewer would flag.',
];

/**
 * Cheap keyword heuristics — enough to name the language in the prompt so the
 * model starts right; never a language detector. First match wins, so order
 * matters: go before rust before python before the web trio.
 */
const CE_RULES = [
    'go' => '/\bpackage\s+\w+|\bfunc\s+\w+|:=/',
    'rust' => '/\bfn\s+\w+|\blet\s+mut\b|\bimpl\b/',
    'python' => '/\bdef\s+\w+\s*\(|\bprint\s*\(|\bimport\s+\w+\s*$/m',
    'sql' => '/\bSELECT\b.+\bFROM\b/i',
    'typescript' => '/\binterface\s+\w+\s*\{|\btype\s+\w+\s*=|:\s*(string|number|boolean)\b/',
    'javascript' => '/\bconst\s+\w+\s*=|=>|console\.log/',
    'css' => '/[.#]?[\w-]+\s*\{[^}]*:[^}]*;/',
    'html' => '/<\/?[a-z][\w-]*(\s+[\w-]+="[^"]*")*\s*\/?>/i',
];

/**
 * Guess the language of a code sample. Falls back to 'text' when no rule
 * matches, so the prompt can tell the model to reason about the paste as
 * pseudocode instead of pretending to know better.
 */
function guessLanguage(string $code): string
{
    foreach (CE_RULES as $lang => $pattern) {
        if (preg_match($pattern, $code) === 1) {
            return $lang;
        }
    }

    return 'text';
}

/**
 * Build the [system, user] chat messages for the provider layer.
 *
 * Truncation uses mb_* over UTF-8 code points; the TS original slices UTF-16
 * code units — identical for all BMP text, which is what code pastes are.
 *
 * @return array<int, array{role: string, content: string}>
 */
function buildPromptMessages(string $code, string $level): array
{
    $truncated = mb_strlen($code, 'UTF-8') > CE_MAX_CODE_CHARS;
    $body = $truncated
        ? mb_substr($code, 0, CE_MAX_CODE_CHARS, 'UTF-8') . "\n… (code truncated)"
        : $code;
    $lang = guessLanguage($body);
    $uncertainty = $lang === 'text'
        ? ' (no clear language — say so and reason about it as pseudocode)'
        : '';

    return [
        [
            'role' => 'system',
            'content' => 'You explain code. ' . CE_LEVEL_CONTRACT[$level]
                . " The code appears to be {$lang}{$uncertainty}"
                . '. Use short paragraphs or bullets; markdown is fine.',
        ],
        ['role' => 'user', 'content' => $body],
    ];
}

/**
 * Clean the model's reply into displayable explanation text: strip markdown
 * code fences, then trim. Returns null only when nothing survives cleaning —
 * there is no strict format contract beyond "non-empty".
 */
function parseExplanation(string $text): ?string
{
    $cleaned = trim((string) preg_replace('/```[a-z]*\n?/', '', $text));

    return $cleaned !== '' ? $cleaned : null;
}

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 →