This repository has been archived by the owner on May 27, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
rb.php
7257 lines (7204 loc) · 226 KB
/
rb.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
REDBEANPHP 3.4
--------------
RedBeanPHP Database Objects -
Written by Gabor de Mooij (c) copyright 2009-2013 and the RedBeanPHP community
RedBeanPHP is DUAL Licensed BSD and GPLv2. You may choose the license that fits
best for your project.
*/
interface RedBean_Driver {
/**
* Runs a query and fetches results as a multi dimensional array.
*
* @param string $sql SQL to be executed
*
* @return array $results result
*/
public function GetAll($sql, $aValues = array());
/**
* Runs a query and fetches results as a column.
*
* @param string $sql SQL Code to execute
*
* @return array $results Resultset
*/
public function GetCol($sql, $aValues = array());
/**
* Runs a query and returns results as a single cell.
*
* @param string $sql SQL to execute
*
* @return mixed $cellvalue result cell
*/
public function GetCell($sql, $aValues = array());
/**
* Runs a query and returns a flat array containing the values of
* one row.
*
* @param string $sql SQL to execute
*
* @return array $row result row
*/
public function GetRow($sql, $aValues = array());
/**
* Executes SQL code and allows key-value binding.
* This function allows you to provide an array with values to bind
* to query parameters. For instance you can bind values to question
* marks in the query. Each value in the array corresponds to the
* question mark in the query that matches the position of the value in the
* array. You can also bind values using explicit keys, for instance
* array(":key"=>123) will bind the integer 123 to the key :key in the
* SQL. This method has no return value.
*
* @param string $sql SQL Code to execute
* @param array $aValues Values to bind to SQL query
*
* @return void
*/
public function Execute($sql, $aValues = array());
/**
* Returns the latest insert ID if driver does support this
* feature.
*
* @return integer $id primary key ID
*/
public function GetInsertID();
/**
* Returns the number of rows affected by the most recent query
* if the currently selected driver driver supports this feature.
*
* @return integer $numOfRows number of rows affected
*/
public function Affected_Rows();
/**
* Toggles debug mode. In debug mode the driver will print all
* SQL to the screen together with some information about the
* results. All SQL code that passes through the driver will be
* passes on to the screen for inspection.
* This method has no return value.
*
* @param boolean $trueFalse turn on/off
*
* @return void
*/
public function setDebugMode($tf);
/**
* Starts a transaction.
* @return void
*/
public function CommitTrans();
/**
* Commits a transaction.
* @return void
*/
public function StartTrans();
/**
* Rolls back a transaction.
* @return void
*/
public function FailTrans();
}
class RedBean_Driver_PDO implements RedBean_Driver {
/**
* @var string
*/
protected $dsn;
/**
* @var boolean
*/
protected $debug = false;
/**
* @var RedBean_Logger
*/
protected $logger = NULL;
/**
* @var PDO
*/
protected $pdo;
/**
* @var integer
*/
protected $affected_rows;
/**
* @var integer
*/
protected $rs;
/**
* @var array
*/
protected $connectInfo = array();
/**
* @var bool
*/
public $flagUseStringOnlyBinding = false;
/**
* @var boolean
*/
protected $isConnected = false;
/**
* Constructor. You may either specify dsn, user and password or
* just give an existing PDO connection.
* Examples:
* $driver = new RedBean_Driver_PDO($dsn, $user, $password);
* $driver = new RedBean_Driver_PDO($existingConnection);
*
* @param string|PDO $dsn database connection string
* @param string $user optional, usename to sign in
* @param string $pass optional, password for connection login
*
* @return void
*/
public function __construct($dsn, $user = null, $pass = null) {
if ($dsn instanceof PDO) {
$this->pdo = $dsn;
$this->isConnected = true;
$this->pdo->setAttribute(1002, 'SET NAMES utf8');
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
// make sure that the dsn at least contains the type
$this->dsn = $this->getDatabaseType();
} else {
$this->dsn = $dsn;
$this->connectInfo = array('pass' => $pass, 'user' => $user);
}
}
/**
* Establishes a connection to the database using PHP PDO
* functionality. If a connection has already been established this
* method will simply return directly. This method also turns on
* UTF8 for the database and PDO-ERRMODE-EXCEPTION as well as
* PDO-FETCH-ASSOC.
*
* @return void
*/
public function connect() {
if ($this->isConnected) return;
try {
$user = $this->connectInfo['user'];
$pass = $this->connectInfo['pass'];
$this->pdo = new PDO(
$this->dsn,
$user,
$pass,
array(1002 => 'SET NAMES utf8',
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
)
);
$this->pdo->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, true);
$this->isConnected = true;
} catch(PDOException $e) {
throw new PDOException('Could not connect to database.');
}
}
/**
* Binds parameters. This method binds parameters to a PDOStatement for
* Query Execution. This method binds parameters as NULL, INTEGER or STRING
* and supports both named keys and question mark keys.
*
* @param PDOStatement $s PDO Statement instance
* @param array $aValues values that need to get bound to the statement
*
* @return void
*/
protected function bindParams($s, $aValues) {
foreach($aValues as $key => &$value) {
if (is_integer($key)) {
if (is_null($value)){
$s->bindValue($key+1, null, PDO::PARAM_NULL);
} elseif (!$this->flagUseStringOnlyBinding && RedBean_QueryWriter_AQueryWriter::canBeTreatedAsInt($value) && $value < 2147483648) {
$s->bindParam($key+1, $value, PDO::PARAM_INT);
} else {
$s->bindParam($key+1, $value, PDO::PARAM_STR);
}
} else {
if (is_null($value)){
$s->bindValue($key, null, PDO::PARAM_NULL);
} elseif (!$this->flagUseStringOnlyBinding && RedBean_QueryWriter_AQueryWriter::canBeTreatedAsInt($value) && $value < 2147483648) {
$s->bindParam($key, $value, PDO::PARAM_INT);
} else {
$s->bindParam($key, $value, PDO::PARAM_STR);
}
}
}
}
/**
* This method runs the actual SQL query and binds a list of parameters to the query.
* slots. The result of the query will be stored in the protected property
* $rs (always array). The number of rows affected (result of rowcount, if supported by database)
* is stored in protected property $affected_rows. If the debug flag is set
* this function will send debugging output to screen buffer.
*
* @throws RedBean_Exception_SQL
*
* @param string $sql the SQL string to be send to database server
* @param array $aValues the values that need to get bound to the query slots
*/
protected function runQuery($sql, $aValues) {
$this->connect();
if ($this->debug && $this->logger) {
$this->logger->log($sql, $aValues);
}
try {
if (strpos('pgsql', $this->dsn) === 0) {
$s = $this->pdo->prepare($sql, array(PDO::PGSQL_ATTR_DISABLE_NATIVE_PREPARED_STATEMENT => true));
} else {
$s = $this->pdo->prepare($sql);
}
$this->bindParams($s, $aValues);
$s->execute();
$this->affected_rows = $s->rowCount();
if ($s->columnCount()) {
$this->rs = $s->fetchAll();
if ($this->debug && $this->logger) $this->logger->log('resultset: '.count($this->rs).' rows');
} else {
$this->rs = array();
}
} catch(PDOException $e) {
//Unfortunately the code field is supposed to be int by default (php)
//So we need a property to convey the SQL State code.
$err = $e->getMessage();
if ($this->debug && $this->logger) $this->logger->log('An error occurred: '.$err);
$x = new RedBean_Exception_SQL($err, 0);
$x->setSQLState($e->getCode());
throw $x;
}
}
/**
* @see RedBean_Driver::GetAll
*/
public function GetAll($sql, $aValues = array()) {
$this->runQuery($sql, $aValues);
return $this->rs;
}
/**
* @see RedBean_Driver::GetCol
*/
public function GetCol($sql, $aValues = array()) {
$rows = $this->GetAll($sql, $aValues);
$cols = array();
if ($rows && is_array($rows) && count($rows)>0) {
foreach ($rows as $row) {
$cols[] = array_shift($row);
}
}
return $cols;
}
/**
* @see RedBean_Driver::GetCell
*/
public function GetCell($sql, $aValues = array()) {
$arr = $this->GetAll($sql, $aValues);
$row1 = array_shift($arr);
$col1 = array_shift($row1);
return $col1;
}
/**
* @see RedBean_Driver::GetRow
*/
public function GetRow($sql, $aValues = array()) {
$arr = $this->GetAll($sql, $aValues);
return array_shift($arr);
}
/**
* @see RedBean_Driver::Excecute
*/
public function Execute($sql, $aValues = array()) {
$this->runQuery($sql, $aValues);
return $this->affected_rows;
}
/**
* @see RedBean_Driver::GetInsertID
*/
public function GetInsertID() {
$this->connect();
return (int) $this->pdo->lastInsertId();
}
/**
* @see RedBean_Driver::Affected_Rows
*/
public function Affected_Rows() {
$this->connect();
return (int) $this->affected_rows;
}
/**
* Toggles debug mode. In debug mode the driver will print all
* SQL to the screen together with some information about the
* results.
*
* @param boolean $trueFalse turn on/off
* @param RedBean_Logger $logger
*
* @return void
*/
public function setDebugMode($tf, $logger = NULL) {
$this->connect();
$this->debug = (bool) $tf;
if ($this->debug and !$logger) $logger = new RedBean_Logger_Default();
$this->setLogger($logger);
}
/**
* Injects RedBean_Logger object.
*
* @param RedBean_Logger $logger
*/
public function setLogger(RedBean_Logger $logger) {
$this->logger = $logger;
}
/**
* Gets RedBean_Logger object.
*
* @return RedBean_Logger
*/
public function getLogger() {
return $this->logger;
}
/**
* @see RedBean_Driver::StartTrans
*/
public function StartTrans() {
$this->connect();
$this->pdo->beginTransaction();
}
/**
* @see RedBean_Driver::CommitTrans
*/
public function CommitTrans() {
$this->connect();
$this->pdo->commit();
}
/**
* @see RedBean_Driver::FailTrans
*/
public function FailTrans() {
$this->connect();
$this->pdo->rollback();
}
/**
* Returns the name of the database type/brand: i.e. mysql, db2 etc.
*
* @return string $typeName database identification
*/
public function getDatabaseType() {
$this->connect();
return $this->pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
}
/**
* Returns the version number of the database.
*
* @return mixed $version version number of the database
*/
public function getDatabaseVersion() {
$this->connect();
return $this->pdo->getAttribute(PDO::ATTR_CLIENT_VERSION);
}
/**
* Returns the underlying PHP PDO instance.
*
* @return PDO $pdo PDO instance used by PDO wrapper
*/
public function getPDO() {
$this->connect();
return $this->pdo;
}
/**
* Closes database connection by destructing PDO.
*/
public function close() {
$this->pdo = null;
$this->isConnected = false;
}
/**
* Returns TRUE if the current PDO instance is connected.
*
* @return boolean $yesNO
*/
public function isConnected() {
if (!$this->isConnected && !$this->pdo) return false;
return true;
}
}
class RedBean_OODBBean implements IteratorAggregate, ArrayAccess, Countable {
/**
* @var boolean
*/
private static $flagUseBeautyfulColumnnames = true;
/**
* @var array
*/
private static $beautifulColumns = array();
/**
* @var boolean
*/
private static $flagKeyedExport = false;
/**
* @var boolean
*/
private $flagSkipBeau = false;
/**
* @var array $properties
*/
private $properties = array();
/**
* @var array
*/
private $__info = array();
/**
* @var RedBean_BeanHelper
*/
private $beanHelper = NULL;
/**
* @var null
*/
private $fetchType = NULL;
/**
* @var string
*/
private $withSql = '';
/**
* @var array
*/
private $withParams = array();
/**
* @var string
*/
private $aliasName = NULL;
/**
* By default own-lists and shared-lists no longer have IDs as keys (3.3+),
* this is because exportAll also does not offer this feature and we want the
* ORM to be more consistent. Also, exporting without keys makes it easier to
* export lists to Javascript because unlike in PHP in JS arrays will fill up gaps.
*
* @var boolean $yesNo
*/
public static function setFlagKeyedExport($flag) {
self::$flagKeyedExport = (boolean) $flag;
}
/**
* Flag indicates whether column names with CamelCase are supported and automatically
* converted; example: isForSale -> is_for_sale
*
* @param boolean
*/
public static function setFlagBeautifulColumnNames($flag) {
self::$flagUseBeautyfulColumnnames = (boolean) $flag;
}
/** Returns the alias for a type
*
* @param $type aliased type
*
* @return string $type type
*/
private function getAlias($type) {
if ($this->fetchType) {
$type = $this->fetchType;
$this->fetchType = null;
}
return $type;
}
/**
* Sets the Bean Helper. Normally the Bean Helper is set by OODB.
* Here you can change the Bean Helper. The Bean Helper is an object
* providing access to a toolbox for the bean necessary to retrieve
* nested beans (bean lists: ownBean, sharedBean) without the need to
* rely on static calls to the facade (or make this class dep. on OODB).
*
* @param RedBean_IBeanHelper $helper
*
* @return void
*/
public function setBeanHelper(RedBean_BeanHelper $helper) {
$this->beanHelper = $helper;
}
/**
* Returns an ArrayIterator so you can treat the bean like
* an array with the properties container as its contents.
*
* @return ArrayIterator $arrayIt an array iterator instance with $properties
*/
public function getIterator() {
return new ArrayIterator($this->properties);
}
/**
* Imports all values from an associative array $array. Chainable.
*
* @param array $array what you want to import
* @param string|array $selection selection of values
* @param boolean $notrim if TRUE values will not be trimmed
*
* @return RedBean_OODBBean $this
*/
public function import($arr, $selection = false, $notrim = false) {
if (is_string($selection)) {
$selection = explode(',', $selection);
}
if (!$notrim && is_array($selection)) foreach($selection as $k => $s){ $selection[$k] = trim($s); }
foreach($arr as $k => $v) {
if ($k != '__info') {
if (!$selection || ($selection && in_array($k, $selection))) {
$this->$k = $v;
}
}
}
return $this;
}
/**
* Imports data from another bean. Chainable.
*
* @param RedBean_OODBBean $sourceBean the source bean to take properties from
*
* @return RedBean_OODBBean $self
*/
public function importFrom(RedBean_OODBBean $sourceBean) {
$this->__info['tainted'] = true;
$array = $sourceBean->properties;
$this->properties = $array;
return $this;
}
/**
* Injects the properties of another bean but keeps the original ID.
* Just like import() but keeps the original ID.
* Chainable.
*
* @param RedBean_OODBBean $otherBean the bean whose properties you would like to copy
*
* @return RedBean_OODBBean $self
*/
public function inject(RedBean_OODBBean $otherBean) {
$myID = $this->id;
$array = $otherBean->export();
$this->import($array);
$this->id = $myID;
return $this;
}
/**
* Exports the bean as an array.
* This function exports the contents of a bean to an array and returns
* the resulting array.
*
* @param boolean $meta set to TRUE if you want to export meta data as well
* @param boolean $parents set to TRUE if you want to export parents as well
* @param boolean $onlyMe set to TRUE if you want to export only this bean
* @param array $filters optional whitelist for export
*
* @return array $arr
*/
public function export($meta = false, $parents = false, $onlyMe = false, $filters = array()) {
$arr = array();
if ($parents) {
foreach($this as $k => $v) {
if (substr($k, -3) == '_id') {
$prop = substr($k, 0, strlen($k)-3);
$this->$prop;
}
}
}
foreach($this as $k => $v) {
if (!$onlyMe && is_array($v)) {
$vn = array();
foreach($v as $i => $b) {
if (is_numeric($i) && !self::$flagKeyedExport) {
$vn[] = $b->export($meta, false, false, $filters);
} else {
$vn[$i] = $b->export($meta, false, false, $filters);
}
$v = $vn;
}
} elseif ($v instanceof RedBean_OODBBean) {
if (is_array($filters) && count($filters) && !in_array(strtolower($v->getMeta('type')), $filters)) {
continue;
}
$v = $v->export($meta, $parents, false, $filters);
}
$arr[$k] = $v;
}
if ($meta) $arr['__info'] = $this->__info;
return $arr;
}
/**
* Exports the bean to an object.
*
* @param object $obj target object
*
* @return array $arr
*/
public function exportToObj($obj) {
foreach($this->properties as $k => $v) {
if (!is_array($v) && !is_object($v))
$obj->$k = $v;
}
}
/**
* Implements isset() function for use as an array.
*
* @param string $property name of the property you want to check
*
* @return boolean
*/
public function __isset($property) {
return (isset($this->properties[$property]));
}
/**
* Returns the ID of the bean no matter what the ID field is.
*
* @return string $id record Identifier for bean
*/
public function getID() {
return (string) $this->id;
}
/**
* Unsets a property. This method will load the property first using
* __get.
*
* @param string $property property
*
* @return void
*/
public function __unset($property) {
$this->__get($property);
$fieldLink = $property.'_id';
if (isset($this->$fieldLink)) {
//wanna unset a bean reference?
$this->$fieldLink = null;
}
if ((isset($this->properties[$property]))) {
unset($this->properties[$property]);
}
}
/**
* Removes a property from the properties list without invoking
* an __unset on the bean.
*
* @param string $property property that needs to be unset
*
* @return void
*/
public function removeProperty($property) {
unset($this->properties[$property]);
}
/**
* Adds WHERE clause conditions to ownList retrieval.
* For instance to get the pages that belong to a book you would
* issue the following command: $book->ownPage
* However, to order these pages by number use:
*
* $book->with(' ORDER BY `number` ASC ')->ownPage
*
* the additional SQL snippet will be merged into the final
* query.
*
* @param string|RedBean_SQLHelper $sql SQL to be added to retrieval query.
* @param array $params array with parameters to bind to SQL snippet
*
* @return RedBean_OODBBean $self
*/
public function with($sql, $params = array()) {
if ($sql instanceof RedBean_SQLHelper) {
list($this->withSql, $this->withParams) = $sql->getQuery();
} else {
$this->withSql = $sql;
$this->withParams = $params;
}
return $this;
}
/**
* Just like with(). Except that this method prepends the SQL query snippet
* with AND which makes it slightly more comfortable to use a conditional
* SQL snippet. For instance to filter an own-list with pages (belonging to
* a book) on specific chapters you can use:
*
* $book->withCondition(' chapter = 3 ')->ownPage
*
* This will return in the own list only the pages having 'chapter == 3'.
*
* @param string|RedBean_SQLHelper $sql SQL to be added to retrieval query (prefixed by AND)
* @param array $params array with parameters to bind to SQL snippet
*
* @return RedBean_OODBBean $self
*/
public function withCondition($sql, $params = array()) {
if ($sql instanceof RedBean_SQLHelper) {
list($sql, $params) = $sql->getQuery();
}
$this->withSql = ' AND '.$sql;
$this->withParams = $params;
return $this;
}
/**
* Prepares an own-list to use an alias. This is best explained using
* an example. Imagine a project and a person. The project always involves
* two persons: a teacher and a student. The person beans have been aliased in this
* case, so to the project has a teacher_id pointing to a person, and a student_id
* also pointing to a person. Given a project, we obtain the teacher like this:
*
* $project->fetchAs('person')->teacher;
*
* Now, if we want all projects of a teacher we cant say:
*
* $teacher->ownProject
*
* because the $teacher is a bean of type 'person' and no project has been
* assigned to a person. Instead we use the alias() method like this:
*
* $teacher->alias('teacher')->ownProject
*
* now we get the projects associated with the person bean aliased as
* a teacher.
*
* @param string $aliasName the alias name to use
*
* @return RedBean_OODBBean
*/
public function alias($aliasName) {
$this->aliasName = $aliasName;
return $this;
}
/**
* Turns a camelcase property name into an underscored property name.
* Examples:
* oneACLRoute -> one_acl_route
* camelCase -> camel_case
*
* Also caches the result to improve performance.
*
* @param string $property
*
* @return string
*/
public function beau($property) {
if (strpos($property, 'own') !== 0 && strpos($property, 'shared') !== 0) {
if (isset(self::$beautifulColumns[$property])) {
$propertyBeau = self::$beautifulColumns[$property];
} else {
$propertyBeau = strtolower(preg_replace('/(?<=[a-z])([A-Z])|([A-Z])(?=[a-z])/', '_$1$2', $property));
self::$beautifulColumns[$property] = $propertyBeau;
}
return $propertyBeau;
} else {
return $property;
}
}
/**
* Magic Getter. Gets the value for a specific property in the bean.
* If the property does not exist this getter will make sure no error
* occurs. This is because RedBean allows you to query (probe) for
* properties. If the property can not be found this method will
* return NULL instead.
* @param string $property
* @return mixed $value
*/
public function &__get($property) {
if (self::$flagUseBeautyfulColumnnames && !$this->flagSkipBeau) {
$property = $this->beau($property);
}
if ($this->beanHelper) {
$toolbox = $this->beanHelper->getToolbox();
$redbean = $toolbox->getRedBean();
}
if ($this->withSql !== '') {
if (strpos($property, 'own') === 0) {
unset($this->properties[$property]);
}
}
if (!isset($this->properties[$property])) {
$fieldLink = $property.'_id';
if (isset($this->$fieldLink) && $fieldLink !== $this->getMeta('sys.idfield')) {
$this->__info['tainted'] = true;
$bean = $this->getMeta('sys.parentcache.'.$property);
if (!$bean) {
$type = $this->getAlias($property);
$targetType = $this->properties[$fieldLink];
$bean = $redbean->load($type, $targetType);
}
$this->properties[$property] = $bean;
return $this->properties[$property];
}
elseif (strpos($property, 'own') === 0 && ctype_upper(substr($property, 3, 1))) {
$type = lcfirst(substr($property, 3));
if (self::$flagUseBeautyfulColumnnames) {
$type = $this->beau($type);
}
if ($this->aliasName) {
$parentField = $this->aliasName;
$myFieldLink = $this->aliasName.'_id';
$this->__info['sys.alias.'.$type] = $this->aliasName;
$this->aliasName = null;
} else {
$myFieldLink = $this->__info['type'].'_id';
$parentField = $this->__info['type'];
}
$beans = array();
if ($this->getID()>0) {
$params = array_merge(array($this->getID()), $this->withParams);
$beans = $redbean->find($type, array(), array(" $myFieldLink = ? ".$this->withSql, $params));
}
$this->withSql = '';
$this->withParams = array();
foreach($beans as $b) {
$b->__info['sys.parentcache.'.$parentField] = $this;
}
$this->properties[$property] = $beans;
$this->__info['sys.shadow.'.$property] = $beans;
$this->__info['tainted'] = true;
return $this->properties[$property];
}
elseif (strpos($property, 'shared') === 0 && ctype_upper(substr($property, 6, 1))) {
$type = lcfirst(substr($property, 6));
if (self::$flagUseBeautyfulColumnnames ) {
$type = $this->beau($type);
}
$keys = $redbean->getAssociationManager()->related($this, $type);
if (!count($keys)) $beans = array(); else
if (trim($this->withSql) !== '') {
$beans = $redbean->find($type, array('id' => $keys), array($this->withSql, $this->withParams), true);
} else {
$beans = $redbean->batch($type, $keys);
}
$this->withSql = '';
$this->withParams = array();
$this->properties[$property] = $beans;
$this->__info['sys.shadow.'.$property] = $beans;
$this->__info['tainted'] = true;
return $this->properties[$property];
} else {
$null = null;
return $null;
}
} else {
return $this->properties[$property];
}
}
/**
* Magic Setter. Sets the value for a specific property.
* This setter acts as a hook for OODB to mark beans as tainted.
* The tainted meta property can be retrieved using getMeta("tainted").
* The tainted meta property indicates whether a bean has been modified and
* can be used in various caching mechanisms.
* @param string $property
* @param mixed $value
*/
public function __set($property, $value) {
if (self::$flagUseBeautyfulColumnnames) {
$property = $this->beau($property);
}
$this->flagSkipBeau = true;
$this->__get($property);
$this->flagSkipBeau = false;
$this->setMeta('tainted', true);
$linkField = $property.'_id';
if (isset($this->properties[$linkField]) && !($value instanceof RedBean_OODBBean)) {
if (is_null($value) || $value === false) {
return $this->__unset($property);
} else {
throw new RedBean_Exception_Security('Cannot cast to bean.');
}
}
if ($value === false) {
$value = '0';
} elseif ($value === true) {
$value = '1';
} elseif ($value instanceof DateTime) {
$value = $value->format('Y-m-d H:i:s');
}
$this->properties[$property] = $value;
}
/**
* Sets a property directly, for internal use only.
*
* @param string $property property
* @param mixed $value value
*/
public function setProperty($property, $value) {
$this->properties[$property] = $value;
}
/**
* Returns the value of a meta property. A meta property
* contains extra information about the bean object that will not
* get stored in the database. Meta information is used to instruct
* RedBean as well as other systems how to deal with the bean.
* For instance: $bean->setMeta("buildcommand.unique", array(
* array("column1", "column2", "column3") ) );
* Will add a UNIQUE constaint for the bean on columns: column1, column2 and
* column 3.
* To access a Meta property we use a dot separated notation.
* If the property cannot be found this getter will return NULL instead.
*
* @param string $path path
* @param mixed $default default value
*
* @return mixed $value
*/
public function getMeta($path, $default = NULL) {
return (isset($this->__info[$path])) ? $this->__info[$path] : $default;
}
/**
* Stores a value in the specified Meta information property. $value contains
* the value you want to store in the Meta section of the bean and $path
* specifies the dot separated path to the property. For instance "my.meta.property".
* If "my" and "meta" do not exist they will be created automatically.
*
* @param string $path path
* @param mixed $value value
*/
public function setMeta($path, $value) {
$this->__info[$path] = $value;
}
/**
* Copies the meta information of the specified bean
* This is a convenience method to enable you to
* exchange meta information easily.
*
* @param RedBean_OODBBean $bean
*
* @return RedBean_OODBBean
*/
public function copyMetaFrom(RedBean_OODBBean $bean) {
$this->__info = $bean->__info;
return $this;
}
/**
* Reroutes a call to Model if exists. (new fuse)
*
* @param string $method
* @param array $args
*
* @return mixed $mixed
*/
public function __call($method, $args) {
if (!isset($this->__info['model'])) {
$model = $this->beanHelper->getModelForBean($this);
if (!$model) return;
$this->__info['model'] = $model;
}
if (!method_exists($this->__info['model'], $method)) return null;
return call_user_func_array(array($this->__info['model'], $method), $args);
}
/**
* Implementation of __toString Method
* Routes call to Model.
*
* @return string $string
*/
public function __toString() {
$string = $this->__call('__toString', array());
if ($string === null) {
return json_encode($this->properties);
} else {
return $string;
}
}
/**
* Implementation of Array Access Interface, you can access bean objects
* like an array.
* Call gets routed to __set.
*
* @param mixed $offset offset string
* @param mixed $value value