| 1 |
<?php |
| 2 |
|
| 3 |
namespace TablePress\PhpOffice\PhpSpreadsheet\Reader\Xlsx; |
| 4 |
|
| 5 |
use TablePress\PhpOffice\PhpSpreadsheet\Cell\Coordinate; |
| 6 |
use TablePress\PhpOffice\PhpSpreadsheet\Reader\Xlsx; |
| 7 |
use TablePress\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; |
| 8 |
use SimpleXMLElement; |
| 9 |
|
| 10 |
class Hyperlinks |
| 11 |
{ |
| 12 |
private Worksheet $worksheet; |
| 13 |
|
| 14 |
/** @var string[] */ |
| 15 |
private array $hyperlinks = []; |
| 16 |
|
| 17 |
public function __construct(Worksheet $workSheet) |
| 18 |
{ |
| 19 |
$this->worksheet = $workSheet; |
| 20 |
} |
| 21 |
|
| 22 |
public function readHyperlinks(SimpleXMLElement $relsWorksheet): void |
| 23 |
{ |
| 24 |
foreach ($relsWorksheet->children(Namespaces::RELATIONSHIPS)->Relationship as $elementx) { |
| 25 |
$element = Xlsx::getAttributes($elementx); |
| 26 |
if ($element->Type == Namespaces::HYPERLINK) { |
| 27 |
$this->hyperlinks[(string) $element->Id] = (string) $element->Target; |
| 28 |
} |
| 29 |
} |
| 30 |
} |
| 31 |
|
| 32 |
public function setHyperlinks(SimpleXMLElement $worksheetXml): void |
| 33 |
{ |
| 34 |
foreach ($worksheetXml->children(Namespaces::MAIN)->hyperlink as $hyperlink) { |
| 35 |
$this->setHyperlink($hyperlink, $this->worksheet); |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
private function setHyperlink(SimpleXMLElement $hyperlink, Worksheet $worksheet): void |
| 40 |
{ |
| 41 |
// Link url |
| 42 |
$linkRel = Xlsx::getAttributes($hyperlink, Namespaces::SCHEMA_OFFICE_DOCUMENT); |
| 43 |
|
| 44 |
$attributes = Xlsx::getAttributes($hyperlink); |
| 45 |
foreach (Coordinate::extractAllCellReferencesInRange($attributes->ref) as $cellReference) { |
| 46 |
$cell = $worksheet->getCell($cellReference); |
| 47 |
|
| 48 |
$hyperlinkUrl = ''; |
| 49 |
if (isset($linkRel['id'])) { |
| 50 |
$hyperlinkUrl = $this->hyperlinks[(string) $linkRel['id']] ?? ''; |
| 51 |
} |
| 52 |
if (isset($attributes['location'])) { |
| 53 |
if ($hyperlinkUrl === '') { |
| 54 |
$hyperlinkUrl = 'sheet://' . (string) $attributes['location']; |
| 55 |
} else { |
| 56 |
$hyperlinkUrl .= '#' . (string) $attributes['location']; |
| 57 |
} |
| 58 |
} |
| 59 |
$cell->getHyperlink()->setUrl($hyperlinkUrl); |
| 60 |
// Tooltip |
| 61 |
if (isset($attributes['tooltip'])) { |
| 62 |
$cell->getHyperlink()->setTooltip((string) $attributes['tooltip']); |
| 63 |
} |
| 64 |
|
| 65 |
if (isset($attributes['display'])) { |
| 66 |
$cell->getHyperlink()->setDisplay((string) $attributes['display']); |
| 67 |
} |
| 68 |
} |
| 69 |
} |
| 70 |
} |
| 71 |
|