Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Fractor Xml Laravel Package

a9f/fractor-xml

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package

    composer require a9f/fractor-xml --dev
    

    Ensure you’re using --dev if this is for local development or testing.

  2. Register the Service Provider Add the package to your config/app.php under providers:

    AndreasWolf\FractorXml\FractorXmlServiceProvider::class,
    
  3. First Use Case: Basic XML Processing Create a custom rule implementing a9f\FractorXml\Contract\XmlFractor:

    use a9f\FractorXml\Contract\XmlFractor;
    use DOMNode;
    
    class ExampleXmlRule implements XmlFractor
    {
        public function process(DOMNode $node): void
        {
            // Example: Log all element names
            error_log($node->nodeName);
        }
    }
    

    Tag the rule in your service container:

    $this->app->tag([ExampleXmlRule::class], ['fractor.xml_rule']);
    
  4. Run the Processor Use the XmlFileProcessor to analyze/modify an XML file:

    use AndreasWolf\FractorXml\Processor\XmlFileProcessor;
    
    $processor = app(XmlFileProcessor::class);
    $processor->process('path/to/file.xml');
    

Implementation Patterns

Workflows

  1. Rule-Based Processing

    • Traversal: Leverage DOMNode methods (childNodes, firstChild, nextSibling) to traverse the XML tree.
    • Conditional Logic: Use nodeName, nodeValue, or XPath ($node->xpath()) to target specific nodes.
    • Modifications: Alter nodes via DOMNode methods (e.g., setAttribute, appendChild).

    Example: Update all <price> tags with a discount:

    public function process(DOMNode $node): void
    {
        if ($node->nodeName === 'price') {
            $newValue = $node->nodeValue * 0.9;
            $node->nodeValue = number_format($newValue, 2);
        }
    }
    
  2. Integration with Laravel

    • Artisan Commands: Create a custom command to process XML files in bulk:
      use Illuminate\Console\Command;
      use AndreasWolf\FractorXml\Processor\XmlFileProcessor;
      
      class ProcessXmlCommand extends Command
      {
          protected $signature = 'xml:process {files*}';
          protected $description = 'Process XML files with Fractor rules';
      
          public function handle(XmlFileProcessor $processor)
          {
              foreach ($this->argument('files') as $file) {
                  $processor->process($file);
              }
          }
      }
      
    • Events: Trigger processing after file uploads (e.g., via HandleUploadedFile events).
  3. Batch Processing

    • Use Laravel’s Storage facade to iterate over files in a directory:
      foreach (Storage::files('xml/') as $file) {
          $processor->process(storage_path("app/{$file}"));
      }
      
  4. Validation Rules

    • Combine with Laravel Validation to ensure XML conforms to schemas before processing:
      use Illuminate\Support\Facades\Validator;
      
      $validator = Validator::make(
          ['xml' => file_get_contents($file)],
          ['xml' => 'required|xml']
      );
      

Gotchas and Tips

Pitfalls

  1. XML Parsing Errors

    • Issue: Malformed XML may crash the processor.
    • Fix: Wrap processing in a try-catch and log errors:
      try {
          $processor->process($file);
      } catch (\Exception $e) {
          Log::error("Failed to process {$file}: " . $e->getMessage());
      }
      
    • Tip: Use libxml_use_internal_errors(true) to debug parsing issues:
      libxml_use_internal_errors(true);
      $dom = new DOMDocument();
      $dom->load($xmlString);
      foreach (libxml_get_errors() as $error) {
          error_log($error->message);
      }
      
  2. Performance with Large Files

    • Issue: Deep traversal of large XML files may timeout.
    • Fix:
      • Use DOMXPath for targeted queries instead of full traversal.
      • Process files in chunks or use streaming parsers like SimpleXML for read-heavy tasks.
  3. Namespace Handling

    • Issue: XML namespaces may break XPath queries.
    • Fix: Register namespaces in your XPath queries:
      $xpath = new DOMXPath($dom);
      $xpath->registerNamespace('ns', 'http://example.com/ns');
      $nodes = $xpath->query('//ns:element');
      
  4. Rule Ordering

    • Issue: Rules may override each other unpredictably.
    • Fix: Explicitly define rule priority in the service provider’s register method:
      $this->app->bind(XmlFileProcessor::class, function ($app) {
          $processor = new XmlFileProcessor();
          $processor->setRules([
              HighPriorityRule::class,
              LowPriorityRule::class,
          ]);
          return $processor;
      });
      

Tips

  1. Debugging Nodes

    • Dump node structures for debugging:
      public function process(DOMNode $node): void
      {
          dump([
              'name' => $node->nodeName,
              'value' => $node->nodeValue,
              'children' => iterator_to_array($node->childNodes),
          ]);
      }
      
  2. Testing Rules

    • Use Laravel’s XmlFileProcessor in tests with mock DOMDocument:
      public function testXmlRule()
      {
          $dom = new DOMDocument();
          $dom->loadXML('<root><price>100</price></root>');
      
          $rule = new ExampleXmlRule();
          $rule->process($dom->documentElement->firstChild);
      
          $this->assertEquals('90.00', $dom->documentElement->firstChild->nodeValue);
      }
      
  3. Extending Functionality

    • Custom Processors: Subclass XmlFileProcessor to add pre/post-processing hooks:
      class CustomXmlProcessor extends XmlFileProcessor
      {
          protected function beforeProcess(string $file): void
          {
              // Pre-processing logic (e.g., validation)
          }
      
          protected function afterProcess(string $file): void
          {
              // Post-processing logic (e.g., notifications)
          }
      }
      
    • Event Dispatching: Trigger Laravel events within rules:
      event(new XmlNodeProcessed($node));
      
  4. Configuration Quirks

    • Rule Discovery: Ensure tagged rules are autowired. If using custom tags, register them in config/fractor.php (if available) or manually in the service provider:
      $this->app->tag([CustomRule::class], ['fractor.xml_rule']);
      
  5. Memory Management

    • For memory-intensive tasks, use DOMDocument::loadXML() with LIBXML_NOBLANKS or LIBXML_NOCDATA flags to reduce memory usage:
      $dom->loadXML($xml, LIBXML_NOBLANKS);
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky