Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Jonas Raoni Soares Silva http://www.jsfromhell.com

« Newer Snippets
Older Snippets »
Showing 1-8 of 8 total  RSS 

Replace working as PHP str_replace //JavaScript Function

Useless JavaScript implementation of the php function str_replace.

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com

function replace(f, r, s){
	var ra = r instanceof Array, sa = s instanceof Array, l = (f = [].concat(f)).length, r = [].concat(r), i = (s = [].concat(s)).length;
	while(j = 0, i--)
		while(s[i] = s[i].split(f[j]).join(ra ? r[j] || "" : r[0]), ++j < l);
	return sa ? s : s[0];
}

Output JavaScript variables from PHP

Class with useful static methods for outputting PHP values into JavaScript format.

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com

class JS{
	//generic and maybe not the desired results xD
	function value($o){
		if($o === null)
			return 'null';
		$t = strtolower(gettype($o));
		if($t == 'string' && is_numeric($o) && ($o[0] || strlen($o) == 1) || in_array($t, array('double', 'integer')))
			$t = 'number';
		elseif($t == 'string' && preg_match('@^\d{4}(?:-\d{1,2}){1,2}(?: (?:\d{1,2}:){2}\d{1,2})?$@', $o)) //strtotime works also with "strange" values strtotime('x')
			$t = 'date';
		elseif($t == 'array' && ($c = count($k = array_keys($o))) && $k !== range(0, $c - 1))
			$t = 'object';
		elseif(!in_array($t, array('boolean', 'string', 'array', 'object')))
			$t = 'string';
		$t = 'from' . $t;
		return self::$t($o);
	}
	function fromNumber($o){
		return +$o . '';
	}
	function fromObject($o){
		$r = array();
		foreach($o as $n => $v)
			$r[] = self::fromString($n) . ':' . self::value($v);
		return '{' . implode(',', $r) . '}';
	}
	function fromBoolean($o){
		return $o ? 'true' : 'false';
	}
	//$q = should quote? 
	//$c = char that will be used to quote
	function fromString($o, $q = true, $c = '"'){
		return ($p = $q ? $c : '') . preg_replace('/\r\n|\n\r|\r/', '\n', str_replace($c, '\\' . $c, str_replace('\\', '\\\\', $o))) . $p;
	}
	function fromArray($o){
		$s = '';
		foreach($o as $v)
			$s .= ($s ? ',' : '') . self::value($v);
		return '[' . $s . ']';
	}
	function fromDate($o){
		(is_numeric($o) && $o = +$o) || ($o = strtotime($o)) > 0 || ($o = mktime());
		$o = explode(',', date('Y,n,j,G,i,s', $o));
		foreach($o as $i => $v)
			$o[$i] = +$v;
		return 'new Date(' . implode(',', $o)  . ')';
	}
}


Example

$o = new stdClass;
$o->abc = 123;
echo implode("\n<br />", array(
	JS::value('1984-07-22 11:30:12'),
	JS::value('Test'),
	JS::value(1234),
	JS::value(true),
	JS::value(array(1,2,3)),
	JS::value(array('lala' => 'x')),
	JS::value($o)
));

CSV Parser / Writer for PHP

CSV Parser / Writer

Example A:

//cell separator, row separator, value enclosure
$csv = new CSV(';', "\r\n", '"');

//parse the string content
$csv->setContent(file_get_contents('data.csv'));

//returns an array with the CSV data
print_r($csv->getArray());



Exemple B:

$csv = new CSV(';', "\r\n", '"');
//sets up the content through an array
$csv->setArray(
	array(
		array('col"una1', "colu\r\nna2"),
		array('col;una3', 'coluna4')
	)
);
//retorns string with the CSV representation
print $csv->getContent();



<?php
//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com
class CSV{
	var $cellDelimiter;
	var $valueEnclosure;
	var $rowDelimiter;

	function CSV($cellDelimiter, $rowDelimiter, $valueEnclosure){
		$this->cellDelimiter = $cellDelimiter;
		$this->valueEnclosure = $valueEnclosure;
		$this->rowDelimiter = $rowDelimiter;
		$this->o = array();
	}
	function getArray(){
		return $this->o;
	}
	function setArray($o){
		$this->o = $o;
	}
	function getContent(){
		if(!(($bl = strlen($b = $this->rowDelimiter)) && ($dl = strlen($d = $this->cellDelimiter)) && ($ql = strlen($q = $this->valueEnclosure))))
			return '';
		for($o = $this->o, $i = -1; ++$i < count($o);){
			for($e = 0, $j = -1; ++$j < count($o[$i]);)
				(($e = strpos($o[$i][$j], $q) !== false) || strpos($o[$i][$j], $b) !== false || strpos($o[$i][$j], $d) !== false)
				&& $o[$i][$j] = $q . ($e ? str_replace($q, $q . $q, $o[$i][$j]) : $o[$i][$j]) . $q;
			$o[$i] = implode($d, $o[$i]);
		}
		return implode($b, $o);
	}
	function setContent($s){
		$this->o = array();
		if(!strlen($s))
			return true;
		if(!(($bl = strlen($b = $this->rowDelimiter)) && ($dl = strlen($d = $this->cellDelimiter)) && ($ql = strlen($q = $this->valueEnclosure))))
			return false;
		for($o = array(array('')), $this->o = &$o, $e = $r = $c = 0, $i = -1, $l = strlen($s); ++$i < $l;){
			if(!$e && substr($s, $i, $bl) == $b){
				$o[++$r][$c = 0] = '';
				$i += $bl - 1;
			}
			elseif(substr($s, $i, $ql) == $q){
				$e ? (substr($s, $i + $ql, $ql) == $q ?
				$o[$r][$c] .= substr($s, $i += $ql, $ql) : $e = 0)
				: (strlen($o[$r][$c]) == 0 ? $e = 1 : $o[$r][$c] .= substr($s, $i, $ql));
				$i += $ql - 1;
			}
			elseif(!$e && substr($s, $i, $dl) == $d){
				$o[$r][++$c] = '';
				$i += $dl - 1;
			}
			else
				$o[$r][$c] .= $s[$i];
		}
		return true;
	}
}
?>

ProbabilityRandom //PHP Class


Class to return items based on their probability.

Updated version can be found here


usage
$prExample = new ProbabilityRandom;

$prExample->add( 'I have more chances than everybody :]', 30 );
$prExample->add( 'I have good chances', 10 );
$prExample->add( 'I\'m difficult to appear...', 1 );

for( $x=10; $x--; print $prExample->get() . '<br />' );


//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com
class ProbabilityRandom {
	#private vars
	var
		$data = array(),
		$universe = 0;

	#add an item to the list and defines its probability of being chosen
	function add( $data, $probability ){
		$this->data[ $x = sizeof( $this->data ) ] = new stdClass;
		$this->data[ $x ]->value = $data;
		$this->universe += $this->data[ $x ]->probability = abs( $probability );
	}

	#remove an item from the list
	function remove( $index ){
		if( $index > -1 && $index < sizeof( $this->data ) ) {
			$item = array_splice( $this->data, $index, 1 );
			$this->universe -= $item->probability;
		}
	}

	#clears the class
	function clear(){
		$this->universe = sizeof( $this->data = array() );
	}

	#return a randomized item from the list
	function get(){
		if( !$this->universe )
			return null;
		$x = round( mt_rand( 0, $this->universe ) );
		$max = $i = 0;
		do
			$max += $this->data[ $i++ ]->probability;
		while( $x > $max );
		return $this->data[ $i-1 ]->value;
	}
}

Exception class fix for php 4 //PHP Class

if(!class_exists('Exception')){
	class Exception{
		var $_message = '';
		var $_code = 0;
		var $_line = 0;
		var $_file = '';
		var $_trace = null;

		function Exception($message = 'Unknown exception', $code = 0){
			$this->_message = $message;
			$this->_code = $code;
			$this->_trace = debug_backtrace();
			$x = array_shift($this->_trace);
			$this->_file = $x['file'];
			$this->_line = $x['line'];
		}

		function __construct($message = 'Unknown exception', $code = 0){
			$this->Exception($message, $code);
		}

		function getMessage(){
			return $this->_message;
		}
		function getCode(){
			return $this->_code;
		}
		function getFile(){
			return $this->_file;
		}
		function getLine(){
			return $this->_line;
		}
		function getTrace(){
			return $this->_trace;
		}
		function getTraceAsString(){
			$s = '';
			foreach($this->_trace as $i=>$item){
				foreach($item['args'] as $j=>$arg)
					$item['args'][$j] = print_r($arg, true);
				$s .= "#$i " . (isset($item['class']) ? $item['class'] . $item['type'] : '') . $item['function']
				. '(' . implode(', ', $item['args']) . ") at [$item[file]:$item[line]]\n";
			}
			return $s;
		}
		function printStackTace(){
			echo $this->getTraceAsString();
		}
		function toString(){
			return $this->getMessage();
		}
		function __toString(){
			return $this->toString();
		}
	}
}

Response::redirect //PHP Function

class Response{
	function redirect($url){
		exit(header('Location: ' . $url));
	}
}

removeDir //PHP Function

Removes a folder, including its subfolders and files in a efficient way without recursion, returns Boolean.

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com

function removeFolder($dir){
	if(!is_dir($dir))
		return false;
	for($s = DIRECTORY_SEPARATOR, $stack = array($dir), $emptyDirs = array($dir); $dir = array_pop($stack);){
		if(!($handle = @dir($dir)))
			continue;
		while(false !== $item = $handle->read())
			$item != '.' && $item != '..' && (is_dir($path = $handle->path . $s . $item) ?
			array_push($stack, $path) && array_push($emptyDirs, $path) : unlink($path));
		$handle->close();
	}
	for($i = count($emptyDirs); $i--; rmdir($emptyDirs[$i]));
}

Request Adapter //PHP Class

A simple class providing a cute adapter for get/post requests.

Usage
$r = &new Request(POST_METHOD | GET_METHOD);
#$r = &new Request(POST_METHOD); //just post
#$r = &new Request(GET_METHOD); //just get =b

if($r->has('name'))
  echo $r->get('name'), $r->name;

echo $r->get('year', '2006');

if($r->isPosted())
  echo 'This was a post =b';


if($r->isFile('file'))
  if($r->file->isUploaded()){
    echo 'The file was uploaded';
    if($r->file->hasError())
      echo 'And there was an error when uploading';
    else{
      echo 'Moving ' . $r->file->path;
      $r->file->save('uploads/' . $r->file->name)
    }
  }




<?php
//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com

define('GET_METHOD', 1);
define('POST_METHOD', 2);

class PostedFile{
	var $file, $name, $type, $size, $path, $error;

	function PostedFile(&$f){
		$this->file = &$f;
		$this->name = $f['name'];
		$this->type = $f['type'];
		$this->size = $f['size'];
		$this->path = $f['tmp_name'];
		$this->error = $f['error'];
	}

	function hasError(){
		return $this->isUploaded() && $this->error != UPLOAD_ERR_OK;
	}

	function isUploaded(){
		return $this->error != UPLOAD_ERR_NO_FILE;
	}

	function save($path){
		return @move_uploaded_file($this->path, $path);
	}
}

class Request{
	function &Request($method){
		if(GET_METHOD & $method)
			foreach($_GET as $n=>$v)
				$this->$n = $v;
		if(POST_METHOD & $method){
			foreach($_POST as $n=>$v)
				$this->$n = $v;
			foreach($_FILES as $n=>$v)
				$this->$n = &new PostedFile($v);
		}
		return $this;
	}

	function isFile($name){
		return is_a($this->get($name), 'PostedFile');
	}

	function has($name){
		if(is_array($name)){
			foreach($name as $n)
				if(!isset($this->$n))
					return false;
			return true;
		}
		else
			return isset($this->$name);
	}

	function get($name, $default = null){
		if($this->has($name))
			return $this->$name;
		else
			return $default;
	}

	function isPosted(){
		return $_SERVER['REQUEST_METHOD'] == 'POST' && isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'];
	}
}
?>
« Newer Snippets
Older Snippets »
Showing 1-8 of 8 total  RSS