ClassCreator::create()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 9.584
c 0
b 0
f 0
cc 3
nc 3
nop 2
1
<?php
2
3
/*
4
 * This file is part of the Prophecy.
5
 * (c) Konstantin Kudryashov <[email protected]>
6
 *     Marcello Duarte <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Prophecy\Doubler\Generator;
13
14
use Prophecy\Exception\Doubler\ClassCreatorException;
15
16
/**
17
 * Class creator.
18
 * Creates specific class in current environment.
19
 *
20
 * @author Konstantin Kudryashov <[email protected]>
21
 */
22
class ClassCreator
23
{
24
    private $generator;
25
26
    /**
27
     * Initializes creator.
28
     *
29
     * @param ClassCodeGenerator $generator
30
     */
31
    public function __construct(ClassCodeGenerator $generator = null)
32
    {
33
        $this->generator = $generator ?: new ClassCodeGenerator;
34
    }
35
36
    /**
37
     * Creates class.
38
     *
39
     * @param string         $classname
40
     * @param Node\ClassNode $class
41
     *
42
     * @return mixed
43
     *
44
     * @throws \Prophecy\Exception\Doubler\ClassCreatorException
45
     */
46
    public function create($classname, Node\ClassNode $class)
47
    {
48
        $code = $this->generator->generate($classname, $class);
49
        $return = eval($code);
50
51
        if (!class_exists($classname, false)) {
52
            if (count($class->getInterfaces())) {
53
                throw new ClassCreatorException(sprintf(
54
                    'Could not double `%s` and implement interfaces: [%s].',
55
                    $class->getParentClass(), implode(', ', $class->getInterfaces())
56
                ), $class);
57
            }
58
59
            throw new ClassCreatorException(
60
                sprintf('Could not double `%s`.', $class->getParentClass()),
61
                $class
62
            );
63
        }
64
65
        return $return;
66
    }
67
}
68