File: MockDelegateFunctionBuilder.php

package info (click to toggle)
php-mock-integration 3.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 152 kB
  • sloc: php: 183; makefile: 18; sh: 7; xml: 7
file content (87 lines) | stat: -rw-r--r-- 2,329 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php

namespace phpmock\integration;

use phpmock\generator\ParameterBuilder;
use SebastianBergmann\Template\Template;

/**
 * Defines a MockDelegateFunction.
 *
 * @author Markus Malkusch <markus@malkusch.de>
 * @link bitcoin:1335STSwu9hST4vcMRppEPgENMHD2r1REK Donations
 * @license http://www.wtfpl.net/txt/copying/ WTFPL
 * @internal
 */
class MockDelegateFunctionBuilder
{
    
    /**
     * The delegation method name.
     */
    const METHOD = "delegate";
    
    /**
     * @var string The namespace of the build class.
     */
    private $namespace;
    
    /**
     * @var Template The MockDelegateFunction template.
     */
    private $template;
    
    /**
     * Instantiation.
     */
    public function __construct()
    {
        $this->template = new Template(__DIR__ . '/MockDelegateFunction.tpl');
    }
    
    /**
     * Builds a MockDelegateFunction for a function.
     *
     * @param string|null $functionName The mocked function.
     *
     * @SuppressWarnings(PHPMD)
     */
    public function build($functionName = null)
    {
        $functionNameOrEmptyString = $functionName === null ? '' : $functionName;

        $parameterBuilder = new ParameterBuilder();
        $parameterBuilder->build($functionNameOrEmptyString);
        $signatureParameters = $parameterBuilder->getSignatureParameters();

        /**
         * If a class with the same signature exists, it is considered equivalent
         * to the generated class.
         */
        $hash = md5($functionNameOrEmptyString . $signatureParameters);
        $this->namespace = __NAMESPACE__ . $hash;
        if (class_exists($this->getFullyQualifiedClassName())) {
            return;
        }
        
        $data = [
            "namespace"           => $this->namespace,
            "signatureParameters" => $signatureParameters,
            "function"            => $functionName === null ? '' : 'public function ' . $functionName . '() {}',
        ];
        $this->template->setVar($data, false);
        $definition = $this->template->render();
        
        eval($definition);
    }

    /**
     * Returns the fully qualified class name
     *
     * @return string The class name.
     */
    public function getFullyQualifiedClassName()
    {
        return "$this->namespace\\MockDelegateFunction";
    }
}