<?php
namespace App\Services;


class ValidNameGeneratorService
{
    /**
     * Check if a string is a valid PHP identifier:
     *   - starts with a letter (any case) or underscore
     *   - followed by any number of letters, digits or underscores
     *
     * @param  string  $name
     * @return bool
     */
    public static function isValidName(string $name): bool
    {
        return (bool) preg_match('/^[A-Za-z_\x80-\xff][A-Za-z0-9_\x80-\xff]*$/', $name);
    }

    /**
     * Turn any string into a valid PHP identifier by:
     *   1. replacing invalid characters with '_'
     *   2. ensuring it doesn't start with a digit
     *   3. ensuring it's not empty
     *
     * @param  string  $name
     * @return string
     */
    public static function makeValidName(string $name): string
    {
        // 1) replace any character that's not letter, digit or underscore
        $valid = preg_replace('/[^A-Za-z0-9_]/', '_', $name);

        // 2) if it starts with a digit, prefix an underscore
        if (preg_match('/^[0-9]/', $valid)) {
            $valid = '_' . $valid;
        }

        // 3) if empty (e.g. input was all invalid chars), use a single underscore
        if ($valid === '' || $valid === false) {
            $valid = '_';
        }

        return $valid;
    }
}
