Skip to content

Instantly share code, notes, and snippets.

@YordiLorenzo
Created November 24, 2014 10:48
Show Gist options
  • Select an option

  • Save YordiLorenzo/5647b5ae5218a060f209 to your computer and use it in GitHub Desktop.

Select an option

Save YordiLorenzo/5647b5ae5218a060f209 to your computer and use it in GitHub Desktop.
Portfolio - Growne sample
/**
* Here the iOS app is bootstrapped with requiring the Namspace module and getting the app instance
*/
/**
*
* Main namespace model
* Require main namespace, in the main namespace al the classes and modules / views life
* @type Object
*
*/
var namespace = require('classes/Namespace');
/**
*
* app namespace
* Register app namespace, get the actual app namespace and register it with an existing namespace or an empty object
* @type Object
*
*/
var app = namespace.app || {};
/**
*
* Run app
*
*/
app.run();
/**
* Advanced GrowneController that uses SessionManager instances for managing a custom generated Session that is passed with an async call.
*/
<?php
use Growne\Handlers\GrowneHandler;
use Growne\Models\User;
use Growne\Models\Task;
use Growne\Models\Like;
use Growne\Models\Dislike;
use Growne\Models\Growne;
use Growne\Classes\Analytics;
use Growne\Classes\System;
use Growne\Models\AppSession;
use Growne\Exceptions\GrowneNotCreatedException;
use Growne\Exceptions\GrowneNotUpdatedException;
use Growne\Validators\Managers\SessionManager;
class GrowneController extends BaseController
{
private $ApiController;
private $System;
private $Analytics;
private $rules = array(
'title' => 'Required|Min:3|Max:80|alpha_spaces',
'description' => 'Required|Max:1000|alpha_spaces',
'belongs_to' => 'Required|integer',
'img' => 'Required|mimes:jpeg,bmp,png',
'lat' => 'Required',
'long' => 'Required'
);
private $updateRules = array(
'title' => 'Min:3|Max:80|alpha_spaces',
'description' => 'Max:1000|alpha_spaces',
'belongs_to' => 'integer',
'img' => 'mimes:jpeg,bmp,png',
'session_key' => 'Required',
'user_id' => 'Required'
);
/**
*
* [__construct Construct the class]
*
*/
function __construct()
{
$this->ApiController = new ApiController();
$this->System = new System();
$this->Analytics = new Analytics();
}
/**
*
* [index Index Growne models with pagination of 10]
* @return [Response] [JSOn response with models]
*
*/
public function index()
{
if(Input::has('top')){
if(Input::get('top')){
$growne = Growne::with('user')->paginate(20)->sortBy('likes_count');
}
}else {
$growne = Growne::with('user')->paginate(10);
}
$data = [
'data' => $growne->toArray()
];
return Response::json($data, 200);
}
/**
*
* [show Show Growne model belonging to ID]
* @var integer $id [Show growne with ID]
* @return [Response] [Response with Growne Model]
*
*/
public function show($id){
$data = [];
try {
$growne = Growne::with('user')->findOrFail($id);
$data = [
'data' => $growne->toArray()
];
} catch (Exception $e) {
$data = [
'data' => null
];
}
return Response::json($data, 200);
}
/**
*
* [search Search Growne models]
* @var string $query [Query to match the models]
* @return [Response] [Return results in JSON response]
*
*/
public function search($query){
$growne = Growne::with('user')->where('description', 'LIKE', '%'.$query.'%')->get();
$data = [
'data' => $growne->toArray()
];
return Response::json($data, 200);
}
/**
*
* [update Update Growne model belonging to ID]
* @var integer $id [ID of the Growne to Update]
* @return [Response] [JSON response of the updated model]
*
*/
public function update($id){
$data = [];
$messages = [];
$input = Input::all();
$validator = Validator::make($input,$this->updateRules);//Create new validator instance
try {
if ($validator->passes()) {
$growne = Growne::findOrFail($id);//Find growne model
if (AppSession::valid(Input::get('session_key'), Input::get('user_id'))) {//Check if session is valid , NEEDS TO BE UPDATED to reflect usage of SessionManager
if($growne->belongs_to == Input::get('user_id')){
if(Input::hasFile('new_img')){
$filename = GrowneHandler::handleFileUpload(Input::file('new_img'));
Input::merge(['img' => $filename]);
}
unset($input['session_key'], $input['user_id'], $input['_method']);//Unset unneeded fields
$growne->update($input);//Update
$growne->save();//Save
$data = [//Output
"growne" => $growne->toArray(),
"session_valid" => true
];
}else {
$data = [
'data' => null,
'session_valid' => false,
];
}
} else {
$data = [
'data' => null,
'session_valid' => false,
];
}
} else {
$messages = $validator->messages()->toArray();
throw new GrowneNotUpdatedException('Growne is not updated, Stack : '.$validator->messages());
}
} catch (GrowneNotUpdatedException $e) {
$data = $this->mergeDataFields(['data' => null], $messages);
} catch (ModelNotFoundException $e){
$data = $this->mergeDataFields(['data' => null], $messages);
}
return Response::json($data, 200);
}
/**
*
* Destroy a growne model
* @var integer $id [ID of the growne to delete]
* @return growne that is deleted
*
*/
public function destroy($id){
try {
$growne = Growne::findOrFail($id);
$sessionManager = SessionManager::getInstance()->setName('SessionManagingInstance')->setPurpose('DeleteGrowne')->verify(Input::get('session_key'), Input::get('user_id'));
if ($sessionManager->passes() && $growne->id == $id && $growne->belongs_to == Input::get('user_id')) {
$growne->delete();
return [
"data" => $user->toArray(),
"deleted" => true,
"session_valid" => true
];
}else {
return [
"data" => null,
"deleted" => false,
"session_valid" => false
];
}
} catch (Exception $e) {
return [
"data" => null,
"deleted" => false,
"session_valid" => true
];
}
}
public function store(){
$input = Input::all();//Get all Input vars
$messages = [];
$validator = Validator::make($input,$this->rules);//Create new validator instance
$data = [];
if (Input::has('session_key') && Input::has('user_id')) {//Check if session info is present
if (AppSession::valid(Input::get('session_key'), Input::get('user_id')) && Input::get('user_id') === Input::get('belongs_to')) {//Check if session is valid and user_id and belongs_to match
try {
if ($validator->passes()) {//Check if input parameters are present
$info = [//Fill array with growne info
'title' => Input::get('title'),
'description' => Input::get('description'),
'belongs_to' => Input::get('belongs_to'),
'img' => Input::file('img'),
'lat' => Input::get('lat'),
'long' => Input::get('long')
];
$growne = GrowneHandler::create($info);//let grownehandler handle te creation and send back response
$data = [
'data' => $growne,//Response from GrowneHandler
'session_valid' => true,
'fieldset' => true
];
}else {
$messages = $validator->messages()->toArray();
throw new GrowneNotCreatedException('Growne is not created, Stack : '.$validator->messages());
}
} catch (GrowneNotCreatedException $e) {
$data = $this->mergeDataFields(['data' => null], $messages);
}
}else {//Session is not valid
$data = [
'data' => null,
'session_valid' => false,
'fieldset' => true
];
}
}else {//Session parameters are not set
$data = [
'data' => null,
'session_valid' => false,
'fieldset' => false
];
}
return Response::json($data, 200);//Return the response
}
/**
* [stats Return likes and dislikes by id]
* @var integer $id [ID of the growne]
* @return [Response] [Return json response]
*/
public function stats($id){
return GrowneHandler::stats($id);
}
/**
* Vote up method
*/
public function voteUp($id){
try {
$growne = Growne::with('user')->findOrFail($id)->toArray();
$sessionManager = SessionManager::getInstance()->setName('SessionManagingInstance')->setPurpose('VerifyUser')->verify(Input::get('session_key'), Input::get('user_id'));
if($sessionManager->passes()){
$like = Like::where('user_id', Input::get('user_id'))->where('growne_id', $growne['id'])->get();
if($like->count() < 1){
Dislike::where('user_id', Input::get('user_id'))->where('growne_id' , $id)->delete();
return ["data" => Like::create(['growne_id' => (int) $id,
'user_id' => (int) Input::get('user_id')
])->toArray(), "voted" => true];
}else {
return ["data" => null, "liked" => false, "session" => true];
}
}else {
return ["data" => null, "session" => false];
}
} catch (Exception $e) {
return ["data" => null, "session" => null];
}
}
/**
* [voteDown description]
* @param $id [description]
* @return
*/
public function voteDown($id){
try {
$growne = Growne::with('user')->findOrFail($id)->toArray();
$sessionManager = SessionManager::getInstance()->setName('SessionManagingInstance')->setPurpose('VerifyUser')->verify(Input::get('session_key'), Input::get('user_id'));
if($sessionManager->passes()){
$dislike = Dislike::where('user_id', Input::get('user_id'))->where('growne_id', $growne['id'])->get();
if($dislike->count() < 1){
Like::where('user_id', Input::get('user_id'))->where('growne_id' , $id)->delete();
return ["data" => Dislike::create(['growne_id' => (int) $id,
'user_id' => (int) Input::get('user_id')
])->toArray(), "voted" => true];
}else {
return ["data" => null, "liked" => false, "session" => true];
}
}else {
return ["data" => null, "session" => false];
}
} catch (Exception $e) {
dd($e->getMessage());
return ["data" => null, "session" => null];
}
}
/*
|--------------------------------------------------------------------------
| Admin Panel section
|--------------------------------------------------------------------------
| The next lines contain only code that is used inside the control panel
|
*/
/**
*
* [create Create a growne from the control panel without a session key]
* @return [Response] [JSON response of the created Growne]
*
*/
public function create() {
$input = Input::all();//Get all Input vars
$validator = Validator::make($input,$this->rules);//Create new validator instance
$messages = [];
$data = [];
try {
if($validator->passes()){//Check if validator passes
$info = [//Fill array with growne info
'title' => Input::get('title'),
'description' => Input::get('description'),
'belongs_to' => Input::get('belongs_to'),
'img' => Input::file('img'),
'lat' => '52.04948',
'long' => '4.232662'
];
$growne = GrowneHandler::create($info);
$data = [
"data" => $growne,
"created" => true
];
}else {
$messages = $validator->messages()->toArray();
throw new GrowneNotCreatedException('Growne is not created, Stack : '.$validator->messages());
}
} catch (GrowneNotCreatedException $e) {
$data = [
"data" => null,
"created" => false,
];
foreach ($messages as $key => $value) {
$data[$key] = $value;
}
}
return $data;
}
/**
*
* [showDashboard Show growne view with Grownees]
* @return [View] [Return a new View]
*
*/
public function showDashboard(){
$user_sess = Sentry::getUser();
$notifications = $this->System->getNotifications();
$user = [
'username' => $user_sess->first_name . ' ' . $user_sess->last_name,
'member_since' => $user_sess->created_at->toFormattedDateString(),
'user_img' => $user_sess->user_img
];
$grownees = Growne::with('user')->get()->toArray();
$tasks = Task::all()->toArray();
$stats = [
'notifications' => $notifications,
'notifications_count' => count($notifications)
];
return View::make('admin.grownees', ["user" => $user, "grownees" => $grownees, "tasks" => $tasks, "stats" => $stats]);
}
/**
*
* [showCreatePage Show page to create a Growne]
* @return [View] [Return a new View]
*
*/
public function showCreatePage(){
$user_sess = Sentry::getUser();
$user = [
'username' => $user_sess->first_name . ' ' . $user_sess->last_name,
'member_since' => $user_sess->created_at->toFormattedDateString(),
'user_img' => $user_sess->user_img
];
$tasks = Task::all()->toArray();
$stats = [
'notifications' => $this->System->getNotifications(),
'notifications_count' => count($this->System->getNotifications())
];
return View::make('admin.grownees.create', ["user" => $user, "tasks" => $tasks, "stats" => $stats]);
}
/**
*
* [createGrowneWithResponse Create the Growne with a response]
* @return [response] [json response]
*
*/
public function createGrowneWithResponse() {
$result = $this->create();
$user_sess = Sentry::getUser();
$user = [
'username' => $user_sess->first_name . ' ' . $user_sess->last_name,
'member_since' => $user_sess->created_at->toFormattedDateString(),
'user_img' => $user_sess->user_img
];
$tasks = Task::all()->toArray();
$stats = [
'notifications' => $this->System->getNotifications(),
'notifications_count' => count($this->System->getNotifications())
];
if($result['created']){
return View::make('admin.grownees.created', ["user" => $user, "tasks" => $tasks, "stats" => $stats, "errors" => $result]);
}else {
unset($result['data'], $result['created']);
return View::make('admin.grownees.notcreated', ["user" => $user, "tasks" => $tasks, "stats" => $stats, "errors" => $result]);
}
}
/**
*
* [showEditPage Show page to edit a Growne]
* @var integer $id [ID of the growne to edit]
* @return [View] [Return a new View]
*
*/
public function showEditPage($id){
try {
$edit_growne = Growne::with('user')->findOrFail($id)->toArray();
$user_sess = Sentry::getUser();
$notifications = $this->System->getNotifications();
$user = [
'username' => $user_sess->first_name . ' ' . $user_sess->last_name,
'member_since' => $user_sess->created_at->toFormattedDateString(),
'user_img' => $user_sess->user_img
];
$tasks = Task::all()->toArray();
$stats = [
'notifications' => $notifications,
'notifications_count' => count($notifications)
];
return View::make('admin.grownees.edit', ["user" => $user, "tasks" => $tasks, "stats" => $stats, "edit_growne" => $edit_growne]);
} catch (Exception $e) {
return Redirect::to('/admin/grownees');
}
}
/**
*
* [editGrowneWithResponse Edit a Growne and send back a response view]
* @var integer $id [ID of the growne do edit]
* @return [Redirect] [Redirect to Growne page]
*
*/
public function editGrowneWithResponse($id) {
try {
$growne = Growne::findOrFail($id);
$growne->update(Input::all());
$growne->save();
return Redirect::to('/admin/grownees');
} catch (Exception $e) {
return Redirect::to('/admin/grownees');
}
}
/**
*
* [delete Delete a Growne model]
* @var integer $id [ID of the growne to delete]
* @return [type] [description]
*
*/
public function delete($id){
$data = [];
try {
$growne = Growne::findOrFail($id);
$growne->delete();
$data = [
"id" => $growne->id,
"deleted" => true
];
} catch (Exception $e) {
$data = [
"id" => null,
"deleted" => false
];
}
return Response::json($data, 200);//Return the response
}
}
/*
* This is the root namespace for the Growne iOS app, this namespace provides the app with easy to use modules and views
*/
exports.app = {
run : function(){
ui.boot();
},
ui: {
animations: {}
},
Mailer: require('classes/Mailer'),
Utils: require('classes/Utils'),
Data: require('classes/Data'),
Forms: {
Login: require('views/LoginForm'),
Registration: require('views/RegistrationForm'),
Details: require('views/DetailsForm'),
Builder: require('classes/FormBuilder')
},
Views: {
Partials: {
Header: require('views/partials/Header')
},
OptionDialog: require('views/OptionDialog'),
AlertDialog: require('views/AlertDialog'),
Datepicker: require('views/Datepicker'),
NoNetwork: require('views/NoNetwork')
},
Validators: {
Formvalidator: require('classes/Formvalidator')
},
Gallery: require('classes/Gallery'),
Properties: require('classes/Properties'),
API: require('classes/API'),
Keychain: require('bencoding.securely'),
User: require('classes/User'),
JSON: require('classes/JSON'),
Log: require('classes/Log'),
};
exports.app = app;
/**
* Dynamically bind a new CommonJS module
*/
exports.bind = function(namespace, className, classPath) {
if (typeof classPath == 'undefined') {
classPath = 'classes/' + className;
viewPath = 'views/' + className;
}
try {
namespace[className] = require(classPath);
return namespace[className]; //Return binded instance
} catch (ClassNotFoundException) {
try {
namespace[className] = require(viewPath);
return namespace[className]; //Return binded instance
} catch (SourceNotFoundException) {
throw new Error("Classpath was undefined and dynamic binding failed");
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment