1<?php
2
3namespace dokuwiki\plugin\wordimport\docx;
4
5/**
6 * The relationships of a docx file
7 *
8 * This file contains the relationships between the different parts of the docx file
9 */
10class Relationships extends AbstractXMLFile
11{
12    /**
13     * @var array The relationships type -> id -> target
14     */
15    protected $relationships = [];
16
17    /** @inheritdoc */
18    protected function parse()
19    {
20        $xml = $this->docx->loadXMLFile('word/_rels/document.xml.rels');
21        $this->registerNamespaces($xml);
22
23        foreach ($xml->xpath('//rs:Relationship') as $rel) {
24            $id = (string)$rel->attributes()->Id;
25            $type = basename((string)$rel->attributes()->Type);
26            $target = 'word/' . $rel->attributes()->Target;
27
28            if (!isset($this->relationships[$type])) {
29                $this->relationships[$type] = [];
30            }
31            $this->relationships[$type][$id] = $target;
32        }
33    }
34
35    /**
36     * Get the target for the given type and ID
37     *
38     * @param string $type
39     * @param string $id
40     * @return string The target path relative to the docx file's root (eg. with a word/ prefix)
41     * @throws \Exception
42     */
43    public function getTarget($type, $id = null): ?string
44    {
45        if ($id === null) {
46            $id = array_keys($this->relationships[$type] ?? [])[0] ?? null;
47            if ($id === null) throw new \Exception('No relationship found for type ' . $type);
48        }
49
50        if (!isset($this->relationships[$type][$id])) {
51            throw new \Exception('No relationship found for type ' . $type . ' and id ' . $id);
52        }
53
54        return $this->relationships[$type][$id];
55    }
56}
57