<?php

namespace Dalten\TestHelper;

use Symfony\Component\DomCrawler\Crawler;


trait DomDocumentTestTrait
{
	/**
	 * Assert the presence, absence, or count of elements in a document matching
	 * the CSS $selector, regardless of the contents of those elements.
	 *
	 * The first argument, $selector, is the CSS selector used to match
	 * the elements in the $actual document.
	 *
	 * The second argument, $count, can be either boolean or numeric.
	 * When boolean, it asserts for presence of elements matching the selector
	 * (true) or absence of elements (false).
	 * When numeric, it asserts the count of elements.
	 *
	 * assertSelectCount("#binder", true, $xml);  // any?
	 * assertSelectCount(".binder", 3, $xml);     // exactly 3?
	 *
	 * @param string   $selector
	 * @param int|bool $expected
	 * @param mixed    $actual
	 * @param string   $message
	 * @param bool     $isHtml
	 */
	public static function assertSelectCount($selector, $expected, $actual, $message = '', $isHtml = true)
	{
		if ($isHtml) {
			$crawler = new Crawler($actual);
		} else {
			$crawler = new Crawler();
			$crawler->addXmlContent($actual);
		}
		$found = $crawler->filter($selector)->count();

		if (is_bool($expected)) {
			self::assertGreaterThan(
				0, $found, $message ?: sprintf('Expected to find "%s" but zero occurences found.', $selector)
			);
		} else {
			self::assertEquals(
				$expected, $found,
				$message ?: sprintf('Found %d occurences of "%s", expected %d.', $found, $selector, $expected)
			);
		}
	}
}
