|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Remorhaz\JSONPointer\Evaluator; |
| 4 | + |
| 5 | +use Remorhaz\JSONPointer\Data\SelectableWriterInterface; |
| 6 | +use Remorhaz\JSONPointer\Locator\Locator; |
| 7 | +use Remorhaz\JSONPointer\Locator\Reference; |
| 8 | + |
| 9 | +class OperationDelete extends Operation |
| 10 | +{ |
| 11 | + |
| 12 | + protected $writer; |
| 13 | + |
| 14 | + |
| 15 | + public function __construct(Locator $locator, SelectableWriterInterface $writer) |
| 16 | + { |
| 17 | + parent::__construct($locator); |
| 18 | + $this->writer = $writer; |
| 19 | + } |
| 20 | + |
| 21 | + |
| 22 | + public function perform() |
| 23 | + { |
| 24 | + if (empty($this->locator->getReferenceList())) { |
| 25 | + throw new EvaluatorException("Data root can't be deleted"); |
| 26 | + } |
| 27 | + parent::perform(); |
| 28 | + if ($this->writer->isIndexSelected()) { |
| 29 | + $this->writer->removeElement(); |
| 30 | + } elseif ($this->writer->isPropertySelected()) { |
| 31 | + $this->writer->removeProperty(); |
| 32 | + } else { |
| 33 | + throw new LogicException("Failed to remove data at '{$this->locator->getText()}'"); |
| 34 | + } |
| 35 | + return $this; |
| 36 | + } |
| 37 | + |
| 38 | + |
| 39 | + protected function applyReference(Reference $reference) |
| 40 | + { |
| 41 | + if ($this->writer->isArraySelected()) { |
| 42 | + if ($reference->getType() != $reference::TYPE_INDEX) { |
| 43 | + throw new EvaluatorException( |
| 44 | + "Invalid index '{$reference->getKey()}' at '{$reference->getPath()}''" |
| 45 | + ); |
| 46 | + } |
| 47 | + $index = (int) $reference->getKey(); |
| 48 | + $this->writer->selectIndex($index); |
| 49 | + if (!$this->writer->hasData()) { |
| 50 | + throw new EvaluatorException("No element #{$index} at '{$reference->getPath()}'"); |
| 51 | + } |
| 52 | + } elseif ($this->writer->isObjectSelected()) { |
| 53 | + $property = (string) $reference->getKey(); |
| 54 | + $this->writer->selectProperty($property); |
| 55 | + if (!$this->writer->hasData()) { |
| 56 | + throw new EvaluatorException("No property '{$property}' at '{$reference->getPath()}'"); |
| 57 | + } |
| 58 | + } else { |
| 59 | + throw new EvaluatorException("Scalar data at '{$reference->getPath()}'"); |
| 60 | + } |
| 61 | + return $this; |
| 62 | + } |
| 63 | +} |
0 commit comments