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 23, 2014
1 parent d4f9b40 commit b9a4dae
Show file tree
Hide file tree
Showing 2 changed files with 91 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 = 1;

This comment has been minimized.

Copy link
@77web

77web Sep 24, 2014

Author Owner

$count must start from 0(not 1)

foreach ($xpath->query('//s:ssi/s:si/s:t') as $t) {

This comment has been minimized.

Copy link
@77web

77web Sep 24, 2014

Author Owner

s/ssi/sst/

/** @var \DOMElement $t */
$strings[$count] = $t->nodeValue;
$count++;
}

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

namespace Excel\Templating\Service\Util;

/**
* 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([$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) {

This comment has been minimized.

Copy link
@77web

77web Sep 24, 2014

Author Owner

@t="s"

$stringId = $stringCellValue->nodeValue;
if (!isset($sharedStrings[$stringId])) {
continue;
}

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

return $map;
}
}

0 comments on commit b9a4dae

Please sign in to comment.