<?php

/**
 * Shared PHP string helpers for static safety rules.
 *
 * @package LolaCore\Builder\Safety
 * @license GPL-2.0-or-later
 */

declare(strict_types=1);

namespace LolaCore\Builder\Safety;

if (! defined('ABSPATH')) {
	exit;
}

/**
 * Lightweight comment stripping and line lookup for regex-based safety rules.
 */
final class SafetyPhpHelper {

	/**
	 * Remove block and line comments so pattern checks ignore docblocks.
	 */
	public static function stripComments( string $php ): string {
		$php = preg_replace('/\/\*.*?\*\//s', '', $php) ?? $php;
		$php = preg_replace('/\/\/.*$/m', '', $php) ?? $php;
		$php = preg_replace('/#.*$/m', '', $php) ?? $php;

		return $php;
	}

	public static function lineNumberForMatch( string $php, string $needle ): int {
		$position = strpos($php, $needle);
		if ($position === false) {
			return 0;
		}

		return substr_count(substr($php, 0, $position), "\n") + 1;
	}
}
