<?php
namespace ModulesAbstract\ElectronicInvoice;

/**
 * A basic class that extends stdClass, allows usage pretty similar to SimpleXMLExtended
 * @author Lucian Sirbu
 */
class StdClassExtended extends \stdClass
{

	/**
	 * Export to JSON
	 * @param int $jsonOptions
	 * @return string
	 */
	public function asJSON($jsonOptions = 0)
	{
		return json_encode($this, $jsonOptions);
	}

	/**
	 * Cast to string
	 * Used by the SOAPClient class when sending the request
	 * @return string
	 */
	public function __toString()
	{
		if (!get_object_vars($this)) {
			return '';
		}

		return $this->asJSON();
	}

	/**
	 * Add a child
	 * @param string $name
	 * @param mixed $value
	 * @return static
	 */
	public function &add(string $name, mixed $value = NULL)
	{
		// if the value is null, create a new instance of the class
		if ($value===null) {
			$value = new self();
		}

		// if the property exists, and it is not an array, make it an array
		if (property_exists($this, $name) && !is_array($this->{$name})) {
			$this->{$name} = [ $this->{$name} ];
			$this->{$name}[] = $value;
			return end($this->{$name});
		}
		else {
			$this->{$name} = $value;
			return $this->{$name};
		}
	}

	/**
	 * Get a child
	 * Allows accesses like: $json->get("tagName");
	 *
	 * @param string $name
	 * @return static
	 */
	public function get($name)
	{
		return (property_exists($this, $name) ? $this->{$name} : null);
	}

}
