Skip to content

Commit

Permalink
adding helper for conveniently loading item by ID or some alias
Browse files Browse the repository at this point in the history
  • Loading branch information
soletan committed Dec 27, 2016
1 parent c9548d4 commit b972593
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions extensions/model/classes/model.php
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,44 @@ public static function select( connection $source = null, $itemId )
return new static( $source, $itemId );
}

/**
* Fetches item of current model matching given selector.
*
* This method is searching item with ID matching provided value if value is
* an integer. If provided value is not an integer but some scalar (string)
* it is searching item matching given value in additionally named property.
*
* @param connection|null $source
* @param integer|string $value value to look up to find matching item
* @param string $property name of property to use if value is not an integer
* @return static|null found existing item
*/
public static function get( connection $source = null, $value, $property = 'alias' ) {
if ( !$value )
throw new \InvalidArgumentException( 'missing model item selector' );

if ( $value instanceof self )
return $value;

if ( !is_scalar( $value ) )
throw new \InvalidArgumentException( 'invalid model item selector' );

$value = trim( $value );
if ( ctype_digit( $value ) ) {
$item = static::select( $source, intval( $value ) );

if ( !$item->exists() )
return null;
} else {
$filter = array();
$filter[$property] = $value;

$item = static::findOne( $source, $filter );
}

return $item ?: null;
}

/**
* Detects if selected item of model exists in datasource or not.
*
Expand Down

0 comments on commit b972593

Please sign in to comment.