Skip to content

Commit

Permalink
wip: [Service][Util] StringLocator
Browse files Browse the repository at this point in the history
  • Loading branch information
77web committed Sep 25, 2014
1 parent d4f9b40 commit e32e03b
Show file tree
Hide file tree
Showing 2 changed files with 93 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/Service/Util/SharedStringReader.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

namespace Excel\Templating\Service\Util;

/**
* Class SharedStringReader
*/
class SharedStringReader
{
public function read(\ZipArchive $zip)
{
$xml = $zip->getFromName('xl/sharedStrings.xml');

$dom = new \DOMDocument;
$dom->loadXML($xml);
$xpath = new \DOMXPath($dom);
$xpath->registerNamespace('s', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');

$strings = [];
$count = 0;
foreach ($xpath->query('//s:sst/s:si/s:t') as $t) {
/** @var \DOMElement $t */
$strings[$count] = $t->nodeValue;
$count++;
}

return $strings;
}
}
64 changes: 64 additions & 0 deletions src/Service/Util/StringLocator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php

namespace Excel\Templating\Service\Util;

use Excel\Templating\Service\Util\Sheet as SheetUtil;

/**
* Class StringLocator
*/
class StringLocator
{
/**
* @var SharedStringReader
*/
private $reader;

/**
* @param SharedStringReader $reader
*/
public function __construct(SharedStringReader $reader)
{
$this->reader = $reader;
}

/**
* @param \ZipArchive $zip
* @param string $sheetName
* @return array
*/
public function getLocation(\ZipArchive $zip, $sheetName)
{
$sharedStrings = $this->reader->read($zip);

$sheets = SheetUtil::convertNamesToXmls($zip, [$sheetName]);
$xmlPath = $sheets[$sheetName];

return $this->makeMap($zip->getFromName($xmlPath), $sharedStrings);
}

/**
* @param string $xml
* @param array $sharedStrings
* @return array
*/
private function makeMap($xml, array $sharedStrings)
{
$dom = new \DOMDocument;
$dom->loadXML($xml);
$xpath = new \DOMXPath($dom);
$xpath->registerNamespace('s', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');

$map = [];
foreach ($xpath->query('//s:worksheet/s:sheetData/s:row/s:c[@t="s"]/s:v') as $stringCellValue) {
$stringId = $stringCellValue->nodeValue;
if (!isset($sharedStrings[$stringId])) {
continue;
}

$map[$stringCellValue->parentNode->getAttribute('r')] = $sharedStrings[$stringId];
}

return $map;
}
}

0 comments on commit e32e03b

Please sign in to comment.