1 <?php 2 3 declare(strict_types=1); 4 5 namespace OpenSpout\Writer\Common\Manager\Style; 6 7 use OpenSpout\Common\Entity\Cell; 8 use OpenSpout\Common\Entity\Style\Style; 9 10 /** 11 * @internal 12 */ 13 abstract class AbstractStyleManager implements StyleManagerInterface 14 { 15 /** @var AbstractStyleRegistry Registry for all used styles */ 16 protected AbstractStyleRegistry $styleRegistry; 17 18 public function __construct(AbstractStyleRegistry $styleRegistry) 19 { 20 $this->styleRegistry = $styleRegistry; 21 } 22 23 /** 24 * Registers the given style as a used style. 25 * Duplicate styles won't be registered more than once. 26 * 27 * @param Style $style The style to be registered 28 * 29 * @return Style the registered style, updated with an internal ID 30 */ 31 final public function registerStyle(Style $style): Style 32 { 33 return $this->styleRegistry->registerStyle($style); 34 } 35 36 /** 37 * Apply additional styles if the given row needs it. 38 * Typically, set "wrap text" if a cell contains a new line. 39 * 40 * @return PossiblyUpdatedStyle The eventually updated style 41 */ 42 final public function applyExtraStylesIfNeeded(Cell $cell): PossiblyUpdatedStyle 43 { 44 return $this->applyWrapTextIfCellContainsNewLine($cell); 45 } 46 47 /** 48 * Returns the default style. 49 * 50 * @return Style Default style 51 */ 52 final protected function getDefaultStyle(): Style 53 { 54 // By construction, the default style has ID 0 55 return $this->styleRegistry->getRegisteredStyles()[0]; 56 } 57 58 /** 59 * Set the "wrap text" option if a cell of the given row contains a new line. 60 * 61 * @NOTE: There is a bug on the Mac version of Excel (2011 and below) where new lines 62 * are ignored even when the "wrap text" option is set. This only occurs with 63 * inline strings (shared strings do work fine). 64 * A workaround would be to encode "\n" as "_x000D_" but it does not work 65 * on the Windows version of Excel... 66 * 67 * @param Cell $cell The cell the style should be applied to 68 * 69 * @return PossiblyUpdatedStyle The eventually updated style 70 */ 71 private function applyWrapTextIfCellContainsNewLine(Cell $cell): PossiblyUpdatedStyle 72 { 73 $cellStyle = $cell->getStyle(); 74 75 // if the "wrap text" option is already set, no-op 76 if (!$cellStyle->hasSetWrapText() && $cell instanceof Cell\StringCell && str_contains($cell->getValue(), "\n")) { 77 $cellStyle->setShouldWrapText(); 78 79 return new PossiblyUpdatedStyle($cellStyle, true); 80 } 81 82 return new PossiblyUpdatedStyle($cellStyle, false); 83 } 84 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body