Version 1
[yaffs-website] / web / modules / contrib / migrate_plus / src / Plugin / migrate_plus / data_parser / SimpleXml.php
1 <?php
2
3 namespace Drupal\migrate_plus\Plugin\migrate_plus\data_parser;
4
5 use Drupal\migrate\MigrateException;
6 use Drupal\migrate_plus\DataParserPluginBase;
7
8 /**
9  * Obtain XML data for migration using the SimpleXML API.
10  *
11  * @DataParser(
12  *   id = "simple_xml",
13  *   title = @Translation("Simple XML")
14  * )
15  */
16 class SimpleXml extends DataParserPluginBase {
17
18   use XmlTrait;
19
20   /**
21    * Array of matches from item_selector.
22    *
23    * @var array
24    */
25   protected $matches = [];
26
27   /**
28    * {@inheritdoc}
29    */
30   public function __construct(array $configuration, $plugin_id, $plugin_definition) {
31     parent::__construct($configuration, $plugin_id, $plugin_definition);
32
33     // Suppress errors during parsing, so we can pick them up after.
34     libxml_use_internal_errors(TRUE);
35   }
36
37   /**
38    * {@inheritdoc}
39    */
40   protected function openSourceUrl($url) {
41     $xml_data = $this->getDataFetcherPlugin()->getResponseContent($url);
42     $xml = simplexml_load_string($xml_data);
43     $this->registerNamespaces($xml);
44     $xpath = $this->configuration['item_selector'];
45     $this->matches = $xml->xpath($xpath);
46     foreach (libxml_get_errors() as $error) {
47       $error_string = self::parseLibXmlError($error);
48       throw new MigrateException($error_string);
49     }
50     return TRUE;
51   }
52
53   /**
54    * {@inheritdoc}
55    */
56   protected function fetchNextRow() {
57     $target_element = array_shift($this->matches);
58
59     // If we've found the desired element, populate the currentItem and
60     // currentId with its data.
61     if ($target_element !== FALSE && !is_null($target_element)) {
62       foreach ($this->fieldSelectors() as $field_name => $xpath) {
63         foreach ($target_element->xpath($xpath) as $value) {
64           $this->currentItem[$field_name][] = (string) $value;
65         }
66       }
67       // Reduce single-value results to scalars.
68       foreach ($this->currentItem as $field_name => $values) {
69         if (count($values) == 1) {
70           $this->currentItem[$field_name] = reset($values);
71         }
72       }
73     }
74   }
75
76 }