<?php
/**
* Copyright (c) 2008, SARL Adaltas. All rights reserved.
* Code licensed under the BSD License:
* http://porte.adaltas.com/en/developer/license.html
*/
/**
* PorteOneToManyBelongsTo
*
* @package Porte
* @subpackage plugin
* @author David Worms info(at)adaltas.com
* @copyright 2008 Adaltas
*/
class PorteOneToManyBelongsTo{
public static function getRecord($property,$record){
// Deal with lazy loading if required
if(!array_key_exists($property,$record->attributes)&&!$record->isNew())$record->load($record->getIdentifier(),array('force'=>true));
$config = $record->porte->models->{$record->type}['properties'][$property];
// if association not yet created and we got a foreign key then create the association
if($record->isNew()||array_key_exists($property,$record->associations)){
if(array_key_exists($property,$record->associations)||array_key_exists($property,$record->attributes)){
$value = array_key_exists($property,$record->associations)?$record->associations[$property]:$record->attributes[$property];
if(is_null($value)){
// ok, we'll just return null
}else if(is_int($value)){
$instance = $record->porte->tables->get($config['belongs_to']['type'])->load($value);
$record->associations[$property] = $instance;
}else if(!is_object($value)&&!$value instanceof PorteRecord){
unset($record->associations[$property]);
}
}else{
$record->associations[$property] = null;
}
return $record->associations[$property];
}else if(!isset($record->associations[$property])&&!empty($record->attributes[$property])){
$recordAssoc = $record->porte->tables->{$config['belongs_to']['type']}->load($record->attributes[$property]);
return $record->associations[$property] = $recordAssoc;
// if association already set, return it
}else if(array_key_exists('default',$config)){
return $config['default'];
}else{
return $record->associations[$property] = null;
}
}
/**
* Note, setting an associated record does not load the record if a primary key (or an
* array) is provided.
*
* @return PorteRecord The current record
* @param $property Object
* @param $record Object
* @param $assocRecord Object[optional]
*/
public static function setRecord($property,$record,$assocRecord=null){
$config = $record->porte->models->{$record->type}['properties'][$property];
$assocRecord = PorteAssociations::makeRecord($record,$config,'belongs_to',$assocRecord);
$record->associations[$property] = $assocRecord;
return $record;
}
}
?>