Generator.php 8.96 KB
Newer Older
zYne's avatar
zYne committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
<?php
/*
 *  $Id$
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
19
 * <http://www.phpdoctrine.org>.
zYne's avatar
zYne committed
20 21 22
 */

/**
zYne's avatar
zYne committed
23
 * Doctrine_Record_Generator
zYne's avatar
zYne committed
24 25 26
 *
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
 * @package     Doctrine
27
 * @subpackage  Plugin
zYne's avatar
zYne committed
28 29
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @version     $Revision$
30
 * @link        www.phpdoctrine.org
zYne's avatar
zYne committed
31 32
 * @since       1.0
 */
33
abstract class Doctrine_Record_Generator
zYne's avatar
zYne committed
34 35 36 37
{
    /**
     * @var array $_options     an array of plugin specific options
     */
zYne's avatar
zYne committed
38
    protected $_options = array('generateFiles' => false,
39 40 41 42
                                'identifier'    => false,
                                'generateFiles' => false,
                                'table'         => false,
                                'pluginTable'   => false,
43
                                'children'      => array());
44 45
                                
    protected $_initialized = false;
zYne's avatar
zYne committed
46 47 48 49 50 51 52 53
    /**
     * __get
     * an alias for getOption
     *
     * @param string $option
     */
    public function __get($option)
    {
zYne's avatar
zYne committed
54
        if (isset($this->_options[$option])) {
zYne's avatar
zYne committed
55 56 57 58
            return $this->_options[$option];
        }
        return null;
    }
59

zYne's avatar
zYne committed
60 61 62 63 64 65 66 67 68
    /**
     * __isset
     *
     * @param string $option
     */
    public function __isset($option) 
    {
        return isset($this->_options[$option]);
    }
69

zYne's avatar
zYne committed
70 71 72 73 74 75 76 77 78 79 80 81 82 83
    /**
     * returns the value of an option
     *
     * @param $option       the name of the option to retrieve
     * @return mixed        the value of the option
     */
    public function getOption($name)
    {
        if ( ! isset($this->_options[$name])) {
            throw new Doctrine_Plugin_Exception('Unknown option ' . $name);
        }
        
        return $this->_options[$name];
    }
84

zYne's avatar
zYne committed
85 86 87 88 89 90 91 92 93 94 95 96 97
    /**
     * sets given value to an option
     *
     * @param $option       the name of the option to be changed
     * @param $value        the value of the option
     * @return Doctrine_Plugin  this object
     */
    public function setOption($name, $value)
    {
        $this->_options[$name] = $value;
        
        return $this;
    }
98

zYne's avatar
zYne committed
99
    public function addChild(Doctrine_Record_Generator $template)
zYne's avatar
zYne committed
100
    {
101
        $this->_options['children'][] = $template;
zYne's avatar
zYne committed
102 103
    }

zYne's avatar
zYne committed
104 105 106 107 108 109 110
    /**
     * returns all options and their associated values
     *
     * @return array    all options as an associative array
     */
    public function getOptions()
    {
zYne's avatar
zYne committed
111
        return $this->_options;
zYne's avatar
zYne committed
112
    }
113

114
    public function initialize($table)
115
    {
116 117 118 119 120 121 122
    	if ($this->_initialized) {
    	    return false;
    	}
        
        $this->_initialized = true;

        $this->initOptions();
123

zYne's avatar
zYne committed
124
        $table->addGenerator($this, get_class($this));
125 126

        $this->_options['table'] = $table;
127 128 129 130 131 132 133 134 135

        $this->_options['className'] = str_replace('%CLASS%',
                                                   $this->_options['table']->getComponentName(),
                                                   $this->_options['className']);

        // check that class doesn't exist (otherwise we cannot create it)
        if (class_exists($this->_options['className'])) {
            return false;
        }
136

137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
        $conn = $this->_options['table']->getConnection();

        $this->_table = new Doctrine_Table($this->_options['className'], $conn);
        
        $conn->addTable($this->_table);

        $fk = $this->buildForeignKeys($this->_options['table']);
        
        $this->_table->setColumns($fk);

        $this->buildRelation();

        $this->setTableDefinition();
        $this->setUp();

        $this->generateClass($this->_table->getColumns());
153

154
        $this->buildChildDefinitions();
155

156 157 158 159
    }
    /** 
     * empty template method for providing the concrete plugins the ability
     * to initialize options before the actual definition is being built
160
     *
161 162 163
     * @return void
     */
    public function initOptions()
164
    {
165
        
166
    }
167
    public function buildChildDefinitions()
zYne's avatar
zYne committed
168
    {
169
        if ( ! isset($this->_options['children'])) {
170
            throw new Doctrine_Plugin_Exception("Unknown option 'children'.");
171
        }
172

zYne's avatar
zYne committed
173
        foreach ($this->_options['children'] as $child) {
zYne's avatar
zYne committed
174
            $this->_table->addGenerator($child, get_class($child));
175 176

            $child->setTable($this->_table);
zYne's avatar
zYne committed
177 178 179 180 181

            $child->setUp();
        }
    }

zYne's avatar
zYne committed
182 183 184 185 186 187 188 189 190
    /**
     * generates foreign keys for the plugin table based on the owner table
     *
     * the foreign keys generated by this method can be used for 
     * setting the relations between the owner and the plugin classes
     *
     * @param Doctrine_Table $table     the table object that owns the plugin
     * @return array                    an array of foreign key definitions
     */
191
    public function buildForeignKeys($table)
zYne's avatar
zYne committed
192 193 194 195 196 197 198 199 200 201
    {
        $fk = array();

        foreach ((array) $table->getIdentifier() as $column) {
            $def = $table->getDefinitionOf($column);

            unset($def['autoincrement']);
            unset($def['sequence']);
            unset($def['primary']);

202
            $col = $column;
zYne's avatar
zYne committed
203 204 205 206 207 208

            $def['primary'] = true;
            $fk[$col] = $def;
        }
        return $fk;
    }
209

210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
    public function buildLocalRelation()
    {
        $options = array('local'    => $this->_options['table']->getIdentifier(),
                         'foreign'  => $this->_options['table']->getIdentifier(),
                         'type'     => Doctrine_Relation::MANY);

        $options['type'] = Doctrine_Relation::ONE;
        $options['onDelete'] = 'CASCADE';
        $options['onUpdate'] = 'CASCADE';

        $this->_table->getRelationParser()->bind($this->_options['table']->getComponentName(), $options);
    }
    
    public function buildForeignRelation($alias = null)
    {
        $options = array('local'    => $this->_options['table']->getIdentifier(),
                         'foreign'  => $this->_options['table']->getIdentifier(),
                         'type'     => Doctrine_Relation::MANY);

        $aliasStr = '';

        if ($alias !== null) {
            $aliasStr = ' as ' . $alias;
        }

        $this->_options['table']->getRelationParser()->bind($this->_table->getComponentName() . $aliasStr,
                                                            $options);
    }

zYne's avatar
zYne committed
239
    /**
240
     * build a relation array to given table
zYne's avatar
zYne committed
241 242 243 244 245 246
     *
     * this method can be used for generating the relation from the plugin 
     * table to the owner table
     *
     * @return array                    the generated relation array
     */
247
    public function buildRelation()
zYne's avatar
zYne committed
248
    {
249 250
    	$this->buildForeignRelation();
        $this->buildLocalRelation();
zYne's avatar
zYne committed
251
    }
252

zYne's avatar
zYne committed
253 254 255 256 257
    /**
     * generates the class definition for plugin class
     *
     * @param array $columns    the plugin class columns, keys representing the column names
     *                          and values as column definitions
258
     *
zYne's avatar
zYne committed
259
     * @param array $relations  the bound relations of the plugin class
260 261 262
     *
     * @param array $options    plugin class options, keys representing the option names
     *                          and values as option values
zYne's avatar
zYne committed
263 264
     * @return void
     */
265
    public function generateClass(array $columns = array(), array $relations = array(), array $options = array())
zYne's avatar
zYne committed
266
    {
267
        $options['className'] = $this->_options['className'];
268

269
        $builder = new Doctrine_Builder_Record();
zYne's avatar
zYne committed
270 271 272 273

        if ($this->_options['generateFiles']) {
            if (isset($this->_options['generatePath']) && $this->_options['generatePath']) {
                $builder->setTargetPath($this->_options['generatePath']);
274

zYne's avatar
zYne committed
275 276
                $builder->buildRecord($options, $columns, $relations);
            } else {
zYne's avatar
zYne committed
277
                throw new Doctrine_Record_Exception('If you wish to generate files then you must specify the path to generate the files in.');
zYne's avatar
zYne committed
278 279 280
            }
        } else {
            $def = $builder->buildDefinition($options, $columns, $relations);
281

zYne's avatar
zYne committed
282 283 284
            eval($def);
        }
    }
zYne's avatar
zYne committed
285
}