Is there a way to convert any value especially boolean and arrays into strings? I want to do this for a cleaner error message in a function. Right now all I can get in this example below it this for an error message
Fatal error: Uncaught InvalidArgumentException: $argument cannot be in /file.php:## Stack trace: #0 /file.php:(##): myFunction(false) #1 {main} thrown in /file.php on line 47
I want it to say "$argument cannot be false" not "$argument cannot be "
<?php
myFunction(false);
myFunction(array('a', 'b'));
//Version 0.5
function myFunction($argument) {
if (!is_string($argument)) {
throw new InvalidArgumentException('$argument cannot be ' . strval($argument));
}
//...
}
?>
Best way to convert most value types to string is using json_encode.
An array for example would become ["a","b"].
Just json_encode($argument)
I would use gettype and/or var_export:
throw new InvalidArgumentException('$argeument cannot be ' . gettype($argeument) . ' ' . var_export($argeument, true));
Or buffer output of var_dump and you can see it all:
ob_start();
var_dump($argeument);
$text = ob_get_clean();
throw new InvalidArgumentException('$argeument cannot be ' . $text);
Perhaps (in lieu of function (string $value), which I recommend)?
class InvalidArgumentType extends InvalidArgumentException
{
public function __construct(int $position, string $requiredType, $value)
{
$encoded = json_encode($value);
if (strlen($encoded) > 10) {
$encoded = sprintf('%s ... %s', substr($encoded, 0, 10), substr($encoded, -1));
}
$inferredType = is_object($value) ? get_class($value) : gettype($value);
parent::__construct(sprintf(
'Argument %d value %s should be %s but is %s.',
$position,
$encoded,
$requiredType,
$inferredType
));
}
}
class Foo {}
echo (new InvalidArgumentType(1, 'string', new Foo()))->getMessage().PHP_EOL;
echo (new InvalidArgumentType(2, 'string', [1,2,3,4,5,6,7,8,9,10]))->getMessage().PHP_EOL;
echo (new InvalidArgumentType(3, 'string', 123))->getMessage().PHP_EOL;
echo (new InvalidArgumentType(2, 'string', null))->getMessage();
Gives:
Argument 1 value {} should be string but is Foo.
Argument 2 value [1,2,3,4,5 ... ] should be string but is array.
Argument 3 value 123 should be string but is integer.
Argument 2 value null should be string but is NULL.
https://3v4l.org/ko7o1
Related
C:\xampp\htdocs\ksucatalog\application\helpers\nokencode_helper.php
Line: 118
Function: number_format
Message: number_format(): Passing null to parameter #1 ($num) of type float is deprecated
code:
if (!function_exists('money')) {
function money($str)
{
return number_format($str, 2, '.', ',');
}
}
Message error: 3 passed and at least 4 expected.
I understand that 7.1 creates a fatal error but I don't understand why it is expecting 4 arguments in this case and it says that it passed 3 arguments instead of the two normally accepted with call_user_func_array.
The error is indicated on this line:
$ret = call_user_func_array(array($this->loadedPlugins[$this->availableMethods[$method]], $method), $args);
After reading the php documentation about user_func_array I saw that the array should be in the second position, so I tried to inverse them :
call_user_func_array($args, array($this->loadedPlugins[$this->availableMethods[$method]], $method));
In this case the error disappears but the images are not showing.
This use to work in php5.6 and php7.
Any help is appreciated
public function execute($cmd){
$ret = null ;
$out = array();
if($this->escapeChars) {
$cmd= str_replace ('(','\(',$cmd);
$cmd= str_replace (')','\)',$cmd);
}
exec( $cmd .' 2>&1', $out, $ret);
if($ret != 0)
if($this->debug) trigger_error (new phMagickException ('Error executing "'. $cmd.'" <br>return code: '. $ret .' <br>command output :"'. implode("<br>", $out).'"' ), E_USER_NOTICE );
$this->log[] = array(
'cmd' => $cmd
,'return' => $ret
,'output' => $out
);
return $ret ;
}
public function __call($method, $args){
if(! key_exists($method, $this->availableMethods))
throw new Exception ('Call to undefined method : ' . $method);
array_unshift($args, $this);
$ret = call_user_func_array(array($this->loadedPlugins[$this->availableMethods[$method]], $method), $args);
if($ret === false)
throw new Exception ('Error executing method "' . $method ."'");
return $ret ;
}
I'm trying to implement a generic HMAC function in PHP. I'm following the RFC and the wikipedia page, but I cannot get my function to match the sample outputs. What am I doing wrong?
function myHmac(string $data, string $key, callable $algoFn, int $algoBlockSizeInBytes): string
{
if (strlen($key) > $algoBlockSizeInBytes)
{
$key = $algoFn($key); // keys longer than blocksize are shortened
}
if (strlen($key) < $algoBlockSizeInBytes)
{
$key = $key . str_repeat(0x00, $algoBlockSizeInBytes - strlen($key)); // keys shorter than blocksize are zero-padded
}
$outerKeyPad = str_repeat(0x5c, $algoBlockSizeInBytes) ^ $key;
$innerKeyPad = str_repeat(0x36, $algoBlockSizeInBytes) ^ $key;
return bin2hex($algoFn($outerKeyPad . $algoFn($innerKeyPad . $data)));
}
$md5Fn = function ($str) { return md5($str, true); };
echo 'my output: ' . myHmac("", "", $md5Fn, 64) . "\n";
echo 'correct output: ' . hash_hmac('md5', "", "") . "\n";
You invoke string_repeat() with an integer instead of the string to be repeated. So integer to string conversion applies. This means that currently you get something like 0x36 -> '54' -> '54545454...5454' ('54' repeated 64 times) and so on. Use chr(0x36) to get the actual byte.
I received this warning
Warning: Illegal string offset 'class' in C:\xampp\htdocs\myweb\libraries\cms\html\html.php on line 971
Warning: Illegal string offset 'class' in C:\xampp\htdocs\myweb\libraries\cms\html\html.php on line 972
Warning: Illegal string offset 'class' in C:\xampp\htdocs\myweb\libraries\cms\html\html.php on line 972
On joomla 3.3 (file path \libraries\cms\html\html.php) and the code is:
public static function calendar($value, $name, $id, $format = '%Y-%m-%d', $attribs = null)
{
static $done;
if ($done === null)
{
$done = array();
}
$attribs['class'] = isset($attribs['class']) ? $attribs['class'] : 'input-medium';//happen here
$attribs['class'] = trim($attribs['class'] . ' hasTooltip');//happen here
$readonly = isset($attribs['readonly']) && $attribs['readonly'] == 'readonly';
$disabled = isset($attribs['disabled']) && $attribs['disabled'] == 'disabled';
if (is_array($attribs))
{
$attribs = JArrayHelper::toString($attribs);
}
.......
Shows that it had to do with $attribs['class']. And if I'm correct illegal string offset could mean that $attribs is not an array but a string. So is there any way to correct this?
I'm on PHP5.4
This:
public static function calendar($value, $name, $id, $format = '%Y-%m-%d', $attribs = null)
{
}
Should be:
public static function calendar($value, $name, $id, $format = '%Y-%m-%d', $attribs = array())
{
}
Point is that by setting "null" to the variable by default, you actually say it's an empty string, or an empty variable. By setting "array()", you define the variable being an empty array.
Just by looking a little bit further, there is an array expected, since the code is looking for specific array_keys like: 'readonly' AND 'disabled'.
I have the following function...
function myFunction($arg1 = '', arg2 = '') {
return 'My args: ' . $arg1 . ' & ' . $arg2;
}
... which I call with the data retrieved from GET in...
$arg1 = retrieve($_GET, 'arg1'); // custom function
$arg2 = retrieve($_GET, 'arg2'); // retrieves array value or empty string
$result = myFunction($arg1, $arg2);
... but ...
echo ($result === 'My args: ' . $arg1 . ' & ' . $arg2); // Why is this false?
Given that arg1 results in an empty string, but arg2 does not, why is the value of arg2 considered arg1 once it's been passed on to the function?
I'm a newbie to PHP, I'm most used to Java, and the introduction of optional parameters plus a mix of paradigms, etc confuses me.
TLDR; Why is arg1 not empty when called as myFunction('', $arg2);
EDIT: Posted code is made-up; actual code can be found here -> http://pastie.org/8623944#7
EDIT2: Testing code again, it was a typo on my part; I was reassigning $arg1 the value of $arg2 BEFORE passing it to the function. My bad.
Your function does not return the string, but echoes it, so the === will never be true
try
function myFunction($arg1 = '', arg2 = '') {
return 'My args: ' . $arg1 . ' & ' . $arg2;
}