Skip to content

Instantly share code, notes, and snippets.

@nijikokun
Created August 9, 2011 03:51
Show Gist options
  • Save nijikokun/1133368 to your computer and use it in GitHub Desktop.
Save nijikokun/1133368 to your computer and use it in GitHub Desktop.
php.java - Objects ported to PHP for many reasons...

php.java

Java Objects ported to PHP, as well as specific methods / functions.

Why?

Essentially the entire reason is because I can, however there are a lot of reasons behind this.

A few pertain to how PHP doesn't follow any standards regarding function naming, and that is only the tip of the iceberg.

So instead of arguing, I'm simply going to do / prove that it is possible.

Licensing

All code is / must be licensed under the AOL.

For more information

php.java is brought to you by Nijikokun, and inspiration from the Java team, as well as PHP.

<?php
/**
* Commonly needed functions for some Java -> PHP things to function properly.
*
* @author Nijikokun <[email protected]>
* @copyright AOL <http://aol.nexua.org>
* @package Common
* @version 1.0.1
* @since p.j1
*/
/**
* Last index of a string / character starting at the rightmost index.
* Backwards searching, Case-insensitive.
*/
function strbipos($haystack = "", $needle = "", $offset = 0) {
$len = strlen($haystack);
$pos = stripos(strrev($haystack), strrev($needle), $len - $offset - 1);
if($pos === false)
return false;
return $len - strlen($needle) - $pos;
}
/**
* Last index of a string / character starting at the rightmost index.
* Backwards searching, Case-sensitive.
*/
function strbpos($haystack = "", $needle = "", $offset = 0) {
$len = strlen($haystack);
$pos = strpos(strrev($haystack), strrev($needle), $len - $offset - 1);
if($pos === false)
return false;
return $len - strlen($needle) - $pos;
}
/**
* Windows utilizes DST and messes up filemtime. So
* we need to correct the time for that adjustment.
*
* @return adjusted filemtime
*/
function correctmtime($path) {
$time = filemtime($path);
$isDST = (date('I', $time) == 1);
$systemDST = (date('I') == 1);
$adjustment = 0;
if($isDST == false && $systemDST == true)
$adjustment = 3600;
else if($isDST == true && $systemDST == false)
$adjustment = -3600;
else
$adjustment = 0;
return ($time + $adjustment);
}
/**
* PHP has issues reading files > 4GB due to 32b INT
* So we need a function that can correctly read the file
* size at large sizes. Utilizing in-house PHP functions
* fsize was made to do this.
*
*/
function fsize($file) {
$fmod = filesize($file);
if ($fmod < 0)
$fmod += 2.0 * (PHP_INT_MAX + 1);
$i = 0;
$f = fopen($file, "r");
while (strlen(fread($f, 1)) === 1) {
fseek($f, PHP_INT_MAX, SEEK_CUR);
$i++;
}
fclose($f);
if ($i % 2 == 1)
$i--;
return ((float)($i) * (PHP_INT_MAX + 1)) + $fmod;
}
/**
* Format sizes based on bytes.
*
* @return human readable size.
*/
function formatBytes($b, $precision = null, $spacer = ' ') {
$units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
$c = 0;
if(!$precision && $precision !== 0) {
foreach($units as $k => $u)
if(($b / pow(1024, $k)) >= 1) {
$r["bytes"] = $b / pow(1024, $k);
$r["units"] = $u;
$c++;
}
return number_format($r["bytes"], 2) . $spacer . $r["units"];
}
return number_format($b / pow(1024,$p)) . $spacer . $units[$p];
}
<?php
// Include our sources, I may implement (Importing)
include('Common.java.php');
include('System.java.php');
include('String.java.php');
include('File.java.php');
// Initialize a String
$hello = new String("World");
// Show it lowercase
out::prntln("Lowercase of '{$hello->toString()}': " . $hello->toLowerCase());
// Show the string's equality without case
out::prntln("EqualsIgnoreCase test against 'world': " . (($hello->equalsIgnoreCase("world")) ? 'true' : 'false'));
// Show the string's containment for "e"
out::prntln("Contains 'e'? " . (($hello->contains("e")) ? 'true' : 'false'));
// Show the last index of o
out::prntln("Last index of 'o': " . ((!$hello->lastIndexOf("o")) ? 'false' : $hello->lastIndexOf("o")));
// New Section
out::prntln();
// Initialize a File
$self = new File("Examples.java.php");
// Check validation.
out::prntln("Does it exist? " . (($self->exists()) ? 'true' : 'false'));
<?php
/**
* Soon to be a port of Java's Abstract File Object implementation.
*
* In PHP System directory path prefixes don't matter so we can skip those here.
*
* A File will be treated as a file, if given a directory it will treat it as such,
* unlike java's version, as PHP is more finicky about how the file-system is treated.
*
* @author Nijikokun <[email protected]>
* @copyright AOL <http://aol.nexua.org>
* @package File
* @version 1.0.2
* @since p.j1
*/
class File {
/**
* This abstract pathname's normalized pathname string.
*/
private $path;
const seperatorChar = '/';
/**
* Initializes a new File Object from parent and child or just parent.
*/
public function __construct($parent = "", $child = "") {
$parent = new String($parent);
$child = new String($child);
if($parent->isEmpty())
throw new Exception("File path cannot be empty.");
if($parent->isEmpty() && $child->isEmpty())
throw new Exception("File path cannot be empty.");
if($parent->substring(-1) == $this::seperatorChar && !$child->isEmpty())
$this->path = $parent . $child;
else if(!$child->isEmpty())
$this->path = $parent . $this::seperatorChar . $child;
else
$this->path = $parent;
}
/**
* Returns the current path name.
*
* @since 1.0.1
*/
public function getName() {
return basename($this->path);
}
/**
* Returns the pathname string of this abstract pathname's parent.
*
* @return The pathname string of the parent directory or file.
* @since 1.0.2
*/
public function getParent() {
return dirname($this->path);
}
/**
* Returns path's parent as a File instead of String.
*
* @return File or Null
* @since 1.0.2
*/
public function getParentFile() {
$parent = $this->getParent();
if ($parent == "" || $parent == $this->path)
return null;
return new File($parent);
}
/**
* Determines if the current path we are using is the Absolute path.
* @since 1.0.2
*/
public function isAbsolute() {
return (realpath($this->path) == $this->path);
}
/**
* Returns the absolute form of this abstract pathname.
*
* @return String
* @since 1.0.2
*/
public function getAbsolutePath() {
return realpath($this->path);
}
/**
* Returns the absolute form of the path as a File.
*
* @return File
* @since 1.0.2
*/
public function getAbsoluteFile() {
return new File($this->getAbsolutePath());
}
/**
* Verifies the existance of our current path.
* Path or Directory, it will verify it either way.
*
* @since 1.0.1
*/
public function exists() {
return file_exists($this->path);
}
/**
* Tells whether the current path is capable of being
* written to.
*
* @since 1.0.1
* @change Changed from #isWritable to #canWrite
*/
public function canWrite() {
return is_writable($this->path);
}
/**
* Tells whether we can access our current path data.
*
* @since 1.0.1
* @change Changed from #isReadable to #canRead
*/
public function canRead() {
return is_readable($this->path);
}
/**
* Tells whether the current path is capable of being
* executed by php.
*
* @since 1.0.1
*/
public function isExecutable() {
return is_executable($this->path);
}
/**
* Tells whether the current path is a file.
*
* @since 1.0.1
*/
public function isFile() {
return is_file($this->path);
}
/**
* Tells whether the current path is a directory.
*
* @since 1.0.1
*/
public function isDirectory() {
return is_dir($this->path);
}
/**
* Determines if a file is hidden based on the prefix being a period.
* Windows does hidden files differently, and would require DOS actions
* to perform correctly so those have been left out.
*
* @since 1.0.1
*/
public function isHidden() {
return $this->path->startsWith('.');
}
/**
* Returns the time that the file denoted by this abstract pathname was
* last modified.
*
* @return A <code>long</code> value representing the time the file was
* last modified, measured in milliseconds since the epoch
* (00:00:00 GMT, January 1, 1970), or <code>0L</code> if the
* file does not exist or if an I/O error occurs
* @since 1.0.2
*/
public function lastModified() {
if ($this->exists())
return correctmtime($this->path);
throw new Exception('File ' . $this->getName() . ' does not exist.');
}
/**
* Return file size if the file exists.
* @since 1.0.2
*/
public function length() {
if($this->exists())
return fsize($this->path);
throw new Exception('File ' . $this->getName() . ' does not exist.');
}
/**
* Creates file if and only if the file does not already exist.
*
* @return true on file creation, false otherwise.
* @since 1.0.2
*/
public function createNewFile() {
$created = null;
if(!$this->exists() && $this->isFile())
$created = fclose(fopen($filename,"x"));
if($created != null)
return true;
return false;
}
/**
* Delete the current path. If the current path is a directory
* only delete if the directory is empty.
*
* @return true on deletion, false otherwise.
* @since 1.0.2
*/
public function delete() {
if(!$this->exists())
return true;
if($this->isDirectory && $this->isEmptyDir())
unlink($this->path);
else
return false;
if($this->isFile)
unlink($this->path);
return true;
}
private function isEmptyDir() {
return (($files = @scandir($this->path)) && count($files) <= 2);
}
}
<?php
/**
* The <code>String</code> class represents strings in a semantic way like in Java. All
* string methods are given the correct namespace and use a single method of naming.
*
* PHP is fond for it's inability to follow a single internal function/method naming scheme.
* This is to help reduce the clutter.
*
* @author Nijikokun <[email protected]>
* @copyright AOL <http://aol.nexua.org>
* @package String
* @version 1.0.5
* @since p.j1
*/
class String {
private $str;
private $length;
public function __construct($str = "") {
$this->str = $str;
$this->length = strlen($str);
}
/**
* Verifies the emptiness of our current String.
*/
public function isEmpty() {
return $this->length == 0 || $this->str == "" || $this->str == null;
}
/**
* Returns our current String length
*/
public function length() {
return $this->length;
}
/**
* Converts an indice to the given character at the point.
*
* @todo Create Char Object.
* @return Char
*/
public function charAt($index) {
if (($index < 0) || ($index >= $this->length))
throw new Exception("Index out of bounds.");
return $this->str[$index];
}
/**
* Converts all characters in the current String
* to their ord counterparts and returns in array form.
*
* @return Array
*/
public function getBytes() {
$bytes = array();
for($i = 0; $i < $this->length; $i++){
$bytes[] = ord($this->str[$i]);
}
return $bytes;
}
/**
* Tells whether the sequence of characters in our current String
* matches the sequence in another.
*
* @param $another String to be checked upon.
* @return Boolean
*/
public function equals($another) {
if ($this->str == $another)
return true;
if ($this->length == strlen($another)) {
for($i = 0; $i < strlen($this->str); $i++)
if ($this->str[$i] != $another[$i])
return false;
return true;
}
return false;
}
/**
* Tells whether the sequence of characters in our current String
* matches the sequence in another without case sensitivity.
*
* @param $another String to be checked upon.
* @return Boolean
*/
public function equalsIgnoreCase($another) {
if ($this->equals($another))
return true;
if ($this->toLowerCase() == strtolower($another))
return true;
if ($this->length == strlen($another)) {
for($i = 0; $i < strlen($this->str); $i++)
if (strtolower($this->str[$i]) != strtolower($another[$i]))
return false;
return true;
}
return false;
}
/**
* Lexigraphically compares two strings and returns the numeric value.
* This is UTF-8/16 Based. Beware of usage.
*
* @todo Create Integer Object
* @param $another String to be checked upon.
* @return Integer
*/
public function compareTo($another) {
$l1 = mb_strlen($this->str);
$l2 = mb_strlen($another);
$i = 0;
while ($i < $l1 && $i < $l2) {
$c1 = mb_convert_encoding(mb_substr($this->str, $i, 1),'utf-16le');
$c1 = ord($c1[0]) + (ord($c1[1]) << 8);
$c2 = mb_convert_encoding(mb_substr($another, $i, 1),'utf-16le');
$c2 = ord($c2[0]) + (ord($c2[1]) << 8);
$res = $c1 - $c2;
if ($res != 0)
return $res;
$i++;
}
return $l1 - $l2;
}
/**
* Converts all characters in the current String to lowercase.
*
* @return string
*/
public function toLowerCase() {
return strtolower($this->str);
}
/**
* Converts all characters in the current String to uppercase.
*
* @since 1.0.1
* @return string
*/
public function toUpperCase() {
return strtoupper($this->str);
}
/**
* Returns a new String containing the character array
* from the given indices.
*
* @param $a Beginning index
* @param $b Ending index
* @return string
* @version 0.2
*/
public function substring($a = "", $b = "") {
if($a == "" && $b == "")
throw new Exception("Invalid start and end.");
if(!is_int($a) && !is_int($b))
throw new Exception("Start and end must be numeric.");
if(is_int($a))
return substr($this->str, $a);
if(is_int($a) && is_int($b))
return substr($this->str, $a, $b);
throw new Exception("Invalid start and end.");
}
/**
* Tells whether or not the current String contains
* a given needle.
*
* @version 0.3
*/
public function contains($needle) {
return strpos($this->str, $needle) !== false;
}
/**
* Tells whether or not the current String begins
* with the string given.
*
* @param $needle String to be compared to.
* @param $case Boolean that toggles case sensitivity.
* @return Boolean
*/
public function startsWith($needle, $case = true) {
if($case)
return (strcmp(substr($this->str, 0, strlen($needle)), $needle) === 0);
return (strcasecmp(substr($this->str, 0, strlen($needle)), $needle) === 0);
}
/**
* Tells whether or not the current String begins
* with the string given.
*
* @param $needle String to be compared to.
* @param $case Boolean that toggles case sensitivity.
* @return Boolean
*/
public function endsWith($needle, $case = true) {
if($case)
return (strcmp(substr($this->str, strlen($this->str) - strlen($needle)), $needle) === 0);
return (strcasecmp(substr($this->str, strlen($this->str) - strlen($needle)), $needle) === 0);
}
/**
* Returns the index within this string of the first occurrence of the
* specified substring, starting at the specified index. If the substring
* is not found, false is returned.
*
* @since 1.0.5
* @param $needle Substring to be searched for.
* @param $starting Starting index, default 0.
* @return False or Position
*/
public function indexOf($needle, $starting = 0, $case = true) {
if($starting != 0)
$pos = ($case) ? strpos($this->str, $needle, $starting) : stripos($this->str, $needle, $starting);
else
$pos = ($case) ? strpos($this->str, $needle) : stripos($this->str, $needle);
if($pos === false)
return false;
return $pos;
}
/**
* Returns the index within this string of the last occurrence of the
* specified substring, starting rightmost at the specified index.
* If the substring is not found, false is returned.
*
* @since 1.0.5
* @param $needle Substring to be searched for.
* @param $starting Starting index, default 0.
* @return False or Position
*/
public function lastIndexOf($needle, $starting = 0, $case = true) {
if($starting != 0)
$pos = ($case) ? strrpos($this->str, $needle, $starting) : strripos($this->str, $needle, $starting);
else
$pos = ($case) ? strrpos($this->str, $needle) : strripos($this->str, $needle);
if($pos === false)
return false;
return $pos;
}
/**
* Concatenates the specified string to the end of this string.
*
* @since 1.0.5
* @param $str the <code>String</code> that is concatenated to the end of this <code>String</code>.
* @return String with the new section concatenated.
*/
public function concat($str) {
return new String($this->str + $str);
}
/**
* Replaces one string with another in the current String.
*
* @since 1.0.5
* @param $old Old character array (String).
* @param $new New character array (String).
*/
public function replace($old, $new) {
return str_replace($this->str, $old, $new);
}
/**
* Converts a string based on the string delimiter into an array of strings, each a substring of the string.
*
* @since 1.0.5
* @param $needle String delimiter
*/
public function split($needle) {
return explode($this->str, $needle);
}
/**
* To keep with Java's internal coding, we issue our own toString().
*
* You can use ->toString() or (string)$variable;
* Either works fine.
*
* @return string
*/
public function toString() {
return $this->str;
}
/**
* Magic internals to return string upon casting.
*
* @return string
*/
public function __toString() {
return $this->str;
}
}
<?php
/**
* The <code>System</code> class contains several useful class fields
* and methods. It is a static class.
*
* @author Nijikokun <[email protected]>
* @copyright AOL <http://aol.nexua.org>
* @package System
* @version 1.0
* @since p.j1
*/
class System { }
/**
* Controls Objects being sent to the PrintStream or Reader (Browser / Terminal).
*
* @author Nijikokun <[email protected]>
* @copyright AOL <http://aol.nexua.org>
* @package System
* @subpackage out
* @version 1.0
* @since p.j1
*/
class out extends System {
/**
* Prints a String and then terminate the line.
* We use prnt because PHP has an issue with over-loading / over-riding functions.
*
* @param $x The <code>Object</code> to be printed.
*/
public static function prntln($x = '') {
return isset($_SERVER['SERVER_PROTOCOL']) ? print $x . "<br />" . PHP_EOL : print $x . PHP_EOL;
}
/**
* Prints an Object without line termination.
* We use prnt because PHP has an issue with over-loading / over-riding functions.
*
* @param $x The <code>Object</code> to be printed.
*/
public static function prnt($x = '') {
print $x;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment