Completed
Push — master ( 5ea837...9dec3c )
by Paul
9s
created

MonologConfig::getConfigurationDefaults()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
/**
3
 * This file is part of the PPI Framework.
4
 *
5
 * @copyright   Copyright (c) 2011-2016 Paul Dragoonis <[email protected]>
6
 * @license     http://opensource.org/licenses/mit-license.php MIT
7
 *
8
 * @link        http://www.ppi.io
9
 */
10
11
namespace PPI\Framework\ServiceManager\Config;
12
13
use Zend\ServiceManager\ServiceManager;
14
15
/**
16
 * ServiceManager configuration for Monolog services.
17
 *
18
 * @author     Vítor Brandão <[email protected]>
19
 */
20
class MonologConfig extends AbstractConfig
21
{
22
    protected $nestedHandlers = array();
23
24
    /**
25
     * Create and return the logger.
26
     *
27
     * @see https://github.com/symfony/MonologBundle/blob/master/DependencyInjection/MonologExtension.php
28
     *
29
     * {@inheritdoc}
30
     */
31
    public function configureServiceManager(ServiceManager $serviceManager)
32
    {
33
        $configs               = $serviceManager->get('Config');
34
        $configs['parameters'] = array_merge(array(
35
            "monolog.logger.class"                                                  => "PPI\Framework\Log\Logger",
36
            "monolog.gelf.publisher.class"                                          => "Gelf\MessagePublisher",
37
            "monolog.handler.stream.class"                                          => "Monolog\Handler\StreamHandler",
38
            "monolog.handler.group.class"                                           => "Monolog\Handler\GroupHandler",
39
            "monolog.handler.buffer.class"                                          => "Monolog\Handler\BufferHandler",
40
            "monolog.handler.rotating_file.class"                                   => "Monolog\Handler\RotatingFileHandler",
41
            "monolog.handler.syslog.class"                                          => "Monolog\Handler\SyslogHandler",
42
            "monolog.handler.null.class"                                            => "Monolog\Handler\NullHandler",
43
            "monolog.handler.test.class"                                            => "Monolog\Handler\TestHandler",
44
            "monolog.handler.gelf.class"                                            => "Monolog\Handler\GelfHandler",
45
            "monolog.handler.firephp.class"                                         => "Symfony\Bridge\Monolog\Handler\FirePHPHandler",
46
            "monolog.handler.chromephp.class"                                       => "Symfony\Bridge\Monolog\Handler\ChromePhpHandler",
47
            "monolog.handler.debug.class"                                           => "Symfony\Bridge\Monolog\Handler\DebugHandler",
48
            "monolog.handler.swift_mailer.class"                                    => "Monolog\Handler\SwiftMailerHandler",
49
            "monolog.handler.native_mailer.class"                                   => "Monolog\Handler\NativeMailerHandler",
50
            "monolog.handler.socket.class"                                          => "Monolog\Handler\SocketHandler",
51
            "monolog.handler.pushover.class"                                        => "Monolog\Handler\PushoverHandler",
52
            "monolog.handler.fingers_crossed.class"                                 => "Monolog\Handler\FingersCrossedHandler",
53
            "monolog.handler.fingers_crossed.error_level_activation_strategy.class" => "Monolog\Handler\FingersCrossed\ErrorLevelActivationStrategy",
54
        ), $configs['parameters']);
55
56
        $config             = $this->processConfiguration($configs, $serviceManager);
0 ignored issues
show
Bug introduced by
It seems like $configs defined by $serviceManager->get('Config') on line 33 can also be of type object; however, PPI\Framework\ServiceMan...:processConfiguration() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
57
        $handlersToChannels = array();
58
59
        if (isset($config['handlers'])) {
60
            $handlers = array();
61
62
            foreach ($config['handlers'] as $name => $handler) {
63
                $handlers[$handler['priority']][] = array(
64
                    'id'       => $this->buildHandler($serviceManager, $configs['parameters'], $name, $handler),
65
                    'channels' => isset($handler['channels']) ? $handler['channels'] : null,
66
                );
67
            }
68
69
            $sortedHandlers = array();
70
            foreach ($handlers as $priorityHandlers) {
71
                foreach (array_reverse($priorityHandlers) as $handler) {
72
                    $sortedHandlers[] = $handler;
73
                }
74
            }
75
76
            foreach ($sortedHandlers as $handler) {
77
                if (!in_array($handler['id'], $this->nestedHandlers)) {
78
                    $handlersToChannels[$handler['id']] = $handler['channels'];
79
                }
80
            }
81
        }
82
83
        $loggerClass = $configs['parameters']['monolog.logger.class'];
84
        $serviceManager->setFactory('monolog.logger', function ($serviceManager) use ($loggerClass, $handlersToChannels) {
85
            $logger = new $loggerClass('app');
86
            foreach ($handlersToChannels as $handler => $channels) {
87
                $logger->pushHandler($serviceManager->get($handler));
88
            }
89
90
            return $logger;
91
        });
92
    }
93
94
    /**
95
     * {@inheritDoc}
96
     */
97
    public function getConfigurationDefaults()
98
    {
99
        return array('monolog' => array());
100
    }
101
102
    protected function buildHandler(ServiceManager $serviceManager, array $parameters, $name, array $handler)
103
    {
104
        $handlerId        = $this->getHandlerId($name);
105
        $class            = $parameters[sprintf('monolog.handler.%s.class', $handler['type'])];
106
        $handler['level'] = is_int($handler['level']) ? $handler['level'] : constant('Monolog\Logger::' . strtoupper($handler['level']));
107
108
        $serviceManager->setFactory($handlerId, function ($serviceManager) use ($class, $handler) {
0 ignored issues
show
Unused Code introduced by
The parameter $serviceManager is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
109
            switch ($handler['type']) {
110
            case 'stream':
111
                return new $class($handler['path'], $handler['level'], $handler['bubble']);
112
            }
113
114
            /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
115
             * TODO:
116
             * <code>
117
             if (!empty($handler['formatter'])) {
118
                $definition->addMethodCall('setFormatter', array(new Reference($handler['formatter'])));
119
             }
120
             */
121
        });
122
123
        return $handlerId;
124
    }
125
126
    protected function getHandlerId($name)
127
    {
128
        return sprintf('monolog.handler.%s', $name);
129
    }
130
131
    /**
132
     * {@inheritDoc}
133
     */
134
    protected function processConfiguration(array $configs, ServiceManager $serviceManager = null)
135
    {
136
        $alias = $this->getAlias();
137
        if (!isset($configs[$alias])) {
138
            return array();
139
        }
140
141
        $parameterBag = $serviceManager->get('application_parameters');
0 ignored issues
show
Bug introduced by
It seems like $serviceManager is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
142
        $config       = $configs[$alias];
143
144
        if (isset($config['handlers'])) {
145
            foreach (array_keys($config['handlers']) as $k) {
146 View Code Duplication
                if (!isset($config['handlers'][$k]['priority'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
147
                    $config['handlers'][$k]['priority'] = 0;
148
                }
149 View Code Duplication
                if (!isset($config['handlers'][$k]['bubble'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
150
                    $config['handlers'][$k]['bubble'] = true;
151
                }
152
                if (isset($config['handlers'][$k]['path'])) {
153
                    $config['handlers'][$k]['path'] = $parameterBag->resolveString($config['handlers'][$k]['path']);
154
                }
155
            }
156
        }
157
158
        return $config;
159
    }
160
}
161