joeycumines/simple-xml-util

用于提高依赖于PHP的simplexml_load_string函数的代码的可维护性的工具。

v1.0.0-alpha 2017-12-01 15:57 UTC

This package is not auto-updated.

Last update: 2024-09-19 04:18:04 UTC


README

用于提高依赖于PHP的simplexml_load_string函数的代码的可维护性的工具。

特性

  • 更好的依赖注入接口
  • 自动管理内部错误,构建可读的错误字符串
  • 使得异常处理成为可能
  • 配置simplexml_load_stringlibxml_use_internal_errorslibxml_disable_entity_loader,而不感觉像是在依赖具有副作用的全局变量

示例

// manual configuration example

use JoeyCumines\SimpleXmlUtil\Parser\SimpleXmlStringParser;

// ...

$xmlParser = new SimpleXmlStringParser($className, $options, $ns, $prefix, $disableEntityLoader);

// or

$xmlParser = (new SimpleXmlStringParser())
    ->setClassName($className)
    ->setOptions($options)
    ->setNs($ns)
    ->setPrefix($prefix)
    ->setDisableEntityLoader($disableEntityLoader);


// use the interface in the service - pre-configured

use JoeyCumines\SimpleXmlUtil\Exception\SimpleXmlStringParserException;
use JoeyCumines\SimpleXmlUtil\Interfaces\SimpleXmlStringParserInterface;

// ...

class SomeService
{
    private $xmlParser;
    private $logger;

    public function __construct(
        SimpleXmlStringParserInterface $xmlParser,
        Logger $logger
    ) {
        $this->xmlParser = $xmlParser;
        $this->logger = $logger;
    }
    
    public function doSomeXmlParsing(string $data): array
    {
        try {
            $doc = $this->xmlParser->parseXmlString($data);
        } catch (SimpleXmlStringParserException $e) {
            // the actual parser error will come through in the logs
            $this->logger->error(
                "[SomeService] o no our xml things failed:\n{$e}",
                $e
            );
            
            throw $e;
        }
        
        // at this point you can always be sure $doc is an actual object
        
        foreach ($doc as $name => $child) {
            // ...
        }
        
        // ...
    }
}