Skip to content

Instantly share code, notes, and snippets.

@dg
Created June 11, 2018 08:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dg/7739c744c449948abf8e0023502d3d99 to your computer and use it in GitHub Desktop.
Save dg/7739c744c449948abf8e0023502d3d99 to your computer and use it in GitHub Desktop.
Nette\StrictObject, simplified alternative for Nette\SmartObject (compatible with nette/utils 2.4)
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette;
use Nette\Utils\ObjectHelpers;
/**
* Strict class for better experience.
* - 'did you mean' hints
* - access to undeclared members throws exceptions
*/
trait StrictObject
{
/**
* @return mixed
* @throws MemberAccessException
*/
public function __call($name, $args)
{
ObjectHelpers::strictCall(get_class($this), $name);
}
/**
* @return void
* @throws MemberAccessException
*/
public static function __callStatic($name, $args)
{
ObjectHelpers::strictStaticCall(get_called_class(), $name);
}
/**
* @return mixed property value
* @throws MemberAccessException if the property is not defined.
*/
public function & __get($name)
{
ObjectHelpers::strictGet(get_class($this), $name);
}
/**
* @return void
* @throws MemberAccessException if the property is not defined or is read-only
*/
public function __set($name, $value)
{
$class = get_class($this);
if (ObjectHelpers::hasProperty($class, $name)) { // unsetted property
$this->$name = $value;
} else {
ObjectHelpers::strictSet($class, $name);
}
}
/**
* @return void
* @throws MemberAccessException
*/
public function __unset($name)
{
$class = get_class($this);
if (!ObjectHelpers::hasProperty($class, $name)) {
throw new MemberAccessException("Cannot unset the property $class::\$$name.");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment