This commit is contained in:
2026-09-15 10:26:34 +08:00
commit ecf36afa56
10493 changed files with 1404888 additions and 0 deletions
@@ -0,0 +1,164 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Helper;
/**
* Helper class to access RabbitMQ server configuration
*/
class Amqp
{
const CONFIG_PATH_HOST = 'queue/amqp/host';
const CONFIG_PATH_USER = 'queue/amqp/user';
const CONFIG_PATH_PASSWORD = 'queue/amqp/password';
const DEFAULT_MANAGEMENT_PROTOCOL = 'http';
const DEFAULT_MANAGEMENT_PORT = '15672';
const DEFAULT_VIRTUALHOST = '/';
/**
* @var Curl
*/
private $curl;
/**
* @var \Magento\Framework\App\DeploymentConfig
*/
private $deploymentConfig;
/**
* @var string
*/
private $host;
/**
* @var string
*/
private $virtualHost;
/**
* Initialize dependencies.
* @param \Magento\Framework\App\DeploymentConfig $deploymentConfig
*/
public function __construct(
\Magento\Framework\App\DeploymentConfig $deploymentConfig = null
) {
$this->deploymentConfig = $deploymentConfig ?? \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->get(\Magento\Framework\App\DeploymentConfig::class);
$this->curl = new Curl();
$this->curl->setCredentials(
$this->deploymentConfig->get(self::CONFIG_PATH_USER),
$this->deploymentConfig->get(self::CONFIG_PATH_PASSWORD)
);
$this->curl->addHeader('content-type', 'application/json');
$this->host = sprintf(
'%s://%s:%s/api/',
defined('RABBITMQ_MANAGEMENT_PROTOCOL')
? RABBITMQ_MANAGEMENT_PROTOCOL
: self::DEFAULT_MANAGEMENT_PROTOCOL,
$this->deploymentConfig->get(self::CONFIG_PATH_HOST),
defined('RABBITMQ_MANAGEMENT_PORT') ? RABBITMQ_MANAGEMENT_PORT : self::DEFAULT_MANAGEMENT_PORT
);
$this->virtualHost = defined('RABBITMQ_VIRTUALHOST') ? RABBITMQ_VIRTUALHOST : self::DEFAULT_VIRTUALHOST;
}
/**
* Check that the RabbitMQ instance has the management plugin installed and the api is available.
*
* @return bool
*/
public function isAvailable(): bool
{
$this->curl->get($this->host . 'overview');
$data = $this->curl->getBody();
$data = json_decode($data, true);
return isset($data['management_version']);
}
/**
* Get declared exchanges.
*
* @return array
*/
public function getExchanges()
{
$this->curl->get($this->host . 'exchanges/' . urlencode($this->virtualHost));
$data = $this->curl->getBody();
$data = json_decode($data, true);
$output = [];
foreach ($data as $value) {
$output[$value['name']] = $value;
}
return $output;
}
/**
* Get declared exchange bindings.
*
* @param string $name
* @return array
*/
public function getExchangeBindings($name)
{
$this->curl->get($this->host . 'exchanges/' . urlencode($this->virtualHost) . '/' . $name . '/bindings/source');
$data = $this->curl->getBody();
return json_decode($data, true);
}
/**
* Get All available connections
*
* @return array
*/
public function getConnections()
{
$this->curl->get($this->host . 'vhosts/' . urlencode($this->virtualHost) . '/connections');
$data = $this->curl->getBody();
$data = json_decode($data, true);
$output = [];
foreach ($data as $value) {
$output[$value['name']] = $value;
}
return $output;
}
/**
* Clear Queue
*
* @param string $name
* @param int $numMessages
* @return string
*/
public function clearQueue(string $name, int $numMessages = 50)
{
$body = [
"count" => $numMessages,
"ackmode" => "ack_requeue_false",
"encoding" => "auto",
"truncate" => 50000
];
$this->curl->post(
$this->host . 'queue/' . urlencode($this->virtualHost) . '/' . $name . '/get',
json_encode($body)
);
return $this->curl->getBody();
}
/**
* Delete connection
*
* @param string $name
* @return string $data
*/
public function deleteConnection($name)
{
$this->curl->delete($this->host . 'conections/' . urlencode($name));
$data = $this->curl->getBody();
return $data;
}
}
@@ -0,0 +1,205 @@
<?php
/**
* Helper for API integration tests.
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\Helper;
class Api
{
/**
* Previous error handler
*
* @var mixed
*/
protected static $_previousHandler = null;
/**
* Call API method via API handler.
*
* @param \PHPUnit\Framework\TestCase $testCase Active test case
* @param string $path
* @param array $params Order of items matters as they are passed to call_user_func_array
* @return mixed
*/
public static function call(\PHPUnit\Framework\TestCase $testCase, $path, $params = [])
{
$soapAdapterMock = $testCase->getMock(\stdClass::class, ['fault']);
$soapAdapterMock->expects(
$testCase->any()
)->method(
'fault'
)->will(
$testCase->returnCallback([__CLASS__, 'soapAdapterFaultCallback'])
);
$serverMock = $testCase->getMock(\stdClass::class, ['getAdapter']);
$serverMock->expects($testCase->any())->method('getAdapter')->will($testCase->returnValue($soapAdapterMock));
$apiSessionMock = $testCase->createPartialMock(\stdClass::class, ['isAllowed', 'isLoggedIn']);
$apiSessionMock->expects($testCase->any())->method('isAllowed')->will($testCase->returnValue(true));
$apiSessionMock->expects($testCase->any())->method('isLoggedIn')->will($testCase->returnValue(true));
$handlerMock = $testCase->createPartialMock(\stdClass::class, ['_getServer', '_getSession']);
self::$_previousHandler = set_error_handler([$handlerMock, 'handlePhpError']);
$handlerMock->expects($testCase->any())->method('_getServer')->will($testCase->returnValue($serverMock));
$handlerMock->expects($testCase->any())->method('_getSession')->will($testCase->returnValue($apiSessionMock));
array_unshift($params, 'sessionId');
/** @var $objectManager \Magento\TestFramework\ObjectManager */
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$objectManager->get(\Magento\Framework\Registry::class)->unregister('isSecureArea');
$objectManager->get(\Magento\Framework\Registry::class)->register('isSecureArea', true);
$result = call_user_func_array([$handlerMock, $path], $params);
$objectManager->get(\Magento\Framework\Registry::class)->unregister('isSecureArea');
$objectManager->get(\Magento\Framework\Registry::class)->register('isSecureArea', false);
self::restoreErrorHandler();
return $result;
}
/**
* Call API method via API handler that raises SoapFault exception
*
* @param \PHPUnit\Framework\TestCase $testCase Active test case
* @param string $path
* @param array $params Order of items matters as they are passed to call_user_func_array
* @param string $expectedMessage exception message
* @return \SoapFault
*/
public static function callWithException(
\PHPUnit\Framework\TestCase $testCase,
$path,
$params = [],
$expectedMessage = ''
) {
try {
self::call($testCase, $path, $params);
self::restoreErrorHandler();
$testCase->fail('Expected error exception was not raised.');
} catch (\SoapFault $exception) {
self::restoreErrorHandler();
if ($expectedMessage) {
$testCase->assertEquals($expectedMessage, $exception->getMessage());
}
return $exception;
}
}
/**
* Restore previously used error handler
*/
public static function restoreErrorHandler()
{
set_error_handler(self::$_previousHandler);
}
/**
* Throw SoapFault exception. Callback for 'fault' method of API.
*
* @param string $exceptionCode
* @param string $exceptionMessage
* @throws \SoapFault
*/
public static function soapAdapterFaultCallback($exceptionCode, $exceptionMessage)
{
throw new \SoapFault($exceptionCode, $exceptionMessage);
}
/**
* Convert Simple XML to array
*
* @param \SimpleXMLObject $xml
* @param String $keyTrimmer
* @return object
*
* In XML notation we can't have nodes with digital names in other words fallowing XML will be not valid:
* &lt;24&gt;
* Default category
* &lt;/24&gt;
*
* But this one will not cause any problems:
* &lt;qwe_24&gt;
* Default category
* &lt;/qwe_24&gt;
*
* So when we want to obtain an array with key 24 we will pass the correct XML from above and $keyTrimmer = 'qwe_';
* As a result we will obtain an array with digital key node.
*
* In the other case just don't pass the $keyTrimmer.
*/
public static function simpleXmlToArray($xml, $keyTrimmer = null)
{
$result = [];
$isTrimmed = false;
if (null !== $keyTrimmer) {
$isTrimmed = true;
}
if (is_object($xml)) {
foreach (get_object_vars($xml->children()) as $key => $node) {
$arrKey = $key;
if ($isTrimmed) {
$arrKey = str_replace($keyTrimmer, '', $key);
}
if (is_numeric($arrKey)) {
$arrKey = 'Obj' . $arrKey;
}
if (is_object($node)) {
$result[$arrKey] = self::simpleXmlToArray($node, $keyTrimmer);
} elseif (is_array($node)) {
$result[$arrKey] = [];
foreach ($node as $nodeValue) {
$result[$arrKey][] = self::simpleXmlToArray($nodeValue, $keyTrimmer);
}
} else {
$result[$arrKey] = (string)$node;
}
}
} else {
$result = (string)$xml;
}
return $result;
}
/**
* Check specific fields value in some entity data.
*
* @param \PHPUnit\Framework\TestCase $testCase
* @param array $expectedData
* @param array $actualData
* @param array $fieldsToCompare To be able to compare fields from loaded model with fields from API response
* this parameter provides fields mapping.
* Array can store model field name $entityField mapped on field name in API response.
* $fieldsToCompare format is:
* $fieldsToCompare = array($modelFieldName => $apiResponseFieldName);
* Example:
* $fieldsToCompare = array(
* 'entity_id' => 'product_id',
* 'sku',
* 'attribute_set_id' => 'set',
* 'type_id' => 'type',
* 'category_ids',
* );
*/
public static function checkEntityFields(
\PHPUnit\Framework\TestCase $testCase,
array $expectedData,
array $actualData,
array $fieldsToCompare = []
) {
$fieldsToCompare = !empty($fieldsToCompare) ? $fieldsToCompare : array_keys($expectedData);
foreach ($fieldsToCompare as $entityField => $field) {
$testCase->assertEquals(
$expectedData[is_numeric($entityField) ? $field : $entityField],
$actualData[$field],
sprintf('"%s" filed has invalid value.', $field)
);
}
}
}
@@ -0,0 +1,159 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Helper providing exclusive restricted access to the underlying bootstrap instance
*/
namespace Magento\TestFramework\Helper;
class Bootstrap
{
/**
* @var \Magento\TestFramework\Helper\Bootstrap
*/
private static $_instance;
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private static $_objectManager;
/**
* @var \Magento\TestFramework\Bootstrap
*/
protected $_bootstrap;
/**
* Set self instance for static access
*
* @param \Magento\TestFramework\Helper\Bootstrap $instance
* @throws \Magento\Framework\Exception\LocalizedException
*/
public static function setInstance(\Magento\TestFramework\Helper\Bootstrap $instance)
{
if (self::$_instance) {
throw new \Magento\Framework\Exception\LocalizedException(__('Helper instance cannot be redefined.'));
}
self::$_instance = $instance;
}
/**
* Self instance getter
*
* @return \Magento\TestFramework\Helper\Bootstrap
* @throws \Magento\Framework\Exception\LocalizedException
*/
public static function getInstance()
{
if (!self::$_instance) {
throw new \Magento\Framework\Exception\LocalizedException(__('Helper instance is not defined yet.'));
}
return self::$_instance;
}
/**
* Check the possibility to send headers or to use headers related function (like set_cookie)
*
* @return bool
*/
public static function canTestHeaders()
{
if (!headers_sent() && extension_loaded('xdebug') && function_exists('xdebug_get_headers')) {
return true;
}
return false;
}
/**
* Constructor
*
* @param \Magento\TestFramework\Bootstrap $bootstrap
*/
public function __construct(\Magento\TestFramework\Bootstrap $bootstrap)
{
$this->_bootstrap = $bootstrap;
}
/**
* Retrieve application installation directory
*
* @return string
*/
public function getAppTempDir()
{
return $this->_bootstrap->getApplication()->getTempDir();
}
/**
* Retrieve application initialization options
*
* @return array
*/
public function getAppInitParams()
{
return $this->_bootstrap->getApplication()->getInitParams();
}
/**
* Reinitialize the application instance optionally passing parameters to be overridden.
* Intended to be used for the tests isolation purposes.
*
* @param array $overriddenParams
*/
public function reinitialize(array $overriddenParams = [])
{
$this->_bootstrap->getApplication()->reinitialize($overriddenParams);
}
/**
* Perform the full request processing by the application instance.
* Intended to be used by the controller tests.
*/
public function runApp()
{
$this->_bootstrap->getApplication()->run();
}
/**
* Retrieve object manager
*
* @return \Magento\Framework\ObjectManagerInterface
*/
public static function getObjectManager()
{
return self::$_objectManager;
}
/**
* Set object manager
*
* @param \Magento\Framework\ObjectManagerInterface $objectManager
*/
public static function setObjectManager(\Magento\Framework\ObjectManagerInterface $objectManager)
{
self::$_objectManager = $objectManager;
}
/**
* Get bootstrap object
*
* @return \Magento\TestFramework\Bootstrap
*/
public function getBootstrap()
{
return $this->_bootstrap;
}
/**
* Load area
* @param string $areaCode
*/
public function loadArea($areaCode)
{
self::$_objectManager->get(\Magento\Framework\App\State::class)->setAreaCode($areaCode);
self::$_objectManager->get(\Magento\Framework\App\AreaList::class)->getArea($areaCode)->load();
}
}
@@ -0,0 +1,50 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\Helper;
use Magento\Framework\App\Cache\Frontend\Pool;
/**
* Helper for cleaning cache
*/
class CacheCleaner
{
/**
* Clean cache by specified types
*
* @param array $cacheTypes
*/
public static function clean(array $cacheTypes = [])
{
$cachePool = self::getCachePool();
foreach ($cacheTypes as $cacheType) {
$cachePool->get($cacheType)->getBackend()->clean();
}
}
/**
* Clean all cache
*/
public static function cleanAll()
{
$cachePool = self::getCachePool();
foreach ($cachePool as $cacheType) {
$cacheType->getBackend()->clean();
}
}
/**
* Get cache pool
*
* @return Pool
*/
private static function getCachePool()
{
return Bootstrap::getObjectManager()
->get(Pool::class);
}
}
@@ -0,0 +1,27 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Helper with routines to work with Magento config
*/
namespace Magento\TestFramework\Helper;
class Config
{
/**
* Returns enabled modules in the system
*
* @return array
*/
public function getEnabledModules()
{
/** @var \Magento\Framework\Module\ModuleListInterface $moduleList */
$moduleList = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\Module\ModuleListInterface::class
);
return $moduleList->getNames();
}
}
@@ -0,0 +1,30 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Helper;
use Magento\Framework\HTTP\Client\Curl as CurlLibrary;
class Curl extends CurlLibrary
{
/**
* Make DELETE request
*
* String type was added to parameter $param in order to support sending JSON or XML requests.
* This feature was added base on Community Pull Request https://github.com/magento/magento2/pull/8373
*
* @param string $uri
* @return void
*
* @see \Magento\Framework\HTTP\Client#post($uri, $params)
*/
public function delete($uri)
{
$this->makeRequest("DELETE", $uri);
}
}
@@ -0,0 +1,41 @@
<?php
/**
* Helper for EAV functionality in integration tests.
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\Helper;
class Eav
{
/**
* Set increment id prefix in entity model.
*
* @param string $entityType
* @param string $prefix
*/
public static function setIncrementIdPrefix($entityType, $prefix)
{
$website = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Store\Model\StoreManagerInterface::class
)->getWebsite();
$storeId = $website->getDefaultStore()->getId();
$entityTypeModel = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Eav\Model\Entity\Type::class
)->loadByCode(
$entityType
);
/** @var \Magento\Eav\Model\Entity\Store $entityStore */
$entityStore = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Eav\Model\Entity\Store::class
)->loadByEntityStore(
$entityTypeModel->getId(),
$storeId
);
$entityStore->setEntityTypeId($entityTypeModel->getId());
$entityStore->setStoreId($storeId);
$entityStore->setIncrementPrefix($prefix);
$entityStore->save();
}
}
@@ -0,0 +1,48 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Factory for helpers, used in Magento testing framework
*/
namespace Magento\TestFramework\Helper;
class Factory
{
/**
* @var array
*/
protected static $_instances = [];
/**
* Retrieves singleton instance of helper
*
* @param string $name
* @return mixed
*/
public static function getHelper($name)
{
if (!isset(self::$_instances[$name])) {
$className = preg_replace('/[^_]*$/', ucfirst($name), __CLASS__, 1);
self::$_instances[$name] = new $className();
}
return self::$_instances[$name];
}
/**
* Sets custom helper instance to be used for specific name, or null to clear instance.
* Returns previous instance (if any) or null (if no helper was defined).
*
* @param string $name
* @param mixed $helper
* @return mixed
*/
public static function setHelper($name, $helper)
{
$old = isset(self::$_instances[$name]) ? self::$_instances[$name] : null;
self::$_instances[$name] = $helper;
return $old;
}
}
@@ -0,0 +1,169 @@
<?php
/**
* Helper for determining system memory usage
*
* Uses OS tools to provide accurate information about factual memory consumption.
* The PHP standard functions may return incorrect information because the process itself may have leaks.
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\Helper;
/**
* Integration Test Framework memory management logic.
*/
class Memory
{
/**
* Prefixes to specify unit of measure for memory amount
*
* Warning: it is important to maintain the exact order of letters in this literal,
* as it is used to convert string with units to bytes
*/
const MEMORY_UNITS = 'BKMGTPE';
/**
* @var \Magento\Framework\Shell
*/
private $_shell;
/**
* Inject dependencies
*
* @param \Magento\Framework\Shell $shell
*/
public function __construct(\Magento\Framework\Shell $shell)
{
$this->_shell = $shell;
}
/**
* Retrieve the effective memory usage of the current process
*
* Function memory_get_usage() cannot be used because of the bug
*
* @link https://bugs.php.net/bug.php?id=62467
* @return int Memory usage in bytes
*/
public function getRealMemoryUsage()
{
$pid = getmypid();
try {
// fall back to the Unix command line
$result = $this->_getUnixProcessMemoryUsage($pid);
} catch (\Magento\Framework\Exception\LocalizedException $e) {
// try to use the Windows command line
// some ports of Unix commands on Windows, such as MinGW, have limited capabilities and cannot be used
$result = $this->_getWinProcessMemoryUsage($pid);
}
return $result;
}
/**
* Retrieve the current process' memory usage using Unix command line interface
*
* @link http://linux.die.net/man/1/ps
* @param int $pid
* @return int Memory usage in bytes
*/
protected function _getUnixProcessMemoryUsage($pid)
{
// RSS - resident set size, the non-swapped physical memory
$command = 'ps --pid %s --format rss --no-headers';
if ($this->isMacOS()) {
$command = 'ps -p %s -o rss=';
}
$output = $this->_shell->execute($command, [$pid]);
$result = $output . 'k';
// kilobytes
return self::convertToBytes($result);
}
/**
* Retrieve the current process' memory usage using Windows command line interface
*
* @link http://technet.microsoft.com/en-us/library/bb491010.aspx
* @param int $pid
* @return int Memory usage in bytes
*/
protected function _getWinProcessMemoryUsage($pid)
{
$output = $this->_shell->execute('tasklist.exe /fi %s /fo CSV /nh', ["PID eq {$pid}"]);
$arr = str_getcsv($output);
$memory = $arr[4];
return self::convertToBytes($memory);
}
/**
* Convert a number optionally followed by the unit symbol (B, K, M, G, etc.) to bytes
*
* @param string $number String representation of a number
* @return int
* @throws \InvalidArgumentException
* @throws \OutOfBoundsException
* phpcs:disable Magento2.Functions.StaticFunction
*/
public static function convertToBytes($number)
{
// phpcs:enable Magento2.Functions.StaticFunction
if (!preg_match('/^(.*\d)\h*(\D)$/', $number, $matches)) {
throw new \InvalidArgumentException("Number format '{$number}' is not recognized.");
}
$unitSymbol = strtoupper($matches[2]);
if (false === strpos(self::MEMORY_UNITS, $unitSymbol)) {
throw new \InvalidArgumentException("The number '{$number}' has an unrecognized unit: '{$unitSymbol}'.");
}
$result = self::_convertToNumber($matches[1]);
$pow = $unitSymbol ? strpos(self::MEMORY_UNITS, $unitSymbol) : 0;
$is32Bit = PHP_INT_SIZE == 4;
if ($is32Bit && $pow >= 4) {
throw new \OutOfBoundsException("A 32-bit system is unable to process such a number.");
}
if ($unitSymbol) {
$result *= pow(1024, $pow);
}
return (int)$result;
}
/**
* Remove non-numeric characters in the string to cast it to a numeric value
*
* Incoming number can be presented in arbitrary format that depends on locale. We don't possess locale information.
* So the best can be done is to treat number as an integer and eliminate delimiters.
* Method will not behave correctly with non-integer numbers for the following reason:
* - if value has more than one delimiter, such as in French notation: "1 234,56" -- then we can infer decimal part
* - but the value has only one delimiter, such as "234,56", then it is impossible to know whether it is decimal
* separator or not. Only knowing the right format would allow this.
*
* @param string $number
* @return string
* @throws \InvalidArgumentException
* phpcs:disable Magento2.Functions.StaticFunction
*/
protected static function _convertToNumber($number)
{
// phpcs:enable Magento2.Functions.StaticFunction
preg_match_all('/(\D+)/', $number, $matches);
if (count(array_unique($matches[0])) > 1) {
throw new \InvalidArgumentException(
"The number '{$number}' seems to have decimal part. Only integer numbers are supported."
);
}
return preg_replace('/\D+/', '', $number);
}
/**
* Whether the operating system belongs to the Mac family
*
* @link http://php.net/manual/en/function.php-uname.php
* @return boolean
* phpcs:disable Magento2.Functions.StaticFunction
*/
public static function isMacOs()
{
// phpcs:enable Magento2.Functions.StaticFunction
return strtoupper(PHP_OS) === 'DARWIN';
}
}
@@ -0,0 +1,68 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\Helper;
use DOMDocument;
use DOMNodeList;
use DOMXPath;
/**
* Xpath query helper
*/
class Xpath
{
/**
* Get elements count for XPath
*
* @param string $xpath
* @param string $html
* @return int
*/
public static function getElementsCountForXpath($xpath, $html)
{
$nodes = self::getElementsForXpath((string) $xpath, (string) $html);
return $nodes->length;
}
/**
* Get elements for XPath
*
* @param string $xpath
* @param string $html
* @return DOMNodeList
*/
public static function getElementsForXpath(string $xpath, string $html): DOMNodeList
{
$domXpath = self::getDOMXpath($html);
return $domXpath->query($xpath);
}
/**
* Get dom document instance
*
* @param string $html
* @return DOMDocument
*/
public static function getDOMDocument(string $html): DOMDocument
{
$domDocument = new DOMDocument('1.0', 'UTF-8');
libxml_use_internal_errors(true);
$domDocument->loadHTML($html);
libxml_use_internal_errors(false);
return $domDocument;
}
/**
* Get dom xpath instance
*
* @param string $html
* @return DOMXPath
*/
public static function getDOMXpath(string $html): DOMXPath
{
return new DOMXPath(self::getDOMDocument($html));
}
}