Completed
Push — master ( 89d255...f8b47e )
by Thomas
03:08
created

AbstractModel::exportRecursiveArray()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 9.4285
cc 3
eloc 6
nc 1
nop 1
crap 3
1
<?php
2
namespace gossi\swagger;
3
4
use phootwork\collection\Collection;
5
6
abstract class AbstractModel {
7
8 10
	protected function export() {
9 10
		$cols = func_get_args();
10
11
		// add cols
12 10
		if (method_exists($this, 'hasRef') && $this->hasRef()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class gossi\swagger\AbstractModel as the method hasRef() does only exist in the following sub-classes of gossi\swagger\AbstractModel: gossi\swagger\Items, gossi\swagger\Parameter, gossi\swagger\Response, gossi\swagger\Schema, gossi\swagger\collections\Parameters. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
13 6
			$cols = array_merge(['$ref'], $cols);
14 6
		}
15
16
		// flatten array
17 10
		$fields = [];
18
		array_walk_recursive($cols, function ($a) use (&$fields) { $fields[] = $a; });
0 ignored issues
show
Coding Style introduced by
It is generally recommended to place each PHP statement on a line by itself.

Let’s take a look at an example:

// Bad
$a = 5; $b = 6; $c = 7;

// Good
$a = 5;
$b = 6;
$c = 7;
Loading history...
19
20 10
		$out = [];
21 10
		$refl = new \ReflectionClass(get_class($this));
22
23 10
		foreach ($fields as $field) {
24 10
			if ($field == 'tags') {
25 7
				$val = $this->exportTags();
0 ignored issues
show
Bug introduced by
The method exportTags() does not exist on gossi\swagger\AbstractModel. Did you maybe mean export()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
26 7
			} else {
27 10
				$prop = $refl->getProperty($field == '$ref' ? 'ref' : $field);
28 10
				$prop->setAccessible(true);
29 10
				$val = $prop->getValue($this);
30
31 10
				if ($val instanceof Collection) {
32 10
					$val = $this->exportRecursiveArray($val->toArray());
33 10
				} else if (method_exists($val, 'toArray')) {
34 10
					$val = $val->toArray();
35 10
				}
36
			}
37
38 10
			if ($field == 'required' && is_bool($val) || !empty($val)) {
39 8
				$out[$field] = $val;
40 8
			}
41 10
		}
42
43 10
		if (method_exists($this, 'getExtensions')) {
44 10
			$out = array_merge($out, $this->getExtensions()->toArray());
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class gossi\swagger\AbstractModel as the method getExtensions() does only exist in the following sub-classes of gossi\swagger\AbstractModel: gossi\swagger\Contact, gossi\swagger\ExternalDocs, gossi\swagger\Header, gossi\swagger\Info, gossi\swagger\Items, gossi\swagger\License, gossi\swagger\Operation, gossi\swagger\Parameter, gossi\swagger\Path, gossi\swagger\Response, gossi\swagger\Schema, gossi\swagger\Swagger, gossi\swagger\Tag, gossi\swagger\collections\Paths, gossi\swagger\collections\Responses. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
45 10
		}
46
47 10
		return $out;
48
	}
49
50
	protected function exportRecursiveArray($array) {
51 11
		return array_map(function ($v) {
52 10
			if (is_object($v) && method_exists($v, 'toArray')) {
53 10
				return $v->toArray();
54
			}
55 6
			return $v;
56 11
		}, $array);
57
	}
58
}
59