destructr/src/DSO.php

121 lines
3 KiB
PHP
Raw Normal View History

2018-08-17 17:32:10 +00:00
<?php
/* Destructr | https://github.com/jobyone/destructr | MIT License */
2018-08-17 22:32:26 +00:00
namespace Destructr;
2018-08-17 17:32:10 +00:00
2018-08-18 15:45:55 +00:00
use \Flatrr\FlatArray;
2018-08-17 17:32:10 +00:00
/**
* Interface for DeStructured Objects (DSOs). These are the class that is
2018-08-17 17:32:10 +00:00
* actually used for storing and retrieving partially-structured data from the
* database.
*/
class DSO extends FlatArray implements DSOInterface
{
protected $factory;
protected $changes;
protected $removals;
public function __construct(array $data = null, Factory $factory = null)
2018-08-17 17:32:10 +00:00
{
$this->resetChanges();
parent::__construct($data);
$this->factory($factory);
$this->resetChanges();
}
public function hook_create()
{
//does nothing
}
public function hook_update()
{
//does nothing
}
public function delete(bool $permanent = false): bool
2018-08-17 17:32:10 +00:00
{
return $this->factory->delete($this, $permanent);
}
public function undelete(): bool
2018-08-17 17:32:10 +00:00
{
return $this->factory->undelete($this);
}
public function insert(): bool
2018-08-17 17:32:10 +00:00
{
return $this->factory()->insert($this);
}
public function update(bool $sneaky = false): bool
2018-08-17 17:32:10 +00:00
{
return $this->factory()->update($this);
}
public function resetChanges()
{
$this->changes = new FlatArray();
$this->removals = new FlatArray();
}
public function changes(): array
2018-08-17 17:32:10 +00:00
{
return $this->changes->get();
}
public function removals(): array
2018-08-17 17:32:10 +00:00
{
return $this->removals->get();
}
public function set(?string $name, $value, $force = false)
2018-08-17 17:32:10 +00:00
{
$name = strtolower($name);
if ($this->get($name) === $value) {
2018-08-17 17:32:10 +00:00
return;
}
if (is_array($value)) {
//check for what's being removed
if (is_array($this->get($name))) {
foreach ($this->get($name) as $k => $v) {
if (!isset($value[$k])) {
if ($name) {
$k = $name . '.' . $k;
2018-08-17 17:32:10 +00:00
}
$this->unset($k);
}
}
} else {
parent::set($name, []);
2018-08-17 17:32:10 +00:00
}
//recursively set individual values so we can track them
foreach ($value as $k => $v) {
if ($name) {
$k = $name . '.' . $k;
2018-08-17 17:32:10 +00:00
}
$this->set($k, $v, $force);
}
} else {
$this->changes->set($name, $value);
unset($this->removals[$name]);
parent::set($name, $value);
}
}
function unset(?string $name) {
2018-08-17 17:32:10 +00:00
if (isset($this[$name])) {
$this->removals->set($name, $this->get($name));
unset($this->changes[$name]);
parent::unset($name);
}
}
public function factory(Factory $factory = null): ?Factory
2018-08-17 17:32:10 +00:00
{
if ($factory) {
$this->factory = $factory;
}
return $this->factory;
}
}