3 namespace RedBeanPHP\Util;
5 use RedBeanPHP\OODB as OODB;
6 use RedBeanPHP\RedException as RedException;
11 * A helper class containing a dispense utility.
13 * @file RedBeanPHP/Util/DispenseHelper.php
14 * @author Gabor de Mooij and the RedBeanPHP Community
18 * copyright (c) G.J.G.T. (Gabor) de Mooij and the RedBeanPHP Community
19 * This source file is subject to the BSD/GPLv2 License that is bundled
20 * with this source code in the file license.txt.
25 * Dispenses a new RedBean OODB Bean for use with
26 * the rest of the methods.
28 * @param OODB $oodb OODB
29 * @param string|array $typeOrBeanArray type or bean array to import
30 * @param integer $number number of beans to dispense
31 * @param boolean $alwaysReturnArray if TRUE always returns the result as an array
33 * @return array|OODBBean
35 public static function dispense( OODB $oodb, $typeOrBeanArray, $num = 1, $alwaysReturnArray = FALSE ) {
37 if ( is_array($typeOrBeanArray) ) {
39 if ( !isset( $typeOrBeanArray['_type'] ) ) {
41 foreach( $typeOrBeanArray as $beanArray ) {
43 !( is_array( $beanArray )
44 && isset( $beanArray['_type'] ) ) ) {
45 throw new RedException( 'Invalid Array Bean' );
48 foreach( $typeOrBeanArray as $beanArray ) $list[] = self::dispense( $oodb, $beanArray );
52 $import = $typeOrBeanArray;
53 $type = $import['_type'];
54 unset( $import['_type'] );
56 $type = $typeOrBeanArray;
59 if ( !preg_match( '/^[a-z0-9]+$/', $type ) ) {
60 throw new RedException( 'Invalid type: ' . $type );
63 $beanOrBeans = $oodb->dispense( $type, $num, $alwaysReturnArray );
65 if ( isset( $import ) ) {
66 $beanOrBeans->import( $import );
74 * Takes a comma separated list of bean types
75 * and dispenses these beans. For each type in the list
76 * you can specify the number of beans to be dispensed.
81 * list( $book, $page, $text ) = R::dispenseAll( 'book,page,text' );
84 * This will dispense a book, a page and a text. This way you can
85 * quickly dispense beans of various types in just one line of code.
90 * list($book, $pages) = R::dispenseAll('book,page*100');
93 * This returns an array with a book bean and then another array
94 * containing 100 page beans.
96 * @param OODB $oodb OODB
97 * @param string $order a description of the desired dispense order using the syntax above
98 * @param boolean $onlyArrays return only arrays even if amount < 2
102 public static function dispenseAll( OODB $oodb, $order, $onlyArrays = FALSE )
106 foreach( explode( ',', $order ) as $order ) {
107 if ( strpos( $order, '*' ) !== FALSE ) {
108 list( $type, $amount ) = explode( '*', $order );
114 $list[] = self::dispense( $oodb, $type, $amount, $onlyArrays );