Compare commits

..
10 Commits
Author SHA1 Message Date
ahwelp c2f00d6c21 Changes 2023-04-25 18:09:41 +00:00
Artur Welp 7b2f03e139 Atualizar 'composer.json' 2023-02-07 13:25:12 +00:00
ahwelp 94793fa252 First steps to fix the softdelete issue 2023-01-24 13:33:59 +00:00
ahwelp 2bfd6ec104 First steps to fix the softdelete issue 2023-01-24 13:33:27 +00:00
ahwelp bfab5fc27e Changing $data param to be a array for default 2023-01-24 13:32:46 +00:00
ahwelp 5f9316e15e Adding each method 2023-01-24 13:32:08 +00:00
ahwelp 0a768bb649 Mudanças 2022-04-05 20:04:28 +00:00
ahwelp 477f3696ba Mudanças 2022-04-05 20:03:21 +00:00
Your Name 5835106252 Mudanças 2022-03-29 16:14:12 +00:00
ahwelp 1669a4279d Changes 2022-03-23 22:01:58 +00:00
7 changed files with 292 additions and 169 deletions
+1 -1
View File
@@ -1,5 +1,5 @@
{ {
"name" : "urfat/orm", "name" : "inforsistemas/orm",
"description" : "Diferent ORM", "description" : "Diferent ORM",
"type" : "library", "type" : "library",
"authors" : [ "authors" : [
+10 -1
View File
@@ -16,7 +16,16 @@ class BelongsTo {
$this->localElement = $localElement; $this->localElement = $localElement;
} }
public function __call($name, $arguments)
{
return $this->get()->$name($arguments);
}
public function __get($key)
{
return $this->get()->$key;
}
function get() { function get() {
return $this->foreignObject::findOne(Array($this->remoteField => Array('=', $this->localElement->{$this->localField}))); return $this->foreignObject::findOne(Array($this->remoteField => Array('=', $this->localElement->{$this->localField})));
} }
+10 -10
View File
@@ -22,28 +22,28 @@ class BelongsToMany {
$this->remoteLimit = $remoteLimit; $this->remoteLimit = $remoteLimit;
} }
function get() { function get() : Collection {
$limitsSql = ''; $limitsSql = '';
foreach ($this->remoteLimit as $key => $value) { foreach ($this->remoteLimit as $key => $value) {
$limitsSql .= "$key $value "; $limitsSql .= "$key $value ";
} }
$pivotTable = '{' . $this->pivotTable . '}'; $pivotTable = '{' . $this->pivotTable . '}';
$sql = "SELECT $this->remoteInPivot FROM $pivotTable WHERE $this->localInPivot = ? $limitsSql"; $sql = "SELECT $this->remoteInPivot FROM $pivotTable WHERE $this->localInPivot = ? $limitsSql";
$relations = DBInstance::query($sql, Array($this->localObject->id), $this->localObject::_connectionName); $relations = DBInstance::query($sql, Array($this->localObject->id), $this->localObject::_connectionName);
$ids = Array(); $ids = Array();
foreach ($relations as $relation) { foreach ($relations as $relation) {
$ids[] = $relation->{$this->remoteInPivot}; $ids[] = $relation->{$this->remoteInPivot};
} }
if (empty($ids)) { if (empty($ids)) {
return Array(); return new Collection();
} }
return $this->foreignObject::findMany(array_merge(Array('id' => Array('IN', $ids)), $this->remoteFilter), Array('*'), $this->remoteLimit); return $this->foreignObject::findMany(array_merge(Array('id' => Array('IN', $ids)), $this->remoteFilter), Array('*'), $this->remoteLimit);
} }
} }
+24 -14
View File
@@ -11,8 +11,9 @@ class BelongsToManyExtended {
private $remoteInPivot; private $remoteInPivot;
private $remoteFilter; private $remoteFilter;
private $remoteLimit; private $remoteLimit;
private $softDelete;
function __construct($localObject, $foreignObject, $pivotTable, $localInPivot, $remoteInPivot, $remoteFilter = Array(), $remoteLimit = Array()) { function __construct($localObject, $foreignObject, $pivotTable, $localInPivot, $remoteInPivot, $remoteFilter = Array(), $remoteLimit = Array(), $softDelete) {
$this->localObject = $localObject; $this->localObject = $localObject;
$this->foreignObject = $foreignObject; $this->foreignObject = $foreignObject;
$this->pivotTable = $pivotTable; $this->pivotTable = $pivotTable;
@@ -20,33 +21,42 @@ class BelongsToManyExtended {
$this->remoteInPivot = $remoteInPivot; $this->remoteInPivot = $remoteInPivot;
$this->remoteFilter = $remoteFilter; $this->remoteFilter = $remoteFilter;
$this->remoteLimit = $remoteLimit; $this->remoteLimit = $remoteLimit;
$this->softDelete = $softDelete;
} }
function get(){ function get() : Collection {
$limitsSql = ''; $limitsSql = '';
foreach ($this->remoteLimit as $key => $value) { foreach ($this->remoteLimit as $key => $value) {
$limitsSql .= "$key $value "; $limitsSql .= "$key $value ";
} }
$pivotTable = '{' . $this->pivotTable . '}'; $pivotTable = '{' . $this->pivotTable . '}';
$sql = "SELECT * FROM $pivotTable WHERE $this->localInPivot = ? $limitsSql";
$sql = '';
$relations = DBInstance::query($sql, Array($this->localObject->id), $this->localObject::_connectionName); if($this->softDelete){
$objects = Array(); $sql = "SELECT * FROM $pivotTable WHERE $this->localInPivot = ? AND deleted_at IS NULL $limitsSql";
} else {
$sql = "SELECT * FROM $pivotTable WHERE $this->localInPivot = ? $limitsSql";
}
$relations = DBInstance::query($sql, Array($this->localObject->id), $this->localObject::_connectionName);
$objects = new Collection();
if (empty($relations)) { if (empty($relations)) {
return Array(); return new Collection();
} }
foreach ($relations as $relation) { foreach ($relations as $relation) {
$relation->childElement = $this->foreignObject::findOne(array_merge(Array("id" => Array("=", $relation->{$this->remoteInPivot})), $this->remoteFilter)); $relation->childElement = $this->foreignObject::findOne(array_merge(Array("id" => Array("=", $relation->{$this->remoteInPivot})), $this->remoteFilter));
$objects[] = $relation; $objects[] = $relation;
} }
if (empty($objects)) { if (empty($objects)) {
return Array(); return new Collection();
} }
return $objects; return $objects;
} }
+21 -9
View File
@@ -26,13 +26,11 @@ class Collection implements \Countable, \IteratorAggregate, \ArrayAccess
} }
// https://www.php.net/manual/en/class.iteratoraggregate.php // https://www.php.net/manual/en/class.iteratoraggregate.php
public function getIterator() public function getIterator(): \Generator
{ {
return (function () { foreach ($this->items as $key => $val) {
while (list($key, $val) = each($this->items)) { yield $key => $val;
yield $key => $val; }
}
})();
} }
// https://www.php.net/manual/en/class.arrayaccess.php // https://www.php.net/manual/en/class.arrayaccess.php
@@ -79,7 +77,6 @@ class Collection implements \Countable, \IteratorAggregate, \ArrayAccess
// Collection specific methods // Collection specific methods
// //
function get($forceCollection = false) function get($forceCollection = false)
{ {
if (sizeof($this->items) == 1 && !$forceCollection) { if (sizeof($this->items) == 1 && !$forceCollection) {
@@ -100,11 +97,13 @@ class Collection implements \Countable, \IteratorAggregate, \ArrayAccess
switch (get_class($relation)) { switch (get_class($relation)) {
case 'ORM\HasMany': case 'ORM\HasMany':
$this->items[$key]->$connection = $this->items[$key]->$connection()->get();
break; break;
case 'ORM\HasOne': case 'ORM\HasOne':
$this->items[$key]->$connection = $this->items[$key]->$connection()->get();
break; break;
case 'ORM\BelongsTo': case 'ORM\BelongsTo':
$searchs['belongsTo'][] = []; $this->items[$key]->$connection = $this->items[$key]->$connection()->get();
break; break;
case 'ORM\BelongsToMany': case 'ORM\BelongsToMany':
$this->items[$key]->$connection = $this->items[$key]->$connection()->get(); $this->items[$key]->$connection = $this->items[$key]->$connection()->get();
@@ -119,7 +118,7 @@ class Collection implements \Countable, \IteratorAggregate, \ArrayAccess
} }
} }
return $this->items; return $this;
} }
function first() function first()
@@ -128,4 +127,17 @@ class Collection implements \Countable, \IteratorAggregate, \ArrayAccess
return $this->items[0]; return $this->items[0];
} }
} }
/**
* Iterate over the colletion
*
* @param mixed $function
* @return void
*/
function each($function)
{
foreach($this->items as $item){
$function($item);
}
}
} }
+83 -53
View File
@@ -2,10 +2,19 @@
namespace ORM; namespace ORM;
/**
* Summary of DBInstance
*/
class DBInstance class DBInstance
{ {
private static function addPrefix($sql, $instance = 'default') /**
* Summary of addPrefix
* @param string $sql
* @param string $instance
* @return string
*/
private static function addPrefix(string $sql, string $instance = 'default')
{ {
$con = Connections::getConnection($instance); $con = Connections::getConnection($instance);
@@ -25,14 +34,11 @@ class DBInstance
* *
* This method will execute a SQL on the database * This method will execute a SQL on the database
* *
* @ctag DBInstance::execute($sql); * @param string $sql The SQL to be executed
* @ctag DBInstance::execute($sql, []); * @param array $data Pass the info to be replaced on the query_prepare
* * @param string $instance Select the connection to execute
* @param String $sql The SQL to be executed
* @param Array $data Pass the info to be replaced on the query_prepare
* @param String $instance Select the connection to execute
*/ */
public static function execute($sql, $data = null, $instance = 'default') public static function execute(string $sql, Array $data = null, string $instance = 'default')
{ {
$sql = self::addPrefix($sql, $instance); $sql = self::addPrefix($sql, $instance);
if ($data) { if ($data) {
@@ -43,12 +49,12 @@ class DBInstance
} }
} }
/* /**
* * Summary of lastInsert
* @ctag DBInstance::lastInsert(); * @param string $instance
* @return mixed
*/ */
public static function lastInsert(string $instance = 'default')
public static function lastInsert($instance = 'default')
{ {
$con = Connections::getConnection($instance); $con = Connections::getConnection($instance);
return $con->lastInsertId(); return $con->lastInsertId();
@@ -62,11 +68,11 @@ class DBInstance
* @ctag DBInstance::query($sql); * @ctag DBInstance::query($sql);
* @ctag DBInstance::query($sql, []); * @ctag DBInstance::query($sql, []);
* *
* @param String $sql The SQL to be executed * @param string $sql The SQL to be executed
* @param Array $data Pass the info to be replaced on the query_prepare * @param array $data Pass the info to be replaced on the query_prepare
* @param String $instance Select the connection to execute * @param string $instance Select the connection to execute
* *
* @return pointer A pointer for a foreach loop * @return mixed A pointer for a foreach loop
*/ */
public static function query($sql, $data = null, $instance = 'default') public static function query($sql, $data = null, $instance = 'default')
{ {
@@ -75,8 +81,12 @@ class DBInstance
if ($data) { if ($data) {
return self::queryPrepare($sql, $data, $instance); return self::queryPrepare($sql, $data, $instance);
} else { } else {
$con = Connections::getConnection($instance); try {
return $con->query($sql, \PDO::FETCH_OBJ); $con = Connections::getConnection($instance);
return $con->query($sql, \PDO::FETCH_OBJ);
} catch (\Throwable $th) {
ddd($sql);
}
} }
} }
@@ -88,14 +98,15 @@ class DBInstance
* *
* This method will execute a SQL and return the first featched register * This method will execute a SQL and return the first featched register
* *
* @param String $sql The SQL to be executed * @param string $sql The SQL to be executed
* @param Array $data Pass the info to be replaced on the query_prepare * @param array $data Pass the info to be replaced on the query_prepare
* @param String $instance Select the connection to execute * @param string $instance Select the connection to execute
* *
* @return stdClass A object with the record info * @return \stdClass A object with the record info
*/ */
public static function queryOne($sql, $data = null, $instance = 'default') public static function queryOne(string $sql, Array $data = null, string $instance = 'default')
{ {
$sql = self::addPrefix($sql, $instance); $sql = self::addPrefix($sql, $instance);
if ($data) { if ($data) {
@@ -115,12 +126,12 @@ class DBInstance
* @ctag DBInstance::getRecord($table, []); * @ctag DBInstance::getRecord($table, []);
* @ctag DBInstance::getRecord($table, [], []); * @ctag DBInstance::getRecord($table, [], []);
* *
* @param String $table The table to be searched * @param string $table The table to be searched
* @param Array $data Pass the info to be replaced on the query_prepare * @param array $data Pass the info to be replaced on the query_prepare
* @param Array $select Info to be put on the SELECT part of the query * @param array $select Info to be put on the SELECT part of the query
* @param String $instance Select the connection to execute * @param string $instance Select the connection to execute
* *
* @return stdClass A object with the record info * @return mixed A object with the record info
*/ */
public static function getRecord($table, $data = array(), $select = array('*'), $instance = 'default') public static function getRecord($table, $data = array(), $select = array('*'), $instance = 'default')
{ {
@@ -166,11 +177,11 @@ class DBInstance
* @ctag DBInstance::getRecordSql($sql); * @ctag DBInstance::getRecordSql($sql);
* @ctag DBInstance::getRecordSql($sql, []); * @ctag DBInstance::getRecordSql($sql, []);
* *
* @param String $sql The SQL to be executed * @param string $sql The SQL to be executed
* @param Array $data Pass the info to be replaced on the query_prepare * @param array $data Pass the info to be replaced on the query_prepare
* @param String $instance Select the connection to execute * @param string $instance Select the connection to execute
* *
* @return stdClass A object with the record info * @return mixed A object with the record info
*/ */
public static function getRecordSql($sql, $data = null, $instance = 'default') public static function getRecordSql($sql, $data = null, $instance = 'default')
{ {
@@ -192,14 +203,14 @@ class DBInstance
* @ctag DBInstance::getRecords($table); * @ctag DBInstance::getRecords($table);
* @ctag DBInstance::getRecords($table, []); * @ctag DBInstance::getRecords($table, []);
* *
* @param String $table The table to be searched * @param string $table The table to be searched
* @param Array $data Pass the info to be replaced on the query_prepare * @param array $data Pass the info to be replaced on the query_prepare
* @param Array $select Info to be put on the SELECT part of the query * @param array $select Info to be put on the SELECT part of the query
* @param String $instance Select the connection to execute * @param string $instance Select the connection to execute
* *
* @return stdClass A object with the record info * @return array A object with the record info
*/ */
public static function getRecords($table, $data = null, $select = array('*'), $limits = array(), $instance = 'default') public static function getRecords($table, $data = array(), $select = array('*'), $limits = array(), $instance = 'default')
{ {
$pointer = self::getRecordsPointer($table, $data, $select, $limits, $instance); $pointer = self::getRecordsPointer($table, $data, $select, $limits, $instance);
@@ -219,12 +230,12 @@ class DBInstance
* @ctag DBInstance::getRecordsPointer($table); * @ctag DBInstance::getRecordsPointer($table);
* @ctag DBInstance::getRecordsPointer($table, []); * @ctag DBInstance::getRecordsPointer($table, []);
* *
* @param String $table The table to be searched * @param string $table The table to be searched
* @param Array $data Pass the info to be replaced on the query_prepare * @param array $data Pass the info to be replaced on the query_prepare
* @param Array $select Info to be put on the SELECT part of the query * @param array $select Info to be put on the SELECT part of the query
* @param String $instance Select the connection to execute * @param string $instance Select the connection to execute
* *
* @return stdClass A object with the record info * @return mixed A object with the record info
*/ */
public static function getRecordsPointer($table, $data = array(), $select = array('*'), $limits = array(), $instance = 'default') public static function getRecordsPointer($table, $data = array(), $select = array('*'), $limits = array(), $instance = 'default')
{ {
@@ -276,11 +287,11 @@ class DBInstance
* @ctag DBInstance::getRecordsSql($sql); * @ctag DBInstance::getRecordsSql($sql);
* @ctag DBInstance::getRecordsSql($sql, []); * @ctag DBInstance::getRecordsSql($sql, []);
* *
* @param String $sql The SQL to be executed * @param string $sql The SQL to be executed
* @param Array $data Pass the info to be replaced on the query_prepare * @param array $data Pass the info to be replaced on the query_prepare
* @param String $instance Select the connection to execute * @param string $instance Select the connection to execute
* *
* @return Array Array with objects representing the database data * @return array Array with objects representing the database data
*/ */
public static function getRecordsSql($sql, $data = null, $instance = 'default') public static function getRecordsSql($sql, $data = null, $instance = 'default')
{ {
@@ -301,6 +312,13 @@ class DBInstance
return $elements; return $elements;
} }
/**
* Summary of insertRecord
* @param string $table
* @param array $data
* @param string $connection
* @return void
*/
public static function insertRecord($table, $data = array(), $connection = 'default') public static function insertRecord($table, $data = array(), $connection = 'default')
{ {
@@ -329,12 +347,24 @@ class DBInstance
DBInstance::execute($sql, $insert_data, $connection); DBInstance::execute($sql, $insert_data, $connection);
} }
/**
* Summary of queryPrepare
* @param string $sql
* @param array $data
* @param string $instance
* @return mixed
*/
public static function queryPrepare($sql, $data = array(), $instance = 'default') public static function queryPrepare($sql, $data = array(), $instance = 'default')
{ {
$sql = self::addPrefix($sql, $instance); try {
$con = Connections::getConnection($instance); $sql = self::addPrefix($sql, $instance);
$statement = $con->prepare($sql); $con = Connections::getConnection($instance);
$statement->execute($data); $statement = $con->prepare($sql);
return $statement->fetchAll(\PDO::FETCH_OBJ); $statement->execute($data);
return $statement->fetchAll(\PDO::FETCH_OBJ);
} catch (\Throwable $th) {
error_log('adsdsadsadsa');
}
} }
} }
+143 -81
View File
@@ -15,7 +15,8 @@ abstract class Entity {
'_timestamps', '_timestamps',
'_softdelete', '_softdelete',
'_tableName', '_tableName',
'_idPolice' '_idPolice',
'_ignore'
); );
const _properties = Array(); const _properties = Array();
@@ -27,11 +28,19 @@ abstract class Entity {
*/ */
const _idPolice = Array(); const _idPolice = Array();
function __construct() { function __construct($assignment = '') {
@$this->_ignore = array_merge((array) $this->_ignore, self::_ignore);
if (isset($this->_timestamps) && $this->_timestamps) { if (isset($this->_timestamps) && $this->_timestamps) {
$this->created_at = date('Y-m-d h:m:s'); $this->created_at = date('Y-m-d h:m:s');
$this->updated_at = date('Y-m-d h:m:s'); $this->updated_at = date('Y-m-d h:m:s');
} }
// Mass Assign
if(is_array($assignment)){
$this->charge($assignment);
}
} }
public function __set($property, $value) { public function __set($property, $value) {
@@ -42,10 +51,18 @@ abstract class Entity {
} }
public function __get($key) { public function __get($key) {
// The __get might be a connection. So return it
if(method_exists($this, $key)){
return $this->$key();
}
// Empty is bad for this kind of dynamicity
if (!isset($this->$key)) { if (!isset($this->$key)) {
return 0; return 0;
} }
return $this->toArray()[$key];
// There is a key. So return it
return $this->$key;
} }
public function __toString() { public function __toString() {
@@ -58,8 +75,29 @@ abstract class Entity {
return static::class; return static::class;
} }
/*public function __call($name, $arguments){
dd($name);
}*/
public function charge($payload) { public function charge($payload) {
foreach (static::_properties as $key => $property) {
$properties = [];
foreach( get_object_vars($this) as $key => $property){
if(substr($key, 0, 1) != '_'){
$properties[] = $key;
}
}
$elements = array_diff(array_merge($properties, static::_properties), self::_ignore);
foreach ($elements as $key => $property) {
if ($property == 'id' && !isset($payload[$property])) {
continue;
}
if(empty($payload[$property])){
continue;
}
$this->$property = $payload[$property]; $this->$property = $payload[$property];
} }
return []; return [];
@@ -99,6 +137,10 @@ abstract class Entity {
$update_data = Array(); $update_data = Array();
$update_data['_update_id'] = $this->id; $update_data['_update_id'] = $this->id;
if (isset($this->_timestamps) && $this->_timestamps) {
$this->updated_at = date('Y-m-d h:m:s');
}
foreach ($columns as $column) { foreach ($columns as $column) {
$update_string .= $column . " = :$column, "; $update_string .= $column . " = :$column, ";
$update_data[$column] = $obj[$column]; $update_data[$column] = $obj[$column];
@@ -119,7 +161,7 @@ abstract class Entity {
$maxVal = ($maxVal) ? $maxVal : 0; $maxVal = ($maxVal) ? $maxVal : 0;
// If the next val is smaller than the minumum value // If the next val is smaller than the minumum value
if (isset(static::_idPolice['min']) && static::_idPolice['min'] > $maxVal->id+1) { if (isset(static::_idPolice['min']) && static::_idPolice['min'] > $maxVal->id + 1) {
// The id value shpuld assume the min value // The id value shpuld assume the min value
$this->id = static::_idPolice['min']; $this->id = static::_idPolice['min'];
} else { } else {
@@ -164,14 +206,6 @@ abstract class Entity {
} }
} }
public function delete() {
if (isset($this->_softdelete) && $this->_softdelete) {
$this->deleted_at = date('Y-m-d h:m:s');
$this->update();
return;
}
$this->purge();
}
public function load($id = false) { public function load($id = false) {
if (!$id) { if (!$id) {
@@ -183,11 +217,29 @@ abstract class Entity {
$this->fill(DBInstance::queryPrepare($sql, Array($id), static::_connectionName)[0]); $this->fill(DBInstance::queryPrepare($sql, Array($id), static::_connectionName)[0]);
} }
public function delete() {
if (static::_softdelete) {
$this->deleted_at = date('Y-m-d h:m:s');
$this->update();
}else{
$this->purge();
}
}
public function purge() { public function purge() {
$sql = "DELETE FROM {" . static::_tableName . "} WHERE id = :id"; $sql = "DELETE FROM {" . static::_tableName . "} WHERE id = :id";
DBInstance::execute($sql, Array('id' => $this->id), static::_connectionName); DBInstance::execute($sql, Array('id' => $this->id), static::_connectionName);
} }
public function restore(){
if (isset($this->_softdelete) && $this->_softdelete) {
$this->deleted_at = null;
$this->update();
}else{
throw new \Exception('Not soft deleteble');
}
}
private function fill($data) { private function fill($data) {
$data = (array) $data; $data = (array) $data;
@@ -206,7 +258,7 @@ abstract class Entity {
* @param Array $limits Array( 'offset'=> 10, 'limit' => 10 ) * @param Array $limits Array( 'offset'=> 10, 'limit' => 10 )
* @param boolean $trashed Bring trashed elements? * @param boolean $trashed Bring trashed elements?
*/ */
public static function findAll($select = Array('*'), $limits = Array(), $trashed = false) { public static function findAll($select = Array('*'), $limits = Array(), $trashed = false) : Collection {
$criteria = ''; $criteria = '';
$limits_sql = ''; $limits_sql = '';
@@ -227,13 +279,13 @@ abstract class Entity {
} }
$results = DBInstance::query($sql, Array(), static::_connectionName); $results = DBInstance::query($sql, Array(), static::_connectionName);
$objects = Array(); $objects = new Collection;
foreach ($results as $value) { foreach ($results as $value) {
$static = static::class; $static = static::class;
$object = new $static; $object = new $static;
$object->fill($value); $object->fill($value);
$objects[] = $object; $objects->addItem($object);
} }
return $objects; return $objects;
} }
@@ -288,6 +340,10 @@ abstract class Entity {
* @param Boolan $trashed true, false * @param Boolan $trashed true, false
*/ */
public static function findOne($criterias = Array(), $select = Array('*'), $trashed = false) { public static function findOne($criterias = Array(), $select = Array('*'), $trashed = false) {
if(empty($criterias)){
$criterias = Array(1 => ['=', 1]);
}
$select_sql = ""; $select_sql = "";
$criteria_sql = ""; $criteria_sql = "";
$limits_sql = ""; $limits_sql = "";
@@ -302,8 +358,10 @@ abstract class Entity {
foreach ($criterias as $key => $criteria) { foreach ($criterias as $key => $criteria) {
if ($criteria_sql != "") { if ($criteria_sql != "") {
$criteria_sql .= " AND "; $criteria_sql .= " AND ";
} else { } else if ($criteria_sql == "") {
$criteria_sql .= " WHERE "; $criteria_sql .= " WHERE ";
} else {
$criteria_sql .= " ";
} }
if (is_array($criteria[1])) { if (is_array($criteria[1])) {
$crit_temp = ''; $crit_temp = '';
@@ -335,28 +393,28 @@ abstract class Entity {
} }
$results = DBInstance::query($sql, $criteria_data, static::_connectionName); $results = DBInstance::query($sql, $criteria_data, static::_connectionName);
$objects = Array(); $objects = new Collection();
foreach ($results as $value) { foreach ($results as $value) {
$class = static::class; $class = static::class;
$object = new $class; $object = new $class;
$object->fill($value); $object->fill($value);
$objects[] = $object; $objects->addItem($object);
} }
if (empty($objects)) { if (empty($objects)) {
//return false; //new $this->classname; return false; //new $this->classname;
$className = static::class;
return new $className;
} }
return $objects[0]; return $objects[0];
} }
/** /**
* Find Many * Find Many
* *
* @param Array $criterias Description * @param array $criterias Description
* @param Array $select Description * @param array $select Description
* @param Array $limits Description * @param array $limits Description
* @param boolean $trashed Description * @param boolean $trashed Description
* *
*/ */
@@ -370,12 +428,22 @@ abstract class Entity {
} }
foreach ($criterias as $key => $criteria) { foreach ($criterias as $key => $criteria) {
if ($criteria_sql != "") { if ($criteria_sql != "" && substr($criteria[0], 0, 2) == 'OR') {
$criteria_sql .= " ";
} else if ($criteria_sql != "" ) {
$criteria_sql .= " ";
} else if ($criteria_sql != "" ) {
$criteria_sql .= " AND "; $criteria_sql .= " AND ";
} else { } else if ($criteria_sql == "") {
$criteria_sql .= " WHERE "; $criteria_sql .= " WHERE ";
} else {
$criteria_sql .= " ";
} }
if (is_string($criteria[1])) {
if (substr($criteria[0], 0, 2) == "OR") {
$criteria[0] = str_replace('OR', '', $criteria[0]);
$criteria_sql .= "OR $key $criteria[0] ('%$criteria[1]%')";
} else if (is_string($criteria[1])) {
$criteria_sql .= "$key $criteria[0] '$criteria[1]'"; $criteria_sql .= "$key $criteria[0] '$criteria[1]'";
} else if (is_array($criteria[1])) { } else if (is_array($criteria[1])) {
$criteria_sql .= "$key $criteria[0] (" . implode(', ', $criteria[1]) . ")"; $criteria_sql .= "$key $criteria[0] (" . implode(', ', $criteria[1]) . ")";
@@ -384,9 +452,12 @@ abstract class Entity {
} }
} }
$criteria_sql = str_replace('WHERE OR', 'WHERE ', $criteria_sql);
foreach ($select as $value) { foreach ($select as $value) {
$select_sql .= $value . ', '; $select_sql .= $value . ', ';
} }
$select_sql = rtrim($select_sql, ', '); $select_sql = rtrim($select_sql, ', ');
if (static::_softdelete && !$trashed) { if (static::_softdelete && !$trashed) {
@@ -396,17 +467,19 @@ abstract class Entity {
} }
$results = DBInstance::query($sql, Array(), static::_connectionName); $results = DBInstance::query($sql, Array(), static::_connectionName);
$objects = Array(); $objects = new Collection();
foreach ($results as $value) { foreach ($results as $value) {
$class = static::class; $class = static::class;
$object = new $class; $object = new $class;
$object->fill($value); $object->fill($value);
$objects[] = $object; $objects->addItem($object);
} }
if (empty($objects)) { if (empty($objects)) {
return Array(); return Array();
} }
return $objects; return $objects;
} }
@@ -424,15 +497,14 @@ abstract class Entity {
* *
* @ctag $this->hasOne('foreign_object', 'field_in_remote'); * @ctag $this->hasOne('foreign_object', 'field_in_remote');
* *
* @param Object $foreign_object Class instance from the remote object * @param object $foreign_object Class instance from the remote object
* @param (int, string) $field_in_remote Field in local object matchin the remote id * @param (int, string) $field_in_remote Field in local object matchin the remote id
* *
* @return Object Instance of the remote class * @return object Instance of the remote class
* *
*/ */
protected function hasOne($foreign_object, $field_in_remote) { protected function hasOne($foreign_object, $field_in_remote) {
$obj = new $foreign_object; return new HasOne($foreign_object, $field_in_remote, $this);
return $obj->findOne(Array($field_in_remote => Array('=', $this->id)));
} }
/** /**
@@ -448,13 +520,12 @@ abstract class Entity {
* *
* @ctag $this->hasMany('foreign_object', 'field_in_foreign'); * @ctag $this->hasMany('foreign_object', 'field_in_foreign');
* *
* @param type $foreign_object Instance of a remote class * @param Entity $foreign_object Instance of a remote class
* @param (int, string) $field_in_foreign The field to match the local id * @param (int, string) $field_in_foreign The field to match the local id
* *
*/ */
protected function hasMany($foreign_object, $field_in_foreign) { protected function hasMany($foreign_object, $field_in_foreign) {
$obj = new $foreign_object; return new HasMany($foreign_object, $field_in_foreign, $this);
return $obj->findMany(Array($field_in_foreign => Array('=', $this->id)));
} }
/** /**
@@ -472,13 +543,12 @@ abstract class Entity {
* @ctag $this->belongsTo('foreign_object', 'local_field'); * @ctag $this->belongsTo('foreign_object', 'local_field');
* @ctag $this->belongsTo('foreign_object', 'local_field', 'id'); * @ctag $this->belongsTo('foreign_object', 'local_field', 'id');
* *
* @param Object $foreign_object Instance of a remote class * @param Entity $foreign_object Instance of a remote class
* @param (int, String) $local_field Remote field relate to local Object * @param (int, String) $local_field Remote field relate to local Object
* @param string $remote_field * @param string $remote_field
*/ */
protected function belongsTo($foreign_object, $local_field, $remote_field = 'id') { protected function belongsTo($foreignObject, $localField, $remoteField = 'id') {
$obj = new $foreign_object; return new BelongsTo($foreignObject, $localField, $remoteField, $this);
return $obj->findOne(Array($remote_field => Array('=', $this->$local_field)));
} }
/** /**
@@ -504,24 +574,8 @@ abstract class Entity {
* @param Array $remote_filter Filters to the remote Array('id', Array('>', 50) ) * @param Array $remote_filter Filters to the remote Array('id', Array('>', 50) )
* @param Array $remote_limit Array( 'offset'=> 10, 'limit' => 10 ) * @param Array $remote_limit Array( 'offset'=> 10, 'limit' => 10 )
*/ */
protected function belongsToMany($foreign_object, $pivot_table, $local_in_pivot, $remote_in_pivot, $remote_filter = Array(), $remote_limit = Array()) { protected function belongsToMany($foreignObject, $pivot_table, $local_in_pivot, $remote_in_pivot, $remote_filter = Array(), $remote_limit = Array()) {
$obj = new $foreign_object; return new BelongsToMany($this, $foreignObject, $pivot_table, $local_in_pivot, $remote_in_pivot, $remote_filter, $remote_limit);
$limits_sql = '';
foreach ($remote_limit as $key => $value) {
$limits_sql .= "$key $value ";
}
$sql = "SELECT $remote_in_pivot FROM {$pivot_table} WHERE $local_in_pivot = $this->id $limits_sql";
$relations = DBInstance::query($sql, Array(), static::_connectionName);
$ids = Array();
foreach ($relations as $relation) {
$ids[] = $relation->$remote_in_pivot;
}
if (empty($ids)) {
return Array();
}
return $obj->findMany(array_merge(Array('id' => Array('IN', $ids)), $remote_filter), Array('*'), $remote_limit);
} }
/** /**
@@ -548,28 +602,36 @@ abstract class Entity {
* @param Array $remote_filter Filters to the remote Array('id', Array('>', 50) ) * @param Array $remote_filter Filters to the remote Array('id', Array('>', 50) )
* @param Array $pivot_limits Array( 'offset'=> 10, 'limit' => 10 ) * @param Array $pivot_limits Array( 'offset'=> 10, 'limit' => 10 )
*/ */
protected function belongsToManyExtended($foreign_object, $pivot_table, $local_in_pivot, $remote_in_pivot, $remote_filter = Array(), $pivot_limits = Array()) { protected function belongsToManyExtended($foreignObject, $pivot_table, $local_in_pivot, $remote_in_pivot, $remote_filter = Array(), $pivot_limit = Array(), $softDelete = true) {
$obj = new $foreign_object; return new BelongsToManyExtended($this, $foreignObject, $pivot_table, $local_in_pivot, $remote_in_pivot, $remote_filter, $pivot_limit, $softDelete);
$limits_sql = '';
foreach ($pivot_limits as $key => $value) {
$limits_sql .= "$key $value ";
}
$sql = "SELECT * FROM $pivot_table WHERE $local_in_pivot = $this->id $limits_sql";
$relations = DBInstance::query($sql, Array(), static::_connectionName);
$objects = Array();
if (empty($relations)) {
return Array();
}
foreach ($relations as $relation) {
$relation->child_element = $obj->findOne(array_merge(Array("id" => Array("=", $relation->$remote_in_pivot)), $remote_filter));
$objects[] = $relation;
}
if (empty($objects)) {
return Array();
}
return $objects;
} }
/**
* With
*
* Eager load relations on this entity
*
**/
public function with($relations = null, $propagate = null){
if(is_string($relations)){
$relations = [$relations];
}
if(!$relations){
return $this;
}
$possibleRelations = get_class_methods(static::class);
foreach($relations as $relation){
if(in_array($relation, $possibleRelations)){
$this->$relation = $this->$relation()->get();
}
if($this->$relation){
$this->$relation->with($propagate);
}
}
return $this;
}
} }