cancel
Showing results for 
Search instead for 
Did you mean: 

Code Sniffer Fails

Code Sniffer Fails

I am trying to run code sniffing for one of my module and it is giving the below error.

 

Class 'ArrayObject' is restricted in /usr/share/eqp/PhpCodeSnifferTool/tmp/work/DataObject.php. Suggested replacement: Custom class, extended from ArrayObject with overwritten serialize/unserialize methods.

Here is the code
<?php
declare(strict_types=1);
namespace Vendor\Module;
use ArrayObject;
class DataObject extends ArrayObject
{
public function __construct($array = [])
{
parent::__construct((array) $array, ArrayObject::ARRAY_AS_PROPS);
}
public function get($key, $default = null) {
if ($this->offsetExists($key)) {
return $this->offsetGet($key);
}
return $default;
}
}
 
Can anyone suggest what can be done to solve this?

Thanks.
1 REPLY 1

Re: Code Sniffer Fails

The error you are seeing is a warning from PHP CodeSniffer indicating that the use of the ArrayObject class is restricted. This warning is often triggered by security scanners that check for the use of untrusted classes that could be used for malicious purposes.

In your case, you can resolve the warning by following the suggestion provided: create a custom class that extends ArrayObject and overrides the serialize and unserialize methods. Here is an example:

<?php
declare(strict_types=1);

namespace Vendor\Module;

class CustomArrayObject extends \ArrayObject
{
    public function serialize()
    {
        // Add any custom serialization logic here
        return parent::serialize();
    }

    public function unserialize($serialized)
    {
        // Add any custom unserialization logic here
        parent::unserialize($serialized);
    }
}

 

Then, update your DataObject class to use the CustomArrayObject class instead of the ArrayObject class:

 
<?php
declare(strict_types=1);

namespace Vendor\Module;

class DataObject extends CustomArrayObject
{
    public function __construct($array = [])
    {
        parent::__construct((array) $array, CustomArrayObject::ARRAY_AS_PROPS);
    }

    public function get($key, $default = null)
    {
        if ($this->offsetExists($key)) {
            return $this->offsetGet($key);
        }
        return $default;
    }
}
 

 

After making these changes, you should be able to run PHP CodeSniffer without encountering the ArrayObject restriction warning.

 

Make sure if your error is solved then press the kudos!