Hi guys,
Need some help translating some Python to PHP. There is the Python snippet as well as a non working version of a PHP conversion. Any help on this would be greatly appreciated.
Python
[CODE]def bchr(ord):
if not (32 < ord < 126):
return “\” + oct(ord).lstrip(‘0’).rjust(3, ‘0’)
elif ord == 92:
return r’\’
else:
return chr(ord)
def encode(data):
return ”.join([bchr(ord(x)) for x in data])
def decode(data):
diter = iter(data)
output = []
next = diter.next
for x in diter:
if x == “\”:
try:
y = next()
except StopIteration:
raise ValueError, “incomplete backslash sequence”
if y == “\”:
pass
elif y.isdigit():
try:
os = ”.join((y, next(), next()))
except StopIteration:
raise ValueError, “incomplete backslash sequence”
try:
x = chr(int(os, base = 8))
except ValueError:
raise ValueError, “invalid bytea octal sequence ‘%s'” %(os,)
else:
raise ValueError, “invalid backslash follow ‘%s'” %(y,)
output.append(x)
return ”.join(output)
PHP
[CODE]public function bchr($ord)
{
if (!((32<$ord)&&($ord<126)))
{
$result = “\\”. str_pad(ltrim(decoct($ord),0),3,0, STR_PAD_LEFT);
Mage::log(‘1=’.$result);
return $result;
}
elseif ($ord==92)
{
$result = ‘\\’;
Mage::log(‘2=’.$result);
return $result;
}
else
{
$result = chr($ord);
Mage::log(‘3=’.$result);
return $result;
}
}
public function encode($data)
{
$joined = ”;
$pregData = preg_split(‘//’, $data, -1, PREG_SPLIT_NO_EMPTY);
foreach ($pregData as $x)
{
$ord = ord($x);
Mage::log(‘x=’.$x);
Mage::log(‘ord=’.$ord);
$joined .= $this->bchr($ord);
}
return $joined;
}
public function decode($data)
{
$pregData = preg_split(‘//’, $data, -1, PREG_SPLIT_NO_EMPTY);
$output = ”;
foreach ($pregData as $x)
{
if ($x == ‘\\’)
{
$y = next($pregData);
//Mage::log($y);
if ($y == ‘\\’)
{
continue;
}
elseif (is_int($y))
{
$os = $y.next($pregData).next($pregData);
$x = chr(intval($os, 8));
Mage::log($x);
}
else
{
//Mage::throwException(‘Invalid Backslash Follow $y’);
}
}
$output .= $x;
}
return $output;
}