Doctrine.php 14.6 KB
Newer Older
doctrine's avatar
doctrine committed
1
<?php
2
/*
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 *  $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
 * <http://www.phpdoctrine.com>.
 */

doctrine's avatar
doctrine committed
22
require_once("Doctrine/Exception.php");
23

doctrine's avatar
doctrine committed
24 25 26 27
/**
 * Doctrine
 * the base class of Doctrine framework
 *
28 29
 * @package     Doctrine
 * @author      Konsta Vesterinen
doctrine's avatar
doctrine committed
30 31 32 33 34 35
 * @license     LGPL
 */
final class Doctrine {
    /**
     * ERROR MODE CONSTANTS
     */
36

doctrine's avatar
doctrine committed
37 38 39 40 41 42 43 44 45 46 47 48 49
    /**
     * NO PRIMARY KEY COLUMN ERROR
     * no primary key column found error code
     */
    const ERR_NO_PK                 = 0;
    /**
     * PRIMARY KEY MISMATCH ERROR
     * this error code is used when user uses factory refresh for a
     * given Doctrine_Record and the old primary key doesn't match the new one
     */
    const ERR_REFRESH               = 1;
    /**
     * FIND ERROR
50
     * this code used when for example Doctrine_Table::find() is called and
doctrine's avatar
doctrine committed
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
     * a Data Access Object is not found
     */
    const ERR_FIND                  = 2;
    /**
     * TABLE NOT FOUND ERROR
     * this error code is used when user tries to initialize
     * a table and there is no database table for this factory
     */
    const ERR_NOSUCH_TABLE          = 3;
    /**
     * NAMING ERROR
     * this code is used when user defined Doctrine_Table is badly named
     */
    const ERR_NAMING                = 5;
    /**
     * TABLE INSTANCE ERROR
     * this code is used when user tries to initialize
     * a table that is already initialized
     */
    const ERR_TABLE_INSTANCE        = 6;
    /**
     * NO OPEN SESSIONS ERROR
     * error code which is used when user tries to get
     * current session are there are no sessions open
     */
    const ERR_NO_SESSIONS           = 7;
    /**
     * MAPPING ERROR
     * if there is something wrong with mapping logic
     * this error code is used
     */
    const ERR_MAPPING               = 8;

    /**
     * ATTRIBUTE CONSTANTS
     */

    /**
     * event listener attribute
     */
    const ATTR_LISTENER         = 1;
    /**
     * fetchmode attribute
     */
    const ATTR_FETCHMODE        = 2;
    /**
     * cache directory attribute
     */
    const ATTR_CACHE_DIR        = 3;
    /**
     * cache time to live attribute
     */
    const ATTR_CACHE_TTL        = 4;
    /**
     * cache size attribute
     */
    const ATTR_CACHE_SIZE       = 5;
    /**
     * cache slam defense probability
     */
    const ATTR_CACHE_SLAM       = 6;
    /**
     * cache container attribute
     */
    const ATTR_CACHE            = 7;
    /**
     * batch size attribute
     */
    const ATTR_BATCH_SIZE       = 8;
    /**
     * primary key columns attribute
     */
    const ATTR_PK_COLUMNS       = 9;
    /**
     * primary key type attribute
     */
    const ATTR_PK_TYPE          = 10;
    /**
     * locking attribute
     */
    const ATTR_LOCKMODE         = 11;
    /**
     * validatate attribute
     */
    const ATTR_VLD              = 12;
    /**
     * name prefix attribute
     */
    const ATTR_NAME_PREFIX      = 13;
    /**
     * create tables attribute
     */
    const ATTR_CREATE_TABLES    = 14;
    /**
     * collection key attribute
     */
    const ATTR_COLL_KEY         = 15;
148
    /**
doctrine's avatar
doctrine committed
149 150 151
     * collection limit attribute
     */
    const ATTR_COLL_LIMIT       = 16;
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
    /**
     * query limit
     */
    const ATTR_QUERY_LIMIT      = 17;
    
    
    /**
     * LIMIT CONSTANTS
     */
    
    /**
     * constant for row limiting
     */
    const LIMIT_ROWS       = 1;
    /**
     * constant for record limiting
     */
    const LIMIT_RECORDS    = 2;

doctrine's avatar
doctrine committed
171 172 173 174 175 176



    /**
     * CACHE CONSTANTS
     */
177

doctrine's avatar
doctrine committed
178 179 180 181 182 183 184 185
    /**
     * sqlite cache constant
     */
    const CACHE_SQLITE          = 0;
    /**
     * constant for disabling the caching
     */
    const CACHE_NONE            = 1;
186 187 188



doctrine's avatar
doctrine committed
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
    /**
     * FETCHMODE CONSTANTS
     */

    /**
     * IMMEDIATE FETCHING
     * mode for immediate fetching
     */
    const FETCH_IMMEDIATE       = 0;
    /**
     * BATCH FETCHING
     * mode for batch fetching
     */
    const FETCH_BATCH           = 1;
    /**
     * LAZY FETCHING
     * mode for lazy fetching
     */
    const FETCH_LAZY            = 2;
    /**
     * LAZY FETCHING
     * mode for offset fetching
     */
    const FETCH_OFFSET          = 3;
    /**
     * LAZY OFFSET FETCHING
     * mode for lazy offset fetching
     */
    const FETCH_LAZY_OFFSET     = 4;
218

219
    /**
220
     * FETCH CONSTANTS
221 222 223 224
     */


    /**
225 226 227 228 229
     * FETCH VALUEHOLDER
     */
    const FETCH_VHOLDER         = 1;
    /**
     * FETCH RECORD
230 231 232 233 234
     *
     * Specifies that the fetch method shall return Doctrine_Record 
     * objects as the elements of the result set.
     *
     * This is the default fetchmode.
235
     */
236
    const FETCH_RECORD          = 2;
237
    /**
238
     * FETCH ARRAY                      
239
     */
240

241
    const FETCH_ARRAY           = 3;
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
    /**
     * FETCH COLUMN
     * Specifies that the fetch method shall return only a single 
     * requested column from the next row in the result set.
     *
     */
    const FETCH_COLUMN          = 4;
    /**
     * FETCH ASSOC
     *
     * Specifies that the fetch method shall return each row as an
     * array indexed by column name as returned in the corresponding
     * result set. If the result set contains multiple columns with
     * the same name, PDO::FETCH_ASSOC returns only a single value per column name.
     *
     */
    const FETCH_ASSOC           = 5;
    /**
     * FETCH NAMED
     *
     * Specifies that the fetch method shall return each row as an array indexed
     * by column name as returned in the corresponding result set. If the result set
     * contains multiple columns with the same name, PDO::FETCH_NAMED returns an
     * array of values per column name.
     *
     */
    const FETCH_NAMED           = 6;
    /**
     * FETCH NUM
     *
     * Specifies that the fetch method shall return each row as an array indexed by
     * column number as returned in the corresponding result set, starting at column 0.
     */
    const FETCH_NUM             = 7;
    /**
     * FETCH BOTH
     *
     * Specifies that the fetch method shall return each row as an array indexed by both
     * column name and number as returned in the corresponding result set, starting at column 0.
     */
    const FETCH_BOTH            = 8;
    /**
     * FETCH OBJ
     *
     * Specifies that the fetch method shall return each row as an object with property names 
     * that correspond to the column names returned in the result set.
     */
    const FETCH_OBJ             = 9;
290

291

doctrine's avatar
doctrine committed
292 293 294
    /**
     * LOCKMODE CONSTANTS
     */
295

doctrine's avatar
doctrine committed
296 297 298 299 300 301 302 303
    /**
     * mode for optimistic locking
     */
    const LOCK_OPTIMISTIC       = 0;
    /**
     * mode for pessimistic locking
     */
    const LOCK_PESSIMISTIC      = 1;
304

doctrine's avatar
doctrine committed
305 306 307
    /**
     * PRIMARY KEY TYPE CONSTANTS
     */
308

doctrine's avatar
doctrine committed
309 310 311 312 313 314 315 316
    /**
     * auto-incremented/(sequence updated) primary key
     */
    const INCREMENT_KEY         = 0;
    /**
     * unique key
     */
    const UNIQUE_KEY            = 1;
317

318 319 320 321 322 323
    /**
     * constructor
     */
    public function __construct() {
        throw new Doctrine_Exception('Doctrine is static class. No instances can be created.');
    }
doctrine's avatar
doctrine committed
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
    /**
     * @var string $path            doctrine root directory
     */
    private static $path;
    /**
     * returns the doctrine root
     *
     * @return string
     */
    public static function getPath() {
        if(! self::$path)
            self::$path = dirname(__FILE__);

        return self::$path;
    }
    /**
     * loads all runtime classes
     *
     * @return void
     */
    public static function loadAll() {
        if(! self::$path)
            self::$path = dirname(__FILE__);
doctrine's avatar
doctrine committed
347 348 349

        $path = self::$path.DIRECTORY_SEPARATOR."Doctrine";
        $dir = dir($path);
doctrine's avatar
doctrine committed
350 351 352 353 354 355 356 357 358 359 360 361
        $a   = array();
        while (false !== ($entry = $dir->read())) {
            switch($entry):
                case ".":
                case "..":
                break;
                case "Cache":
                case "Record":
                case "Collection":
                case "Table":
                case "Validator":
                case "Exception":
doctrine's avatar
doctrine committed
362
                case "EventListener":
doctrine's avatar
doctrine committed
363 364 365 366
                case "Session":
                case "DQL":
                case "Sensei":
                case "Iterator":
367
                case "View":
doctrine's avatar
doctrine committed
368
                case "Query":
doctrine's avatar
doctrine committed
369
                    $a[]  = $path.DIRECTORY_SEPARATOR.$entry;
doctrine's avatar
doctrine committed
370 371
                break;
                default:
doctrine's avatar
doctrine committed
372 373
                    if(is_file($path.DIRECTORY_SEPARATOR.$entry) && substr($entry,-4) == ".php") {
                        require_once($path.DIRECTORY_SEPARATOR.$entry);
doctrine's avatar
doctrine committed
374 375 376 377 378 379 380 381 382 383 384 385 386
                    }
            endswitch;
        }
        foreach($a as $dirname) {
            $dir = dir($dirname);
            $path = $dirname.DIRECTORY_SEPARATOR;
            while (false !== ($entry = $dir->read())) {
                if(is_file($path.$entry) && substr($entry,-4) == ".php") {
                    require_once($path.$entry);
                }
            }
        }
    }
387
    /**
388
     * method for making a single file of most used doctrine runtime components
389
     * including the compiled file instead of multiple files (in worst
390
     * cases dozens of files) can improve performance by an order of magnitude
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
     *
     * @throws Doctrine_Exception
     * @return void
     */
    public static function compile() {
        if(! self::$path)
            self::$path = dirname(__FILE__);

        $classes = array("Doctrine",
                         "Configurable",
                         "Manager",
                         "Session",
                         "Table",
                         "Iterator",
                         "Exception",
                         "Access",
zYne's avatar
zYne committed
407
                         "Null",
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
                         "Record",
                         "Record_Iterator",
                         "Collection",
                         "Validator",
                         "Hydrate",
                         "Query",
                         "Query_Part",
                         "Query_From",
                         "Query_Orderby",
                         "Query_Groupby",
                         "Query_Condition",
                         "Query_Where",
                         "Query_Having",
                         "RawSql",
                         "EventListener_Interface",
                         "EventListener",
                         "Relation",
                         "ForeignKey",
                         "LocalKey",
                         "Association",
doctrine's avatar
doctrine committed
428 429
                         "DB",
                         "DBStatement");
430

431 432 433 434

        $ret     = array();

        foreach($classes as $class) {
doctrine's avatar
doctrine committed
435
            if($class !== 'Doctrine')
436
                $class = 'Doctrine_'.$class;
437

438 439 440 441 442 443
            $file  = self::$path.DIRECTORY_SEPARATOR.str_replace("_",DIRECTORY_SEPARATOR,$class).".php";

            if( ! file_exists($file))
                throw new Doctrine_Exception("Couldn't compile $file. File $file does not exists.");

            self::autoload($class);
zYne's avatar
zYne committed
444 445
            $refl  = new ReflectionClass ( $class );
            $lines = file( $file );
446

zYne's avatar
zYne committed
447 448 449
            $start = $refl -> getStartLine() - 1;
            $end   = $refl -> getEndLine();

zYne's avatar
zYne committed
450
            $ret = array_merge($ret,
451 452 453
                               array_slice($lines,
                               $start,
                              ($end - $start)));
454 455 456

        }

zYne's avatar
zYne committed
457
        $file = self::$path.DIRECTORY_SEPARATOR.'Doctrine.compiled.php';
458 459 460 461 462 463 464 465
        if (!is_writable($file))
            throw new Doctrine_Exception("Couldn't write compiled data. $file is not writable");

        // first write the 'compiled' data to a text file, so
        // that we can use php_strip_whitespace (which only works on files)
        $fp = fopen($file, 'w');
        if ($fp === false)
            throw new Doctrine_Exception("Couldn't write compiled data. Failed to open $file");
466 467 468 469
        fwrite($fp, "<?php".
                    " class InvalidKeyException extends Exception { }".
                    " class DQLException extends Exception { }".
                    implode('', $ret)
470
              );
471
        fclose($fp);
zYne's avatar
zYne committed
472

473 474 475 476
        $stripped = php_strip_whitespace( $file );
        $fp = fopen($file, 'w');
        if ($fp === false)
            throw new Doctrine_Exception("Couldn't write compiled data. Failed to open $file");
zYne's avatar
zYne committed
477 478
        fwrite($fp, $stripped);
        fclose($fp);
479
    }
480

doctrine's avatar
doctrine committed
481 482 483 484 485 486 487 488 489 490 491
    /**
     * simple autoload function
     * returns true if the class was loaded, otherwise false
     *
     * @param string $classname
     * @return boolean
     */
    public static function autoload($classname) {
        if(! self::$path)
            self::$path = dirname(__FILE__);

doctrine's avatar
doctrine committed
492 493
        if(class_exists($classname))
            return false;
doctrine's avatar
doctrine committed
494

doctrine's avatar
doctrine committed
495 496 497 498 499 500 501 502 503
        $class = self::$path.DIRECTORY_SEPARATOR.str_replace("_",DIRECTORY_SEPARATOR,$classname).".php";

        if( ! file_exists($class))
            return false;


        require_once($class);
        return true;
    }
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
    /**
     * returns table name from class name
     *
     * @param string $classname
     * @return string
     */
    public static function tableize($classname) {
         return strtolower(preg_replace('~(?<=\\w)([A-Z])~', '_$1', $classname));
    }
    /**
     * returns class name from table name
     *
     * @param string $tablename
     * @return string
     */
    public static function classify($tablename) {
520
        return preg_replace('~(_?)(_)([\w])~e', '"$1".strtoupper("$3")', ucfirst($tablename));
521
    }
doctrine's avatar
doctrine committed
522 523
}
?>