diff --git a/deploy/lib/data/Message.php b/deploy/lib/data/Message.php index f079328dc..0a7aba9fe 100644 --- a/deploy/lib/data/Message.php +++ b/deploy/lib/data/Message.php @@ -6,14 +6,15 @@ // use Illuminate\Database\Eloquent\Model; use NinjaWars\core\data\Player; -class Message extends \Illuminate\Database\Eloquent\Model +class Message extends NWQuery { - protected $primaryKey = 'message_id'; // Anything other than id + static protected $primaryKey = 'message_id'; // if anything other than id + static protected $table = 'messages'; public $timestamps = false; // The non-mass-fillable fields protected $guarded = ['message_id', 'date']; /** - Currently: + Messages Currently: message_id | serial message | text date | timestamp diff --git a/deploy/lib/data/NWQuery.php b/deploy/lib/data/NWQuery.php new file mode 100644 index 000000000..0b8c986b2 --- /dev/null +++ b/deploy/lib/data/NWQuery.php @@ -0,0 +1,91 @@ +save(), whatever nw needs) + */ +abstract class NWQuery +{ + + private static $model; + // Inheriting classes need to set primaryKey and table as: + // protected $primaryKey; + // protected $table = 'messages'; + + + public static function freshTimestamp() + { + // use Carbon::now() to get a current timestamp + return Carbon::now(); + } + + public static function getTable() + { + return static::$table; + } + + public static function getPrimaryKey() + { + return static::$primaryKey; + } + + public static function creating($model) + { + // initialize the model if it hasn't been already + if (!self::$model) { + // initialize as a stdClass object + + self::$model = new static(); + self::$model->table = static::$table; + self::$model->primaryKey = static::$primaryKey; + } + self::$model->date = self::freshTimestamp(); + return self::$model; + } + + public static function create($model) + { + $model_f = self::creating($model); + $model_f->date = self::freshTimestamp(); + if (!$model_f->table) { + throw new \Exception('Error: Model created does not have a table set.'); + } + return $model_f; + } + + /** + * @return array of items + */ + public static function query($builder) + { + // Destructure the builder into query and parameters + list($query, $params) = $builder; + $datas = query_array($query, $params); + // Meld the incoming data array of multiple entries with the current model + $collected = array_map(function ($data) { + return (object) array_merge((array) self::$model, $data); + }, $datas); + return $collected; + } + + /** + * @return object A single model object + */ + public static function find($id) + { + + $found_data = reset(self::query(['select * from ' . static::$table . ' where ' . static::$primaryKey . ' = :id', [':id' => $id]])); + $model = new static(); + foreach ($found_data as $key => $value) { + $model->$key = $value; + } + return $model; + } +}