alin mircea Tue Dec 28 21:26:18 -0500 2010

Subject: Please consider this

Hello,

I`m new here so first of all, great job on this, it`s quite powerful.

What I had in mind was:

find_by_username_or_useremail_or_create_by_username_and_password_and_useremail (
array(
'username'=>'the girl next door'
'password'=>'is home alone'
'useremail'=>''
));

My way:

if (substr($method,0,7) === 'find_by') {
$attributesCreate = $attributesFind = $attributes = substr($method,8);
$argsCreate = $argsFind = $args;

$is_or_create_by = false;
if(!$create) {
$is_or_create_by = strpos($attributes,'or_create_by');
if($is_or_create_by)//does not handle find_by_or_create_by_col_col_col_x ($is_or_create_by returns 0 in that case) {
$attributesFind = substr($attributes,0,$is_or_create_by-1);
$attributesCreate = substr($attributes,$is_or_create_by+13);
if (strpos($attributesCreate,'_or_') !== false)
throw new ActiveRecordException("Cannot use OR'd attributes in find_by_x_or_create_by");
$create = true;
}
}
//if only one argument (associative array). if it s not associative it`s a list of values
if(count($args) == 1 && is_array($args[0]) && count(array_filter(array_keys($args[0]), 'is_string'))) {
$parts = preg_split('/(and|_or_)/i',$attributesCreate);
$argsCreate = array();
for($q=0,$w=count($parts);$q<$w;$q++) {
array_push($argsCreate,$args[0][$parts[$q]]);
}
if($attributesFind == $attributesCreate) {
$argsFind = $argsCreate;
}
else {
$argsFind = array();
$parts = preg_split('/(and|_or_)/i',$attributesFind);
for($q=0,$w=count($parts);$q<$w;$q++) {
array_push($argsFind,$args[0][$parts[$q]]);
}
}
}
$options['conditions'] = SQLBuilder::create_conditions_from_underscored_string(static::table()->conn,$attributesFind,$argsFind,static::$alias_attribute);
if (!($ret = static::find('first',$options)) && $create)
{
return static::create(SQLBuilder::create_hash_from_underscored_string($attributesCreate,$argsCreate,static::$alias_attribute));
}
return $ret;
}

P.S.
This also fixes
Person::find_or_create_by_name_and_id(array('name' => 'Tito', 'id' => 1));
Which I don`t think was working.
I handle that here in not the greatest way:
if(count($args) == 1 && is_array($args0) && count(array_filter(array_keys($args0), 'is_string')))

I`m new to php coming from actionscript/java so if you see a better way, please

Alin