Completed
Pull Request — master (#15)
by Tim
01:32
created

LoggerFactory::prepareConstructorArgs()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 29
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 29
rs 8.439
cc 5
eloc 13
nc 8
nop 2
1
<?php
2
3
/**
4
 * TechDivision\Import\Configuration\Jms\Configuration\LoggerFactory
5
 *
6
 * NOTICE OF LICENSE
7
 *
8
 * This source file is subject to the Open Software License (OSL 3.0)
9
 * that is available through the world-wide-web at this URL:
10
 * http://opensource.org/licenses/osl-3.0.php
11
 *
12
 * PHP version 5
13
 *
14
 * @author    Tim Wagner <[email protected]>
15
 * @copyright 2016 TechDivision GmbH <[email protected]>
16
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
17
 * @link      https://github.com/techdivision/import-configuration-jms
18
 * @link      http://www.techdivision.com
19
 */
20
21
namespace TechDivision\Import\Configuration\Jms\Configuration;
22
23
use TechDivision\Import\Utils\LoggerKeys;
24
use TechDivision\Import\Utils\SwiftMailerKeys;
25
use TechDivision\Import\ConfigurationInterface;
26
use TechDivision\Import\Configuration\LoggerConfigurationInterface;
27
28
/**
29
 * Logger factory implementation.
30
 *
31
 * @author    Tim Wagner <[email protected]>
32
 * @copyright 2016 TechDivision GmbH <[email protected]>
33
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
34
 * @link      https://github.com/techdivision/import-configuration-jms
35
 * @link      http://www.techdivision.com
36
 */
37
class LoggerFactory
38
{
39
40
    /**
41
     * Creates a new logger instance based on the passed logger configuration.
42
     *
43
     * @param \TechDivision\Import\ConfigurationInterface                     $configuration       The system configuration
44
     * @param \TechDivision\Import\Configuration\LoggerConfigurationInterface $loggerConfiguration The logger configuration
45
     *
46
     * @return \Psr\Log\LoggerInterface The logger instance
47
     */
48
    public static function factory(
49
        ConfigurationInterface $configuration,
50
        LoggerConfigurationInterface $loggerConfiguration
51
    ) {
52
53
        // initialize the processors
54
        $processors = array();
55
        /** @var \TechDivision\Import\Configuration\Logger\ProcessorConfigurationInterface $processorConfiguration */
56
        foreach ($loggerConfiguration->getProcessors() as $processorConfiguration) {
57
            $reflectionClass = new \ReflectionClass($processorConfiguration->getType());
58
            $processors[] = $reflectionClass->newInstanceArgs(LoggerFactory::prepareConstructorArgs($reflectionClass, $processorConfiguration->getParams()));
59
        }
60
61
        // initialize the handlers
62
        $handlers = array();
63
        /** @var \TechDivision\Import\Configuration\Logger\HandlerConfigurationInterface $handlerConfiguration */
64
        foreach ($loggerConfiguration->getHandlers() as $handlerConfiguration) {
65
            // query whether or not, we've a swift mailer configuration
66
            if ($swiftMailerConfiguration = $handlerConfiguration->getSwiftMailer()) {
67
                // load the factory that creates the swift mailer instance
68
                $factory = $swiftMailerConfiguration->getFactory();
69
                // create the swift mailer instance
70
                $swiftMailer = $factory::factory($swiftMailerConfiguration);
71
72
                // load the generic logger configuration
73
                $bubble = $handlerConfiguration->getParam(LoggerKeys::BUBBLE);
74
                $logLevel = $handlerConfiguration->getParam(LoggerKeys::LOG_LEVEL);
75
76
                // load sender/receiver configuration
77
                $to = $swiftMailerConfiguration->getParam(SwiftMailerKeys::TO);
78
                $from = $swiftMailerConfiguration->getParam(SwiftMailerKeys::FROM);
79
                $subject = $swiftMailerConfiguration->getParam(SwiftMailerKeys::SUBJECT);
80
                $contentType = $swiftMailerConfiguration->getParam(SwiftMailerKeys::CONTENT_TYPE);
81
82
                // initialize the message template
83
                $message = $swiftMailer->createMessage()
84
                    ->setSubject(sprintf('[%s] %s', $configuration->getSystemName(), $subject))
85
                    ->setFrom($from)
86
                    ->setTo($to)
87
                    ->setBody('', $contentType);
88
89
                // initialize the handler node
90
                $reflectionClass = new \ReflectionClass($handlerConfiguration->getType());
91
                $handler = $reflectionClass->newInstanceArgs(array($swiftMailer, $message, $logLevel, $bubble));
92
93
            } else {
94
                // initialize the handler node
95
                $reflectionClass = new \ReflectionClass($handlerConfiguration->getType());
96
97
                // load the params
98
                $params = $handlerConfiguration->getParams();
99
100
                // set the default log level, if not already set explicitly
101
                if (!isset($params['level'])) {
102
                    $params['level'] = $configuration->getLogLevel();
103
                }
104
105
                // create the handler instance
106
                $handler = $reflectionClass->newInstanceArgs(LoggerFactory::prepareConstructorArgs($reflectionClass, $params));
107
            }
108
109
            // if we've a formatter, initialize the formatter also
110
            if ($formatterConfiguration = $handlerConfiguration->getFormatter()) {
111
                $reflectionClass = new \ReflectionClass($formatterConfiguration->getType());
112
                $handler->setFormatter($reflectionClass->newInstanceArgs(LoggerFactory::prepareConstructorArgs($reflectionClass, $formatterConfiguration->getParams())));
113
            }
114
115
            // add the handler
116
            $handlers[] = $handler;
117
        }
118
119
        // prepare the logger params
120
        $loggerParams = array(
121
            'name' => $loggerConfiguration->getChannelName(),
122
            'handlers' => $handlers,
123
            'processors' => $processors
124
        );
125
126
        // append the params from the logger configuration
127
        $loggerParams = array_merge($loggerParams, $loggerConfiguration->getParams());
128
129
        // initialize the logger instance itself
130
        $reflectionClass = new \ReflectionClass($loggerConfiguration->getType());
131
        return $reflectionClass->newInstanceArgs(LoggerFactory::prepareConstructorArgs($reflectionClass, $loggerParams));
132
    }
133
134
    /**
135
     * Prepare's the arguments for the passed reflection class by applying the values from the passed configuration array
136
     * to the apropriate arguments. If no value is found in the configuration, the constructor argument's default value is
137
     * used.
138
     *
139
     * @param \ReflectionClass $reflectionClass The reflection class to prepare the arguments for
140
     * @param array            $params          The constructor arguments from the configuration
141
     *
142
     * @return array The array with the constructor arguements
143
     */
144
    protected static function prepareConstructorArgs(\ReflectionClass $reflectionClass, array $params)
145
    {
146
147
        // prepare the array for the initialized arguments
148
        $initializedParams = array();
149
150
        // prepare the array for the arguments in camel case (in configuration we use a '-' notation)
151
        $paramsInCamelCase = array();
152
153
        // convert the configuration keys to camelcase
154
        foreach ($params as $key => $value) {
155
            $paramsInCamelCase[lcfirst(str_replace('-', '', ucwords($key, '-')))] = $value;
156
        }
157
158
        // prepare the arguments by applying the values from the configuration
159
        /** @var \ReflectionParameter $reflectionParameter */
160
        foreach ($reflectionClass->getConstructor()->getParameters() as $reflectionParameter) {
161
            if (isset($paramsInCamelCase[$paramName = $reflectionParameter->getName()])) {
162
                $initializedParams[$paramName] = $paramsInCamelCase[$paramName];
163
            } elseif ($reflectionParameter->isOptional()) {
164
                $initializedParams[$paramName] = $reflectionParameter->getDefaultValue();
165
            } else {
166
                $initializedParams[$paramName] = null;
167
            }
168
        }
169
170
        // return the array with the prepared arguments
171
        return $initializedParams;
172
    }
173
}
174