jQuery Written in PHP

By: Christian Blanquera

I thought it would have been cool to write jQuery but in the PHP library. What didn't make sense was translating jQuery's JavaScript to PHP. I created a quick solution using magic methods.

The Magical Class
class JS {
	protected $_script = array();
	
	public function __toString() {
		$output = NULL;
		foreach($this->_script as $script) {
			if(is_null($output) || substr($output, -1, 1) == ';') {
				$output .= $script;
			} else {
				$output .= '.'.$script;
			}
		}
		return $output;
	}
	
	public function __call($name, $args) {
		//for each argument
		foreach($args as $i => $arg) {
			//encode the argument in javascript
			$args[$i] = $this->___encode($arg);
		}
		
		//add to script
		$this->_script[] = $name.'('.implode(',', $args).')';
		
		return $this;
	}
	
	public function __get($name) {
		//add to script
		$this->_script[] = $name;
		
		return $this;
	}
	
	public function __set($name, $value) {
		//add to script
		$this->_script[] = $name.'='.$this->___encode($value).';';
		
		return $this;
	}
	
	protected function ___encode($value) {
		$type = Eden_Tool::i()->type($value);
		switch($type) {
			case 'array':
			case 'object':
				$jsonType = substr(json_encode($value), 0, 1);
				if($jsonType == '[') {
					$value = $this->____encodeArray($value);
				} else {
					$value = $this->____encodeObject($value);
				}
				break;
			default:
				$value = json_encode($value);
				break;
		}
		
		return $value;
	}
	
	protected function ____encodeObject($object) {
		$encoded = array();
		$class = __CLASS__;
		foreach($object as $key => $value) {
			$key = json_encode($key);
			if(!($value instanceof $class)) {
				$value = $this->___encode($value);
			}
			
			$encoded[] = $key.':'.$value;
		}
		
		return '{'.implode(',', $encoded).'}';
	}
	
	protected function ____encodeArray($array) {
		$encoded = array();
		$class = __CLASS__;
		foreach($array as $value) {
			if(!($value instanceof $class)) {
				$value = $this->___encode($value);
			}
			
			$encoded[] = $value;
		}
		
		return '['.implode(',', $encoded).']';
	}
}
How to use it
$js = new JS();
echo $js->jQuery('div.page')
	->css('background', 'red')
	->children('p')
	->html('something new');
It would echo something like.
jQuery('div.page').css('background', 'red').children('p').html('something new');