array_shift() expects parameter 1 to be array - php

I am using my application in a shared hosting, it is produced in laravel. It gives me
PHP Warning: array_shift() expects parameter 1 to be array, null given in line 53
PHP Notice: Undefined index: argv in line 49
with this code:
class ArgvInput extends Input
{
private $tokens;
private $parsed;
public function __construct(array $argv = null, InputDefinition $definition = null)
{
if (null === $argv) {
$argv = $_SERVER['argv'];
}
// strip the application name
array_shift($argv);
$this->tokens = $argv;
parent::__construct($definition);
}

It can mean that the $_SERVER['argv'] variable is also empty. I'd recommend to check it first, or you can do this:
$argv = $argv ?? $_SERVER['argv'] ?? [];
This way you'll always have an array, even if there's no input, in which case the array will be empty, and it won't trigger that error

Related

Accessing array data returned from Spotify API

I am using jwilsson's spotify-web-api-php to return data from the Spotify API using PHP.
Also I'm using digitalnature's php-ref to return info about variables.
This is my code, apologies for the fact it's probably full of errors, misconceptions, rubbish etc.
// https://stackoverflow.com/questions/4345554/convert-a-php-object-to-an-associative-array
function objectToArray($r)
{
if (is_object($r)) {
if (method_exists($r, 'toArray')) {
return $r->toArray(); // returns result directly
} else {
$r = get_object_vars($r);
}
}
if (is_array($r)) {
$r = array_map(__FUNCTION__, $r); // recursive function call
}
return $r;
}
$session = new SpotifyWebAPI\Session(
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'
);
$session->requestCredentialsToken();
$accessToken = $session->getAccessToken();
$api = new SpotifyWebAPI\SpotifyWebAPI();
$api->setAccessToken($accessToken);
$search = $api->search('fugazi','artist');
// convert object to array
$fff = objectToArray($search);
// php-ref to view info about the $fff array
r($fff);
// try to access the total value
$v1 = $fff[0]['artists']['total'];
This is what the php-ref looks like for the $fff variable:
I tried to access the total attribute via:
$v1 = $fff[0]['artists']['total'];
But receive these errors:
PHP Notice: Undefined offset: 0 in C:\websites\spotify\search.php on line 49
PHP Notice: Trying to access array offset on value of type null in C:\websites\spotify\search.php on line 49
PHP Notice: Trying to access array offset on value of type null in C:\websites\spotify\search.php on line 49
Sorry for asking a silly question and for not understanding what I'm doing, but, what am I doing wrong?

How to write that in PHP 7.2?

I have this piece of code:
private function _resolveCustomEntries($fields)
{
foreach ($fields as &$value) {
if (array_key_exists('custom', $value)) {
if (method_exists($this, $value['custom'])) {
$value['custom'] = $this->$value['custom'](); //variableInterpolation
}
}
}
return $fields;
}
I ran a PHP 7.2 compatibility check and it complained here with the "variableInterpolation" on the marked line. When I run this code, the PHP log tells me this:
ERR (3): Notice: Array to string conversion in
/public_html/lib/KiTT/Payment/Widget.php on line 217
Thats the same line where the "variableInterpolation" check failed. So how would I rewrite this code so it works in PHP 7.2?
Thanks!
Solution:
$value['custom'] = $this->$value['custom']();
has to look like this:
$value['custom'] = $this->{$value['custom']}();
It's a matter of order variables are evaled.
With
class x {
public function y() {
echo 'ok';
}
}
$x = new x();
$y = array('i' => 'y');
Then
$x->$y['i']();
Fails because PHP first tries to cast the $y variable into a string, and get the matching property of $x (which btw does not exist), then tries to get the index 'i' or that unexisting property, and then tries to run it as a callable.
Hence 3 errors:
Array to string conversion
Undefined property x::$Array
Function name must be a string (nda: the undefined property returns NULL)
Instead, curly brace the variable to set the resolving order:
$x->$y['i']();
Will work. So use $this->{$value['custom']}()
This will throw an array to string conversion in 7.2
class bob{
function foo(){
return 'bar';
}
function getFoo(){
$value['custom'] = 'foo';
$value['custom'] = $this->$value['custom']();
return $value['custom'];
}
}
$bob = new Bob();
var_dump($bob->getFoo());
But it will execute just fine in 5.6.
Then i changed the snippet to this, not calling the method directly casting the array key to function name, but initializing a string (hopefully, there is no type validation in your code) variable with the function name first:
class bob{
function foo(){
return 'bar';
}
function getFoo(){
$value['custom'] = 'foo';
$functionName = $value['custom'];
$value['custom'] = $this->$functionName();
return $value['custom'];
}
}
$bob = new Bob();
var_dump($bob->getFoo());
This will run just fine in php 7.2
You could try rewriting your code using complex (curly) syntax, you can read more about it here.
Your code would look something like this.
$value['custom'] = $this->{$value['custom']}();
Edit: moved the curly braces to correct positions.

php code error Warning: Declaration of Digital_Signature::CreateSign()

function CreateSign()
{
$rsa_obj = new Crypt_RSA(array('private_key' => $this->_privateKey));
$this->check_error($rsa_obj);
return $rsa_obj->createSign($this->_document);
}
this code display this error
Warning: Declaration of Digital_Signature::CreateSign() should be compatible with Crypt_RSA::createSign($document, $private_key = NULL, $hash_func = NULL) in /var/www/html/shares/digital_signature.php on line 49
can any one help
both functions in the parent class and child class should have the same arguments , also same default values for their arguments

PHP Warning: array_shift() expects parameter1 to be array, null given in /.../.../twitter_user_timeline/view.php

Although this error has appeared on Stack Overflow below, the answers do not solve my problem.
PHP Warning: array_shift() expects parameter 1 to be array, null given in /var/www/vhosts/my.domain/httpdocs/blocks/twitter_user_timeline/view.php on line 2
I understand I am passing null in the array, which I guess is wrong; how do I solve this?
This is the aforementioned line 2 in the named PHP file:
<?php
$tweet = array_shift( $this->controller->getTweets() ) ;
?>
This is the controller file (in case it is relevant to the above):
<?php
defined('C5_EXECUTE') or die("Access Denied.");
require_once(__DIR__ . '/twitter_api.php');
class TwitterUserTimelineBlockController extends BlockController {
protected $btTable = 'btTwitterUserTimeline';
protected $btWrapperClass = 'ccm-ui';
protected $btInterfaceWidth = 480;
protected $btInterfaceHeight = 360;
public function getBlockTypeDescription() {
return t("get Latest Tweet");
}
public function getBlockTypeName() {
return t("Twitter User Timeline");
}
public function getTweets(){
$settings = array(
'oauth_access_token' => "blah,blah,blah",
'oauth_access_token_secret' => "blah,blah,blah",
'consumer_key' => "blah,blah,blah",
'consumer_secret' => "blah,blah,blah",
);
$twitter = new TwitterAPIExchange($settings);
return json_decode( $twitter->setGetfield("? screen_name=domain_uk&count=1")
->buildOauth ('https://api.twitter.com/1.1/statuses/user_timeline.json', 'GET')
->performRequest(), true );
}
}
The answer really lies within the error message:
PHP Warning: array_shift() expects parameter 1 to be array, null given
It is therefore clear that in this line:
$tweet = array_shift($this->controller->getTweets());
$this->controller->getTweets() can (and at least sometimes does) return null. Now, you could go ahead and put a band-aid around that real quick by making sure array_shift() will not be used if getTweets() did not return an array, as desired:
$tweets = $this->controller->getTweets(); // This might be null
$tweet = $tweets ? array_shift($tweets) : null;
Note, however, that now $tweet might be null, which you need to handle appropriately. Obviously, it would be better to not use a band-aid here but to check why getTweets() (sometimes) returns null and fix that - unless that is indeed intended behavior. We can't tell as we don't know the contract for that method (i.e. how you want that method to work).

PHP Cannot access empty property error

I am getting the following error and I can't seem to figure out why or how it's getting triggered.
Fatal error: Cannot access empty property in /home/content/p/l/a/plai1870/html/com/php/Bone/Compiler.php on line 18
Line 18 is
throw new LogicException($this->$compilers[$language]." is not a supported compiler.");
Here is Compiler.php
<?php
namespace Bone;
use LogicException;
class Compiler implements \Bone\Interfaces\Compiler {
protected $compiler;
protected $compilers = array(
"php" => "PHP",
"as3" => "ActionScript3",
"javascript" => "Javascript"
);
public function __construct($language) {
$language = strtolower($language);
if (!isset($this->$compilers[$language])) {
throw new LogicException($this->$compilers[$language]." is not a supported compiler.");
}
$compiler = "\Bone\Compilers\\".$this->$compilers[$language]."\Compiler";
$this->compiler = new $compiler();
}
public function buildDefinition($object, $path = null) {
return $this->compiler()->buildInterface($object, $path);
}
public function buildObject($object, $path = null) {
return $this->compiler->buildObject($object, $path);
}
public function parameters($method) {
return;
}
public function save($data, $path) {
return;
}
}
?>
EDIT
And I'm calling it with:
$compiler = new \Bone\Compiler("php");
Sorry if this is the most obvious, but:
throw new LogicException($this->$compilers[$language]." is not a supported compiler.");
As it has been checked that the property does not exists, shouldn't it be:
throw new LogicException("$language is not a supported compiler.");
?
Edit:
$this->$compilers[$language]
^- variable property
Remove the $ there:
$this->compilers[$language]
Then you can check if the entry in the array is set, not if a propery with the name of the value inside the (unset) array $compilers (local variable) is set.
When developing, always switch on warnings and notices (highest error level you can imagine) to not run into these problems without having PHP warn you first.
Your array is $this->compilers, not $this->$compilers.
$compilers doesn't exist in your function, so $this->$compilers was looking for a blank property.

Categories