<?php
/*
* This file is part of the overtrue/wechat.
*
* (c) overtrue <i@overtrue.me>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
/**
* Attributes.php.
*
* @author overtrue <i@overtrue.me>
* @copyright 2015 overtrue <i@overtrue.me>
*
* @see https://github.com/overtrue
* @see http://overtrue.me
*/
namespace EasyWeChat\Support;
use EasyWeChat\Core\Exceptions\InvalidArgumentException;
abstract class Attribute extends Collection
{
protected $aliases = [];
protected $snakeable = true;
protected $requirements = [];
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
}
public function setAttribute($attribute, $value)
{
$this->set($attribute, $value);
return $this;
}
public function getAttribute($attribute, $default)
{
return $this->get($attribute, $default);
}
public function with($attribute, $value)
{
$this->snakeable && $attribute = Str::snake($attribute);
if (!$this->validate($attribute, $value)) {
throw new InvalidArgumentException("Invalid attribute '{$attribute}'.");
}
$this->set($attribute, $value);
return $this;
}
protected function validate($attribute, $value)
{
return true;
}
public function set($attribute, $value = null)
{
parent::set($this->getRealKey($attribute), $value);
}
public function get($attribute, $default = null)
{
return parent::get($this->getRealKey($attribute), $default);
}
public function __call($method, $args)
{
if (0 === stripos($method, 'with')) {
$method = substr($method, 4);
}
return $this->with($method, array_shift($args));
}
public function __set($property, $value)
{
return $this->with($property, $value);
}
public function __isset($key)
{
return parent::__isset($this->getRealKey($key));
}
protected function getRealKey($key)
{
if ($alias = array_search($key, $this->aliases, true)) {
$key = $alias;
}
return $key;
}
protected function checkRequiredAttributes()
{
foreach ($this->requirements as $attribute) {
if (!isset($this->$attribute)) {
throw new InvalidArgumentException(" '{$attribute}' cannot be empty.");
}
}
}
public function all()
{
$this->checkRequiredAttributes();
return parent::all();
}
}