<?php

namespace Planaday\Utility\Debug;

class TraitChecker {
	public static function hasTrait(string $traitName, object|string $class): bool {
		$traits = self::class_uses_deep($class);
		return in_array($traitName, $traits);
	}

	/**
	 * @param object|string $class
	 *
	 * @return string[]
	 */
	public static function class_uses_deep(object|string $class):array{
		$traits = class_uses($class);
		$parents = class_parents($class);

		if ($traits === false) $traits = [];
		if ($parents === false) $parents = [];

		foreach ($parents as $parent) {
			$parentTraits = class_uses($parent);
			if ($parentTraits) $traits = array_merge($traits, $parentTraits);
		}

		$traitsToSearch = $traits;
		while (!empty($traitsToSearch)) {
			$newTraits = class_uses(array_pop($traitsToSearch));
			$traits = array_merge($newTraits, $traits);
			$traitsToSearch = array_merge($newTraits, $traitsToSearch);
		}

		return array_unique($traits);
	}

}