Doctrine2ormDatabase   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 109
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
dl 0
loc 109
rs 10
c 0
b 0
f 0
wmc 13
lcom 1
cbo 3

3 Methods

Rating   Name   Duplication   Size   Complexity  
C connect() 0 38 7
B prepareConfiguration() 0 39 5
A getResource() 0 4 1
1
<?php
2
namespace Agavi\Database;
3
4
// +---------------------------------------------------------------------------+
5
// | This file is part of the Agavi package.                                   |
6
// | Copyright (c) 2005-2011 the Agavi Project.                                |
7
// |                                                                           |
8
// | For the full copyright and license information, please view the LICENSE   |
9
// | file that was distributed with this source code. You can also view the    |
10
// | LICENSE file online at http://www.agavi.org/LICENSE.txt                   |
11
// |   vi: set noexpandtab:                                                    |
12
// |   Local Variables:                                                        |
13
// |   indent-tabs-mode: t                                                     |
14
// |   End:                                                                    |
15
// +---------------------------------------------------------------------------+
16
use Agavi\Exception\DatabaseException;
17
18
/**
19
 * A database adapter for the Doctrine2 ORM. Can be used standalone, or by
20
 * referencing a Doctrine2dbalDatabase connection.
21
 *
22
 * Users wishing to implement more advanced configuration options than supported
23
 * by this adapter or register event handlers should subclass this driver and
24
 * override the prepareConfiguration() and prepareEventManager() methods,
25
 * respectively (always remember to call the parent method in this case).
26
 *
27
 * Supported configuration parameters:
28
 *  - "connection": an array of connection details as expected by Doctrine2, or
29
 *                  the name (string) of a configured AgaviDoctrine2dbalDatabase
30
 *                  that should be used by this connection.
31
 *  - "configuration_class": the name of the class used for the configuration
32
 *                           object.
33
 *  - "event_manager_class": the name of the class used for the event manager
34
 *                           object.
35
 *  - "configuration": an array containing various configuration options:
36
 *   - "metadata_driver_impl_argument" (required): the argument for the metadata
37
 *                                                 driver constructor, usually
38
 *                                                 a path to the folder with the
39
 *                                                 entities or metadata files.
40
 *   - "metadata_driver_impl_class": the metadata driver implementation class.
41
 *                                   If omitted, the default annotation driver
42
 *                                   of Doctrine2 will be used.
43
 *   - "auto_generate_proxy_classes": boolean flag for proxy auto generation,
44
 *                                    defaults to on in debug mode.
45
 *   - "proxy_namespace": The namespace of the proxy classes.
46
 *   - "proxy_dir": The directory containing the proxy classes.
47
 *   - "metadata_cache_impl_class": The class to use for metadata caching.
48
 *                                  Defaults to Doctrine\Common\Cache\ApcCache
49
 *                                  (Doctrine\Common\Cache\ArrayCache in debug).
50
 *   - "query_cache_impl_class": The class to use for metadata caching.
51
 *                               Defaults to Doctrine\Common\Cache\ApcCache
52
 *                               (Doctrine\Common\Cache\ArrayCache in debug).
53
 *   - "result_cache_impl_class": The class to use for metadata caching.
54
 *                                Defaults to Doctrine\Common\Cache\ApcCache
55
 *                                (Doctrine\Common\Cache\ArrayCache in debug).
56
 *
57
 * @package    agavi
58
 * @subpackage database
59
 *
60
 * @author     David Zülke <[email protected]>
61
 * @copyright  Authors
62
 * @copyright  The Agavi Project
63
 *
64
 * @since      1.0.6
65
 *
66
 * @version    $Id$
67
 */
68
class Doctrine2ormDatabase extends Doctrine2Database
69
{
70
    /**
71
     * Connect to the database.
72
     *
73
     * @author     David Zülke <[email protected]>
74
     * @since      1.0.6
75
     */
76
    public function connect()
77
    {
78
        $connection = $this->getParameter('connection');
79
        if (is_string($connection)) {
80
            try {
81
                $connection = $this->getDatabaseManager()->getDatabase($connection);
82
            } catch (DatabaseException $e) {
83
                throw new DatabaseException(sprintf('AgaviDoctrine2dbalDatabase connection "%s" configured for use in AgaviDoctrine2ormDatabase "%s" could not be found.', $connection, $this->getName()), 0, $e);
84
            }
85
            try {
86
                $connection = $connection->getConnection();
87
            } catch (DatabaseException $e) {
88
                throw new DatabaseException(sprintf("AgaviDoctrine2dbalDatabase connection '%s' configured for use in AgaviDoctrine2ormDatabase '%s' could not be initialized:\n\n%s", $this->getParameter('connection'), $this->getName(), $e->getMessage()), 0, $e);
89
            }
90
        } elseif (!is_array($connection)) {
91
            throw new DatabaseException('AgaviDoctrine2ormDatabase expects configuration parameter "connection" to be an array containing connection details or a string with the name of an AgaviDoctrine2dbalDatabase to use.');
92
        }
93
        
94
        // make new configuration
95
        $cc = $this->getParameter('configuration_class', '\Doctrine\ORM\Configuration');
96
        $config = new $cc();
97
        $this->prepareConfiguration($config);
98
        
99
        // make new event manager or take the one on the given named connection
100
        if ($connection instanceof \Doctrine\DBAL\Connection) {
0 ignored issues
show
Bug introduced by
The class Doctrine\DBAL\Connection does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
101
            $eventManager = $connection->getEventManager();
102
        } else {
103
            $ec = $this->getParameter('event_manager_class', '\Doctrine\Common\EventManager');
104
            $eventManager = new $ec();
105
        }
106
        $this->prepareEventManager($eventManager);
107
        
108
        try {
109
            $this->connection = \Doctrine\ORM\EntityManager::create($connection, $config, $eventManager);
110
        } catch (Exception $e) {
0 ignored issues
show
Bug introduced by
The class Agavi\Database\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
111
            throw new DatabaseException(sprintf("Failed to create Doctrine\ORM\EntityManager for connection '%s':\n\n%s", $this->getName(), $e->getMessage()), 0, $e);
112
        }
113
    }
114
    
115
    /**
116
     * Prepare the configuration for this connection.
117
     *
118
     * @param      Doctrine\ORM\Configuration The configuration object.
119
     *
120
     * @author     David Zülke <[email protected]>
121
     * @since      1.0.6
122
     */
123
    protected function prepareConfiguration(\Doctrine\DBAL\Configuration $config)
124
    {
125
        parent::prepareConfiguration($config);
126
        
127
        // auto-generate proxy classes in debug mode by default
128
        $config->setAutoGenerateProxyClasses($this->getParameter('configuration[auto_generate_proxy_classes]', Config::get('core.debug')));
129
        
130
        $mda = $this->getParameter('configuration[metadata_driver_impl_argument]');
131
        // check if a metadata driver class is configured (explicitly check with getParameter() to allow "deletion" of the parameter by using null)
132
        if ($this->hasParameter('configuration[metadata_driver_impl_class]') && $md = $this->getParameter('configuration[metadata_driver_impl_class]')) {
133
            // yes, so we construct the class with the configured arguments
134
            // construct the given class and pass the path as the argument
135
            // in many cases, the argument may be a string with a path or an array of paths, which means that we cannot use reflection and newInstanceArgs()
136
            // for more elaborate cases with multiple ctor arguments or where the ctor expects a non-scalar value, people need to use prepareConfiguration() in a subclass
137
            $md = new $md($mda);
138
        } else {
139
            // no, that means we use the default annotation driver and the configured argument as the path
140
            $md = $config->newDefaultAnnotationDriver($mda);
141
        }
142
        $config->setMetadataDriverImpl($md);
143
        
144
        // set proxy namespace and dir
145
        // defaults to something including the connection name, or the app cache dir, respectively
146
        $config->setProxyNamespace($this->getParameter('configuration[proxy_namespace]', 'AgaviDoctrine2ormDatabase_Proxy_' . preg_replace('#\W#', '_', $this->getName())));
147
        $config->setProxyDir($this->getParameter('configuration[proxy_dir]', Config::get('core.cache_dir')));
148
        
149
        // unless configured differently, use ArrayCache in debug mode and APC (if available) otherwise
150
        if (Config::get('core.debug') || !extension_loaded('apc')) {
151
            $defaultCache = '\Doctrine\Common\Cache\ArrayCache';
152
        } else {
153
            $defaultCache = '\Doctrine\Common\Cache\ApcCache';
154
        }
155
        $metadataCache = $this->getParameter('configuration[metadata_cache_impl_class]', $defaultCache);
156
        $config->setMetadataCacheImpl(new $metadataCache);
157
        $queryCache = $this->getParameter('configuration[query_cache_impl_class]', $defaultCache);
158
        $config->setQueryCacheImpl(new $queryCache);
159
        $resultCache = $this->getParameter('configuration[result_cache_impl_class]', $defaultCache);
160
        $config->setResultCacheImpl(new $resultCache);
161
    }
162
    
163
    /**
164
     * Retrieve the Doctrine\DBAL\Connection resource associated with our entity
165
     * manager.
166
     *
167
     * @return     Doctrine\DBAL\Connection The underlying DBAL connection.
168
     *
169
     * @author     David Zülke <[email protected]>
170
     * @since      1.0.6
171
     */
172
    public function getResource()
173
    {
174
        return $this->getConnection()->getConnection();
175
    }
176
}
177