Completed
Push — master ( 1413b8...20a7b3 )
by Asmir
13s
created

SoapContainerBuilder::getMetadataForSoapEnvelope()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
namespace GoetasWebservices\SoapServices\SoapClient\Builder;
3
4
use GoetasWebservices\SoapServices\SoapClient\DependencyInjection\SoapClientExtension;
5
use GoetasWebservices\SoapServices\SoapClient\DependencyInjection\Compiler\CleanupPass;
6
use GoetasWebservices\Xsd\XsdToPhpRuntime\Jms\Handler\BaseTypesHandler;
7
use GoetasWebservices\Xsd\XsdToPhpRuntime\Jms\Handler\XmlSchemaDateHandler;
8
use JMS\Serializer\SerializerBuilder;
9
use JMS\Serializer\Handler\HandlerRegistryInterface;
10
use Psr\Log\LoggerInterface;
11
use Symfony\Component\Config\FileLocator;
12
use Symfony\Component\Config\Loader\DelegatingLoader;
13
use Symfony\Component\Config\Loader\LoaderResolver;
14
use Symfony\Component\DependencyInjection\ContainerBuilder;
15
use Symfony\Component\DependencyInjection\ContainerInterface;
16
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
17
use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
18
use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
19
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
20
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
21
22
class SoapContainerBuilder
23
{
24
25
    private $className = 'SoapClientContainer';
26
27
    private $classNs = 'SoapServicesStub';
28
29
    protected $configFile = 'config.yml';
30
31
    protected $extensions = [];
32
33
    protected $compilerPasses = [];
34
35
    protected static $metadataForSoapEnvelope = [
36
        'GoetasWebservices\SoapServices\SoapClient\Envelope\SoapEnvelope12' => __DIR__ . '/../Resources/metadata/jms12',
37
        'GoetasWebservices\SoapServices\SoapClient\Envelope\SoapEnvelope' => __DIR__ . '/../Resources/metadata/jms'
38
    ];
39
40
    /**
41
     *
42
     * @var LoggerInterface
43
     */
44
    private $logger;
45
46 2
    public function __construct($configFile = null, LoggerInterface $logger = null)
47
    {
48 2
        $this->logger = $logger;
49 2
        $this->setConfigFile($configFile);
50 2
        $this->addExtension(new SoapClientExtension());
51 2
        $this->addCompilerPass(new CleanupPass());
52 2
    }
53
54 2
    public function setConfigFile($configFile)
55
    {
56 2
        $this->configFile = $configFile;
57 2
    }
58
59 2
    protected function addExtension(ExtensionInterface $extension)
60
    {
61 2
        $this->extensions[] = $extension;
62 2
    }
63
64 2
    protected function addCompilerPass(CompilerPassInterface $pass)
65
    {
66 2
        $this->compilerPasses[] = $pass;
67 2
    }
68
69
    public function setContainerClassName($fqcn)
70
    {
71
        $fqcn = strtr($fqcn, [
72
            '.' => '\\',
73
            '/' => '\\'
74
        ]);
75
        $pos = strrpos($fqcn, '\\');
76
        $this->className = substr($fqcn, $pos + 1);
77
        $this->classNs = substr($fqcn, 0, $pos);
78
    }
79
80
    /**
81
     *
82
     * @param array $metadata
83
     * @return ContainerBuilder
84
     */
85 2
    protected function getContainerBuilder(array $metadata = array())
86
    {
87 2
        $container = new ContainerBuilder();
88
89 2
        foreach ($this->extensions as $extension) {
90 2
            $container->registerExtension($extension);
91 2
        }
92
93 2
        foreach ($this->compilerPasses as $pass) {
94 2
            $container->addCompilerPass($pass);
95 2
        }
96
97 2
        $locator = new FileLocator('.');
98
        $loaders = array(
99 2
            new YamlFileLoader($container, $locator),
100 2
            new XmlFileLoader($container, $locator)
101 2
        );
102 2
        $delegatingLoader = new DelegatingLoader(new LoaderResolver($loaders));
103 2
        $delegatingLoader->load($this->configFile);
104
105
        // set the production soap metadata
106 2
        $container->setParameter('goetas_webservices.soap_client.metadata', $metadata);
107
108 2
        $container->compile();
109
110 2
        return $container;
111
    }
112
113
    /**
114
     *
115
     * @param ContainerInterface $debugContainer
116
     * @return array
117
     */
118 1
    protected function fetchMetadata(ContainerInterface $debugContainer)
119
    {
120 1
        $metadataReader = $debugContainer->get('goetas_webservices.soap_client.metadata_loader.dev');
121 1
        $wsdlMetadata = $debugContainer->getParameter('goetas_webservices.soap_client.config')['metadata'];
122 1
        $metadata = [];
123 1
        foreach (array_keys($wsdlMetadata) as $uri) {
124 1
            $metadata[$uri] = $metadataReader->load($uri);
125 1
        }
126
127 1
        return $metadata;
128
    }
129
130 2
    public function getDebugContainer()
131
    {
132 2
        return $this->getContainerBuilder();
133 1
    }
134
135
    /**
136
     *
137
     * @return ContainerInterface
138
     */
139
    public function getProdContainer()
140
    {
141
        $ref = new \ReflectionClass("{$this->classNs}\\{$this->className}");
142
        return $ref->newInstance();
143
    }
144
145
    /**
146
     *
147
     * @param
148
     *            $dir
149
     * @param ContainerInterface $debugContainer
150
     */
151 1
    public function dumpContainerForProd($dir, ContainerInterface $debugContainer)
152
    {
153 1
        $metadata = $this->fetchMetadata($debugContainer);
154
155 1
        if (! $metadata) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $metadata of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
156
            throw new \Exception("Empty metadata can not be used for production");
157
        }
158 1
        $forProdContainer = $this->getContainerBuilder($metadata);
159 1
        $this->dump($forProdContainer, $dir);
160 1
    }
161
162 1
    private function dump(ContainerBuilder $container, $dir)
163
    {
164 1
        $dumper = new PhpDumper($container);
165
        $options = [
166 1
            'debug' => false,
167 1
            'class' => $this->className,
168 1
            'namespace' => $this->classNs
169 1
        ];
170
171 1
        if (! is_dir($dir)) {
172
            mkdir($dir, 0777, true);
173
        }
174
175 1
        file_put_contents($dir . '/' . $this->className . '.php', $dumper->dump($options));
176 1
    }
177
178
    /**
179
     *
180
     * @param ContainerInterface $container
181
     * @param callable $callback
182
     * @return SerializerBuilder
183
     */
184
    public static function createSerializerBuilderFromContainer(ContainerInterface $container, callable $callback = null)
185
    {
186
        $destinations = $container->getParameter('goetas_webservices.soap_client.config')['destinations_jms'];
187
        return self::createSerializerBuilder($destinations, $callback);
188
    }
189
190
    /**
191
     *
192
     * @param array $jmsMetadata
193
     * @param callable $callback
194
     * @return SerializerBuilder
195
     */
196
    public static function createSerializerBuilder(array $jmsMetadata, callable $callback = null)
197
    {
198
        $jmsMetadata = array_merge(self::getMetadataForSoapEnvelope(), $jmsMetadata);
199
200
        $serializerBuilder = SerializerBuilder::create();
201
        $serializerBuilder->configureHandlers(function (HandlerRegistryInterface $handler) use ($callback, $serializerBuilder) {
202
            $serializerBuilder->addDefaultHandlers();
203
            $handler->registerSubscribingHandler(new BaseTypesHandler()); // XMLSchema List handling
204
            $handler->registerSubscribingHandler(new XmlSchemaDateHandler()); // XMLSchema date handling
205
            if ($callback) {
206
                call_user_func($callback, $handler);
207
            }
208
        });
209
210
        foreach ($jmsMetadata as $php => $dir) {
211
            $serializerBuilder->addMetadataDir($dir, $php);
212
        }
213
        return $serializerBuilder;
214
    }
215
216
    /**
217
     *
218
     * @return string[]
219
     */
220
    public static function getMetadataForSoapEnvelope()
221
    {
222
        return self::$metadataForSoapEnvelope;
223
    }
224
}
225