You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

118 lines
3.0 KiB
PHP

<?php
namespace BSR\Lib\db;
use BSR\Lib\Exception\InvalidAttributeException;
/**
* Base class for mapping objects. inherit you database filled objects from here.
*
* @property int $id
*/
abstract class DbMapping
{
protected $attributes;
protected $attributeNames = '';
protected $privateAttributeNames = '';
/**
* @param array $attributes
*/
public function __construct(array $attributes)
{
$this->setAttributes($attributes);
}
/**
* Define a bunch of attribute given by an associative array
* @param array $attributes
*/
public function setAttributes(array $attributes)
{
$this->assertAttributes($attributes);
foreach ($attributes as $key => $value) {
$this->__set($key, $value);
}
}
/**
* Ensure that all keys from attributes are authorized
* @param array $attributes
*/
private function assertAttributes(array $attributes)
{
foreach ($attributes as $key => $value) {
$this->assertAttribute($key);
}
}
/**
* Ensure that name attribute is authorized
* If public_only is false, check against PRIVATE_ATTRIBUTES_NAME too.
* Those one cannot be accessed via setAttributes and other batch methods.
* @param string $name
* @param bool $public_only
* @throws InvalidAttributeException if the attribute is not a valid one
*/
private function assertAttribute($name, $public_only = TRUE)
{
if (strpos($this->attributeNames, $name) === false && ($public_only || strpos($this->privateAttributeNames, $name) === false)) {
throw(new InvalidAttributeException("The attribute $name is invalid"));
}
}
/**
* Get a user attribute or the linked wishes
* @param string $name
* @return mixed
*/
public function __get($name)
{
$sql_safe = FALSE;
if (strpos($name, 'sql_') === 0) {
$name = substr($name, 4);
$sql_safe = TRUE;
}
$this->assertAttribute($name, false);
if (isset($this->attributes[$name])) {
$value = $this->attributes[$name];
if ($sql_safe) {
$value = str_replace("'", "''", $value);
}
return $value;
} else {
return NULL;
}
}
public function to_array() {
return $this->attributes;
}
/**
* Set a user attribute
* @param string $name
* @param mixed $value
*/
public function __set($name, $value)
{
$this->assertAttribute($name, false);
$this->attributes[$name] = $value;
}
/**
* Return all the public attributes in an array;
*/
public function toArray()
{
$result = array();
foreach ($this->attributes as $name => $value) {
if (strpos($this->attributeNames, $name) !== false) {
$result[$name] = $value;
}
}
return $result;
}
}