<?php
/*******************************************************************************
* Copyright 2008 Rafael Marques Martins
*
* This file is part of SQLReactor.
*
* SQLReactor is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* SQLReactor is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SQLReactor; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*******************************************************************************/
class SQLReactorDepTree{
protected $classes = array();
protected $classFlags = array();
protected $creationOrder = array();
public function __construct( $classes ){
$this->addClasses( $classes );
$this->calculateCreationOrder();
}
protected function calculateCreationOrder(){
while( $this->classes ){
foreach( $this->classes as $class => $deps ){
if( array_sum( $deps ) ) continue;
$this->creationOrder[] = $class;
unset( $this->classes[ $class ] );
$this->classFlags[ $class ] = 0;
}
}
}
public function getCreationOrder(){
return $this->creationOrder;
}
protected function addClasses( $classes ){
foreach( $classes as $class ){
$this->addClass( $class );
}
}
protected function addClass( $class ){
if( !isset( $this->classFlags[ $class ] ) ){
$this->classFlags[ $class ] = 1;
}
$this->classes[ $class ] = $this->getClassDeps( $class );
}
protected function getClassDeps( $class ){
$deps = array();
$obj = new $class();
foreach( $obj->_table->columns as $column ){
if( $column instanceof ForeignKey && !$column->config[ 'weakRelation' ] ){
if( is_array( $column->config[ 'target' ] ) ){
$target = $column->config[ 'target' ][ 0 ];
}else{
$target = $column->config[ 'target' ];
}
if( $target == $class ) continue;
if( !isset( $this->classFlags[ $target ] ) ){
$this->classFlags[ $target ] = 1;
}
$deps[] = &$this->classFlags[ $target ];
}
}
return $deps;
}
}
?>