summaryrefslogtreecommitdiffstats
path: root/src/StyleFixer.php
blob: c091ad42e78ce3a9b6d8af56b03ee76e21770a5b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php

namespace PHPExcelFixer\StyleFixer;

use PHPExcelFixer\StyleFixer\Plugin\Plugin;

/**
 * Class StyleFixer
 * PHPExcelが壊した書式設定を修復(テンプレートからコピー)する
 */
class StyleFixer
{
    const STYLES_XML_PATH = 'xl/styles.xml';

    /**
     * @var Plugin[]
     */
    private $plugins;

    public function __construct(array $plugins = null)
    {
        $this->plugins = $plugins;
    }
    
    /**
     * @param string $outputPath
     * @param string $templatePath
     */
    public function execute($outputPath, $templatePath)
    {
        $output = $this->openFile($outputPath);
        $template = $this->openFile($templatePath);

        // スタイル定義を修復
        $this->fixStyles($output, $template);
        $output->close();

        // 個別のシートを修復
        if (null !== $this->plugins) {
            foreach ($this->plugins as $fixer) {

                $output = $this->openFile($outputPath);

                $fixer->execute($output, $template);

                $output->close();
            }
        }

        $template->close();
    }

    /**
     * @param string $path
     * @return \ZipArchive
     */
    protected function openFile($path)
    {
        $zip = new \ZipArchive;
        $zip->open($path);
        
        return $zip;
    }

    /**
     * xl/styles.xml全体を修復(テンプレートからコピー)する
     *
     * @param \ZipArchive $output
     * @param \ZipArchive $template
     */
    private function fixStyles(\ZipArchive $output, \ZipArchive $template)
    {
        $srcStylesXml = $template->getFromName(self::STYLES_XML_PATH);

        $output->addFromString(self::STYLES_XML_PATH, $srcStylesXml);
    }
}