| 1 |
<?php |
| 2 |
|
| 3 |
namespace TablePress\PhpOffice\PhpSpreadsheet\Worksheet\Sparkline; |
| 4 |
|
| 5 |
use TablePress\PhpOffice\PhpSpreadsheet\Cell\CellAddress; |
| 6 |
use TablePress\PhpOffice\PhpSpreadsheet\Cell\Coordinate; |
| 7 |
use TablePress\PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; |
| 8 |
use Stringable; |
| 9 |
|
| 10 |
/** |
| 11 |
* A single sparkline: a miniature chart drawn inside one cell. |
| 12 |
* |
| 13 |
* In OOXML this is the `x14:sparkline` element, holding the source data range |
| 14 |
* (`xm:f`) and the cell it is drawn in (`xm:sqref`). |
| 15 |
*/ |
| 16 |
class Sparkline |
| 17 |
{ |
| 18 |
/** |
| 19 |
* The cell the sparkline is drawn in, e.g. `G2`. Stored uppercased and |
| 20 |
* without any `$` absolute-reference markers. |
| 21 |
*/ |
| 22 |
private string $location = ''; |
| 23 |
/** |
| 24 |
* The range supplying the data plotted by the sparkline, e.g. `Sheet1!B2:F2` |
| 25 |
* or `B2:F2`. |
| 26 |
*/ |
| 27 |
private string $dataRange = ''; |
| 28 |
/** |
| 29 |
* @param CellAddress|string $location the cell the sparkline is drawn in (e.g. 'G2') |
| 30 |
* @param string $dataRange the range supplying the plotted data (e.g. 'B2:F2') |
| 31 |
*/ |
| 32 |
public function __construct($location = '', string $dataRange = '') |
| 33 |
{ |
| 34 |
if ($location !== '') { |
| 35 |
$this->setLocation($location); |
| 36 |
} |
| 37 |
$this->setDataRange($dataRange); |
| 38 |
} |
| 39 |
public function getLocation(): string |
| 40 |
{ |
| 41 |
return $this->location; |
| 42 |
} |
| 43 |
/** |
| 44 |
* Set the cell the sparkline is drawn in. Must be a single cell, not a range. |
| 45 |
* @param \TablePress\PhpOffice\PhpSpreadsheet\Cell\CellAddress|string $location |
| 46 |
*/ |
| 47 |
public function setLocation($location): self |
| 48 |
{ |
| 49 |
$location = (string) $location; |
| 50 |
if (str_contains($location, ':')) { |
| 51 |
throw new PhpSpreadsheetException('Sparkline location must be a single cell, not a range'); |
| 52 |
} |
| 53 |
// Normalise: strip absolute markers and any sheet qualifier. |
| 54 |
$location = str_replace('$', '', $location); |
| 55 |
if (str_contains($location, '!')) { |
| 56 |
$location = (string) substr($location, strrpos($location, '!') + 1); |
| 57 |
} |
| 58 |
// Validate by attempting to resolve the coordinate. |
| 59 |
Coordinate::indexesFromString($location); |
| 60 |
$this->location = strtoupper($location); |
| 61 |
|
| 62 |
return $this; |
| 63 |
} |
| 64 |
public function getDataRange(): string |
| 65 |
{ |
| 66 |
return $this->dataRange; |
| 67 |
} |
| 68 |
public function setDataRange(string $dataRange): self |
| 69 |
{ |
| 70 |
$this->dataRange = $dataRange; |
| 71 |
|
| 72 |
return $this; |
| 73 |
} |
| 74 |
public function __toString(): string |
| 75 |
{ |
| 76 |
return $this->location; |
| 77 |
} |
| 78 |
} |
| 79 |
|