<?php

namespace Wb4Wp\Models;

use Iterator;
use stdClass;

/**
 * Class Struct
 * A safe array or stdClass access wrapper
 *
 * @package Wb4Wp\Models
 */
class Struct implements Iterator {

	/**
	 * @var array
	 */
	private $source;

	/**
	 * @param stdClass|array $source
	 */
	public function __construct( $source ) {
		if ( $source instanceof stdClass ) {
			$this->source = get_object_vars( $source );
		} else {
			$this->source = $source;
		}
	}

	public function get( $key, $default = null ) {
		$value = &$this->source[ $key ];

		return empty( $value ) ? $default : $value;
	}

	/**
	 * @param $key
	 * @param $value
	 */
	public function set( $key, $value ) {
		$this->source[ $key ] = $value;
	}

	public function keys() {
		$values = $this->source;
		if ( $values instanceof stdClass ) {
			$values = get_object_vars( $values );
		}

		return array_keys( $values );
	}

	public function rewind() {
		reset( $this->source );
		$this->valid = true;
	}

	public function current() {
		return current( $this->source );
	}

	public function key() {
		return key( $this->source );
	}

	public function next() {
		next( $this->source );
	}

	public function valid() {
		return key( $this->source ) !== null;
	}
}
