Upgrade Laravel Version and ORM Framework

upgraded laravel version from 5.0 to 5.2.
Changed ORM from eloquent to Doctrine to support better inheritance handling
basically eloquent does not suppor the inheritance model used by Silverstripe
which makes dificult to implement write apis on model hierarchies defined with
SS schema.
Refactoring.

Change-Id: I802e171c8b95e81dc21578543ddb6a02003985e5
This commit is contained in:
Sebastian Marcet 2016-05-27 16:20:46 -03:00
parent 3f9ffa2ca7
commit ce12d3cb89
317 changed files with 16158 additions and 7504 deletions

5
.gitignore vendored
View File

@ -3,7 +3,6 @@
composer.phar
composer.lock
.DS_Storeapp/storage
/app/storage/*
.idea/*
app/config/dev/*
app/config/testing/*
@ -23,4 +22,6 @@ doc/build
*.egg
*.egg-info
.env.testing
.env
.env
storage/logs/*
*.log

View File

@ -0,0 +1,187 @@
<?php namespace Libs\ModelSerializers;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use libs\utils\JsonUtils;
use models\utils\IEntity;
/**
* Class AbstractSerializer
* @package Libs\ModelSerializers
*/
abstract class AbstractSerializer implements IModelSerializer
{
/**
* @var IEntity
*/
protected $object;
/**
* AbstractSerializer constructor.
* @param $object
*/
public function __construct($object){
$this->object = $object;
}
protected static $array_mappings = array();
protected static $allowed_fields = array();
protected static $allowed_relations = array();
/**
* @return array
*/
protected function getAllowedFields()
{
$mappings = array();
$hierarchy = $this->getClassHierarchy();
foreach($hierarchy as $class_name){
if($class_name === 'Libs\ModelSerializers\AbstractSerializer') continue;
$class = new $class_name($this->object);
$mappings = array_merge($mappings, $class->getSelfAllowedFields());
}
$mappings = array_merge($mappings, $this->getSelfAllowedFields());
return $mappings;
}
private function getSelfAllowedFields(){
return static::$allowed_fields;
}
/**
* @return array
*/
protected function getAllowedRelations()
{
$mappings = array();
$hierarchy = $this->getClassHierarchy();
foreach($hierarchy as $class_name){
if($class_name === 'Libs\ModelSerializers\AbstractSerializer') continue;
$class = new $class_name($this->object);
$mappings = array_merge($mappings, $class->getSelfAllowedRelations());
}
$mappings = array_merge($mappings, $this->getSelfAllowedRelations());
return $mappings;
}
private function getSelfAllowedRelations(){
return static::$allowed_relations;
}
/**
* @return array
*/
private function getAttributeMappings()
{
$mappings = array();
$hierarchy = $this->getClassHierarchy();
foreach($hierarchy as $class_name){
if($class_name === 'Libs\ModelSerializers\AbstractSerializer') continue;
$class = new $class_name($this->object);
$mappings = array_merge($mappings, $class->getSelfMappings());
}
$mappings = array_merge($mappings, $this->getSelfMappings());
return $mappings;
}
private function getSelfMappings(){
return static::$array_mappings;
}
/**
* @return array
*/
private function getClassHierarchy(){
return array_reverse($this->get_class_lineage($this));
}
private function get_class_lineage($object)
{
$class_name = get_class($object);
$parents = array_values(class_parents($class_name));
return array_merge(array($class_name), $parents);
}
/**
* @param null $expand
* @param array $fields
* @param array $relations
* @param array $params
* @return array
*/
public function serialize($expand = null, array $fields = array(), array $relations = array(), array $params = array() )
{
$values = array();
if(!count($fields)) $fields = $this->getAllowedFields();
$mappings = $this->getAttributeMappings();
if (count($mappings)) {
$new_values = array();
foreach ($mappings as $attribute => $mapping) {
$mapping = preg_split('/:/',$mapping);
$value = call_user_func( array( $this->object, 'get'.$attribute ) );
if(count($mapping) > 1)
{
//we have a formatter ...
switch(strtolower($mapping[1]))
{
case 'datetime_epoch':
{
if(!is_null($value)) {
$value = $value->getTimestamp();
}
}
break;
case 'json_string':
{
$value = JsonUtils::toJsonString($value);
}
break;
case 'json_boolean':
{
$value = JsonUtils::toJsonBoolean($value);
}
break;
case 'json_int':
{
$value = JsonUtils::toJsonInt($value);
}
break;
case 'json_float':
{
$value = JsonUtils::toJsonFloat($value);
}
break;
}
}
$new_values[$mapping[0]] = $value;
}
$values = $new_values;
}
//check requested fields
if(count($fields) > 0) {
foreach ($values as $field => $value) {
if (in_array($field, $fields)) continue;
unset($values[$field]);
}
}
return $values;
}
}

View File

@ -0,0 +1,25 @@
<?php namespace Libs\ModelSerializers;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
interface IModelSerializer
{
/**
* @param null $expand
* @param array $fields
* @param array $relations
* @param array $params
* @return array
*/
public function serialize($expand = null, array $fields = array(), array $relations = array(), array $params = array() );
}

View File

@ -1,4 +1,4 @@
<?php
<?php namespace libs\utils;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
@ -12,7 +12,7 @@
* limitations under the License.
**/
namespace libs\utils;
/**
* Class JsonUtils
@ -48,7 +48,7 @@ abstract class JsonUtils
*/
public static function toJsonInt($value)
{
if(empty($value)) return null;
if(empty($value)) return 0;
return intval($value);
}
@ -58,7 +58,7 @@ abstract class JsonUtils
*/
public static function toJsonFloat($value)
{
if(empty($value)) return null;
if(empty($value)) return 0.00;
return floatval(number_format(floatval($value),2));
}

View File

@ -1,7 +0,0 @@
<?php namespace App\Commands;
abstract class Command {
//
}

View File

@ -0,0 +1,33 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Foundation\Inspiring;
class Inspire extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'inspire';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Display an inspiring quote';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->comment(PHP_EOL.Inspiring::quote().PHP_EOL);
}
}

View File

@ -1,19 +1,31 @@
<?php namespace App\Console\Commands;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Console\Command;
use libs\utils\ICacheService;
use models\summit\ISummitRepository;
use ModelSerializers\SerializerRegistry;
use services\model\ISummitService;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Config;
use Illuminate\Support\Facades\Config;
/**
* Class SummitJsonGenerator
* @package App\Console\Commands
*/
class SummitJsonGenerator extends Command {
final class SummitJsonGenerator extends Command {
/**
* @var ISummitService
@ -47,7 +59,14 @@ class SummitJsonGenerator extends Command {
*
* @var string
*/
protected $name = 'summit:json:generator';
protected $name = 'summit:json-generator';
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'summit:json-generator {summit_id?}';
/**
@ -64,21 +83,40 @@ class SummitJsonGenerator extends Command {
*/
public function handle()
{
$summit = $this->repository->getCurrent();
if(is_null($this->repository)) return;
$this->info(sprintf("processing summit id %s", $summit->ID));
$summit_id = $this->argument('summit_id');
if(is_null($summit_id))// if we dont provide a summit id, then get current
$summit = $this->repository->getCurrent();
else
$summit = $this->repository->getById(intval($summit_id));
if(is_null($summit)) return;
$this->info(sprintf("processing summit id %s", $summit->getIdentifier()));
$start = time();
$data = $this->service->getSummitData($summit, $expand = 'locations,sponsors,summit_types,event_types,presentation_categories,schedule');
$expand = 'locations,sponsors,summit_types,event_types,presentation_categories,schedule';
$data = SerializerRegistry::getInstance()->getSerializer($summit)->serialize($expand);
if(is_null($data)) return;
$end = time();
$delta = $end - $start;
$this->info(sprintf("execution call %s seconds", $delta));
$current_time = time();
$key = '/api/v1/summits/current.expand=locations%2Csponsors%2Csummit_types%2Cevent_types%2Cpresentation_categories%2Cschedule';
$key_current = sprintf('/api/v1/summits/%s.expand=%s','current', urlencode($expand));
$key_id = sprintf('/api/v1/summits/%s.expand=%s',$summit->getIdentifier(), urlencode($expand));
$cache_lifetime = intval(Config::get('server.response_cache_lifetime', 300));
$this->cache_service->setSingleValue($key, json_encode($data), $cache_lifetime);
$this->cache_service->setSingleValue($key.".generated", $current_time, $cache_lifetime);
$this->info(sprintf("regenerated cache for summit id %s", $summit->ID));
if($summit->isActive())
{
$this->cache_service->setSingleValue($key_current, json_encode($data), $cache_lifetime);
$this->cache_service->setSingleValue($key_current . ".generated", $current_time, $cache_lifetime);
}
$this->cache_service->setSingleValue($key_id, json_encode($data), $cache_lifetime);
$this->cache_service->setSingleValue($key_id.".generated", $current_time, $cache_lifetime);
$this->info(sprintf("regenerated cache for summit id %s", $summit->getIdentifier()));
}
}

View File

@ -1,29 +1,32 @@
<?php namespace App\Console;
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
/**
* Class Kernel
* @package App\Console
*/
class Kernel extends ConsoleKernel {
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
'App\Console\Commands\SummitJsonGenerator',
];
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
\App\Console\Commands\SummitJsonGenerator::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('summit:json:generator')->everyTenMinutes();
}
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// current
$schedule->command('summit:json-generator')->everyTenMinutes()->withoutOverlapping();
//austin
$schedule->command('summit:json-generator 6')->everyTenMinutes()->withoutOverlapping();
}
}

View File

@ -1,7 +1,8 @@
<?php namespace App\Events;
<?php
abstract class Event {
//
namespace App\Events;
abstract class Event
{
//
}

View File

@ -0,0 +1,45 @@
<?php namespace App\Events;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Queue\SerializesModels;
use models\summit\PresentationMaterial;
/**
* Class PresentationVideoCreated
* @package App\Events
*/
final class PresentationMaterialCreated extends Event
{
use SerializesModels;
/**
* @var PresentationMaterial
*/
private $material;
/**
* PresentationMaterialCreated constructor.
* @param PresentationMaterial $material
*/
public function __construct(PresentationMaterial $material)
{
$this->material = $material;
}
/**
* @return PresentationMaterial
*/
public function getMaterial(){
return $this->material;
}
}

View File

@ -1,6 +1,6 @@
<?php
<?php namespace App\Events;
/**
* Copyright 2015 OpenStack Foundation
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -12,15 +12,11 @@
* limitations under the License.
**/
namespace models\main;
use models\utils\SilverstripeBaseModel;
/**
* Class Image
* @package models\main
* Class SummitEventCreated
* @package App\Events
*/
class Image extends File
final class SummitEventCreated extends SummitEventEntityStateChanged
{
protected $mtiClassType = 'abstract';
}

View File

@ -1,6 +1,6 @@
<?php
<?php namespace App\Events;
/**
* Copyright 2015 OpenStack Foundation
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -12,12 +12,11 @@
* limitations under the License.
**/
namespace models\summit;
class SummitExternalLocation extends SummitGeoLocatedLocation
/**
* Class SummitEventDeleted
* @package App\Events
*/
final class SummitEventDeleted extends SummitEventEntityStateChanged
{
protected $stiBaseClass = 'models\summit\SummitGeoLocatedLocation';
protected $mtiClassType = 'abstract';
}

View File

@ -0,0 +1,64 @@
<?php namespace App\Events;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Doctrine\ORM\Event\LifecycleEventArgs;
use Illuminate\Queue\SerializesModels;
use models\summit\SummitEvent;
/**
* Class SummitEventEntityStateChanged
* @package App\Events
*/
class SummitEventEntityStateChanged extends Event
{
use SerializesModels;
/**
* @var SummitEvent
*/
protected $summit_event;
/**
* @var LifecycleEventArgs
*/
protected $args;
/**
* SummitEventEntityStateChanged constructor.
* @param SummitEvent $summit_event
* @param LifecycleEventArgs $args
*/
public function __construct(SummitEvent $summit_event, LifecycleEventArgs $args)
{
$this->summit_event = $summit_event;
$this->args = $args;
}
/**
* @return SummitEvent
*/
public function getSummitEvent()
{
return $this->summit_event;
}
/**
* @return LifecycleEventArgs
*/
public function getArgs()
{
return $this->args;
}
}

View File

@ -0,0 +1,22 @@
<?php namespace App\Events;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class SummitEventUpdated
* @package App\Events
*/
final class SummitEventUpdated extends SummitEventEntityStateChanged
{
}

View File

@ -1,34 +1,46 @@
<?php namespace App\Exceptions;
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
'Symfony\Component\HttpKernel\Exception\HttpException'
AuthorizationException::class,
HttpException::class,
ModelNotFoundException::class,
ValidationException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
* @param \Exception $e
*
* @param \Exception $e
* @return void
*/
public function report(Exception $e)
{
return parent::report($e);
parent::report($e);
}
/**
* Render an exception into an HTTP response.
* @param \Illuminate\Http\Request $request
* @param \Exception $e
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
@ -38,5 +50,4 @@ class Handler extends ExceptionHandler
}
return response()->view('errors.404', [], 404);
}
}

View File

@ -0,0 +1,32 @@
<?php namespace factories;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\App;
/**
* Class FactoriesProvider
* @package factories
*/
final class FactoriesProvider extends ServiceProvider
{
protected $defer = false;
public function boot()
{
}
public function register()
{
App::singleton(\models\summit\factories\IPresentationVideoFactory::class, \factories\PresentationVideoFactory::class);
}
}

View File

@ -0,0 +1,44 @@
<?php namespace factories;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use models\summit\factories\IPresentationVideoFactory;
use models\summit\PresentationVideo;
/**
* Class PresentationVideoFactory
* @package factories
*/
final class PresentationVideoFactory implements IPresentationVideoFactory
{
/**
* @param array $data
* @return PresentationVideo
*/
public function build(array $data){
$video = new PresentationVideo;
$utc_now = new \DateTime();
$video->setYoutubeId(trim($data['you_tube_id']));
$video->setDateUploaded($utc_now);
if(isset($data['name']))
$video->setName(trim($data['name']));
if(isset($data['description']))
$video->setDescription(trim($data['description']));
$video->setDisplayOnSite(isset($data['display_on_site']) ? (bool)$data['display_on_site'] : true);
return $video;
}
}

View File

@ -1,11 +1,16 @@
<?php namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesCommands;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesResources;
abstract class Controller extends BaseController {
use DispatchesCommands, ValidatesRequests;
/**
* Class Controller
* @package App\Http\Controllers
*/
class Controller extends BaseController
{
use AuthorizesRequests, AuthorizesResources, DispatchesJobs, ValidatesRequests;
}

View File

@ -13,10 +13,10 @@
* limitations under the License.
**/
use Exception;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Response;
use Exception;
/**
* Class JsonController
@ -67,11 +67,13 @@ abstract class JsonController extends Controller
if (Input::has('callback')) {
$res->setCallback(Input::get('callback'));
}
return $res;
}
/**
* @param mixed $data
* @return mixed
*/
protected function ok($data = 'ok')
{
$res = Response::json($data, 200);

View File

@ -1,4 +1,4 @@
<?php
<?php namespace App\Http\Controllers;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
@ -12,8 +12,6 @@
* limitations under the License.
**/
namespace App\Http\Controllers;
use models\oauth2\IResourceServerContext;
/**

View File

@ -1,4 +1,4 @@
<?php
<?php namespace App\Http\Controllers;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
@ -12,9 +12,6 @@
* limitations under the License.
**/
namespace App\Http\Controllers;
use models\oauth2\IResourceServerContext;
/**

View File

@ -1,4 +1,4 @@
<?php
<?php namespace App\Http\Controllers;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
@ -12,8 +12,6 @@
* limitations under the License.
**/
namespace App\Http\Controllers;
use models\summit\Summit;
use models\summit\SummitAttendee;

View File

@ -1,4 +1,4 @@
<?php
<?php namespace App\Http\Controllers;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
@ -12,8 +12,6 @@
* limitations under the License.
**/
namespace App\Http\Controllers;
use models\summit\PresentationSpeaker;
use models\summit\Summit;

View File

@ -1,4 +1,4 @@
<?php
<?php namespace App\Http\Controllers;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
@ -12,7 +12,7 @@
* limitations under the License.
**/
namespace App\Http\Controllers;
use models\summit\Summit;

View File

@ -0,0 +1,133 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use models\oauth2\IResourceServerContext;
use models\summit\ISummitRepository;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request as LaravelRequest;
use Exception;
use services\model\IPresentationService;
/**
* Class OAuth2PresentationApiController
* @package App\Http\Controllers
*/
final class OAuth2PresentationApiController extends OAuth2ProtectedController
{
/**
* @var ISummitRepository
*/
private $summit_repository;
/**
* @var IPresentationService
*/
private $presentation_service;
public function __construct
(
IPresentationService $presentation_service,
ISummitRepository $summit_repository,
IResourceServerContext $resource_server_context
)
{
parent::__construct($resource_server_context);
$this->presentation_service = $presentation_service;
$this->summit_repository = $summit_repository;
}
//presentations
//videos
public function getPresentationVideos($summit_id, $presentation_id){
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository)->find($summit_id);
if (is_null($summit)) return $this->error404();
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
public function getPresentationVideo($summit_id, $presentation_id,$video_id){
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository)->find($summit_id);
if (is_null($summit)) return $this->error404();
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
public function addVideo(LaravelRequest $request, $summit_id, $presentation_id){
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository)->find($summit_id);
if (is_null($summit)) return $this->error404();
if (!$request->isJson()) {
return $this->error412(array('invalid content type!'));
}
if(!Request::isJson()) return $this->error403();
$data = Input::json();
$rules = array
(
'you_tube_id' => 'required|alpha_dash',
'name' => 'sometimes|required|text:512',
'description' => 'sometimes|required|text|max:512',
'display_on_site' => 'sometimes|required|boolean',
);
$data = $data->all();
// Creates a Validator instance and validates the data.
$validation = Validator::make($data, $rules);
if ($validation->fails()) {
$ex = new ValidationException;
$ex->setMessages($validation->messages()->toArray());
throw $ex;
}
$video = $this->presentation_service->addVideoTo($presentation_id, $data);
return $this->created($video->getId());
}
catch (EntityNotFoundException $ex1)
{
Log::warning($ex1);
return $this->error404();
}
catch (ValidationException $ex2)
{
Log::warning($ex2);
return $this->error412($ex2->getMessages());
}
catch (Exception $ex)
{
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -0,0 +1,343 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Exception;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use models\oauth2\IResourceServerContext;
use models\summit\IEventFeedbackRepository;
use models\summit\ISpeakerRepository;
use models\summit\ISummitEventRepository;
use models\summit\ISummitRepository;
use ModelSerializers\SerializerRegistry;
use services\model\ISummitService;
/**
* Class OAuth2SummitAttendeesApiController
* @package App\Http\Controllers
*/
final class OAuth2SummitAttendeesApiController extends OAuth2ProtectedController
{
/**
* @var ISummitService
*/
private $service;
/**
* @var ISpeakerRepository
*/
private $speaker_repository;
/**
* @var ISummitEventRepository
*/
private $event_repository;
/**
* @var IEventFeedbackRepository
*/
private $event_feedback_repository;
public function __construct
(
ISummitRepository $summit_repository,
ISummitEventRepository $event_repository,
ISpeakerRepository $speaker_repository,
IEventFeedbackRepository $event_feedback_repository,
ISummitService $service,
IResourceServerContext $resource_server_context
) {
parent::__construct($resource_server_context);
$this->repository = $summit_repository;
$this->speaker_repository = $speaker_repository;
$this->event_repository = $event_repository;
$this->event_feedback_repository = $event_feedback_repository;
$this->service = $service;
}
/**
* Attendees endpoints
*/
/**
* @param $summit_id
* @return mixed
*/
/*public function getAttendees($summit_id)
{
try {
$values = Input::all();
$rules = array
(
'page' => 'integer|min:1',
'per_page' => 'required_with:page|integer|min:5|max:100',
);
$validation = Validator::make($values, $rules);
if ($validation->fails()) {
$messages = $validation->messages()->toArray();
return $this->error412($messages);
}
$summit = SummitFinderStrategyFactory::build($this->repository)->find($summit_id);
if (is_null($summit)) return $this->error404();
// default values
$page = 1;
$per_page = 5;
if (Input::has('page')) {
$page = intval(Input::get('page'));
$per_page = intval(Input::get('per_page'));
}
$filter = null;
if (Input::has('filter')) {
$filter = FilterParser::parse(Input::get('filter'), array
(
'first_name' => array('=@', '=='),
'last_name' => array('=@', '=='),
'email' => array('=@', '=='),
));
}
$order = null;
if (Input::has('order'))
{
$order = OrderParser::parse(Input::get('order'), array
(
'first_name',
'last_name',
));
}
list($total, $per_page, $current_page, $last_page, $items) = $summit->attendees($page, $per_page, $filter, $order);
return $this->ok
(
array
(
'total' => $total,
'per_page' => $per_page,
'current_page' => $current_page,
'last_page' => $last_page,
'data' => $items,
)
);
}
catch (Exception $ex)
{
Log::error($ex);
return $this->error500($ex);
}
}*/
/**
* @param $summit_id
* @param $attendee_id
* @return mixed
*/
public function getAttendee($summit_id, $attendee_id)
{
$expand = Request::input('expand', '');
try {
$summit = SummitFinderStrategyFactory::build($this->repository)->find($summit_id);
if (is_null($summit)) return $this->error404();
$attendee = CheckAttendeeStrategyFactory::build(CheckAttendeeStrategyFactory::Own, $this->resource_server_context)->check($attendee_id, $summit);
if(is_null($attendee)) return $this->error404();
return $this->ok(SerializerRegistry::getInstance()->getSerializer($attendee)->serialize($expand));
}
catch (\HTTP401UnauthorizedException $ex1) {
Log::warning($ex1);
return $this->error401();
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $attendee_id
* @return mixed
*/
public function getAttendeeSchedule($summit_id, $attendee_id)
{
try {
$summit = SummitFinderStrategyFactory::build($this->repository)->find($summit_id);
if (is_null($summit)) return $this->error404();
$attendee = CheckAttendeeStrategyFactory::build(CheckAttendeeStrategyFactory::Own, $this->resource_server_context)->check($attendee_id, $summit);
if(is_null($attendee)) return $this->error404();
$schedule = array();
foreach ($attendee->getSchedule() as $attendee_schedule)
{
if(!$summit->isEventOnSchedule($attendee_schedule->getEvent()->getId())) continue;
$schedule[] = SerializerRegistry::getInstance()->getSerializer($attendee_schedule)->serialize();
}
return $this->ok($schedule);
}
catch (\HTTP401UnauthorizedException $ex1)
{
Log::warning($ex1);
return $this->error401();
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $attendee_id
* @param $event_id
* @return mixed
*/
public function addEventToAttendeeSchedule($summit_id, $attendee_id, $event_id)
{
try {
$summit = SummitFinderStrategyFactory::build($this->repository)->find($summit_id);
if (is_null($summit)) return $this->error404();
$attendee = CheckAttendeeStrategyFactory::build(CheckAttendeeStrategyFactory::Own, $this->resource_server_context)->check($attendee_id, $summit);
if (is_null($attendee)) return $this->error404();
$this->service->addEventToAttendeeSchedule($summit, $attendee, intval($event_id));
return $this->created();
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array( $ex1->getMessage()));
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
}
catch(\HTTP401UnauthorizedException $ex3)
{
Log::warning($ex3);
return $this->error401();
}
catch (Exception $ex)
{
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $attendee_id
* @param $event_id
* @return mixed
*/
public function removeEventFromAttendeeSchedule($summit_id, $attendee_id, $event_id)
{
try {
$summit = SummitFinderStrategyFactory::build($this->repository)->find($summit_id);
if (is_null($summit)) return $this->error404();
$attendee = CheckAttendeeStrategyFactory::build(CheckAttendeeStrategyFactory::Own, $this->resource_server_context)->check($attendee_id, $summit);
if (is_null($attendee)) return $this->error404();
$this->service->removeEventFromAttendeeSchedule($summit, $attendee, intval($event_id));
return $this->deleted();
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array( $ex1->getMessage()));
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
}
catch(\HTTP401UnauthorizedException $ex3)
{
Log::warning($ex3);
return $this->error401();
}
catch (Exception $ex)
{
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $attendee_id
* @param $event_id
* @return mixed
*/
public function checkingAttendeeOnEvent($summit_id, $attendee_id, $event_id)
{
try {
$summit = SummitFinderStrategyFactory::build($this->repository)->find($summit_id);
if (is_null($summit)) return $this->error404();
$attendee = CheckAttendeeStrategyFactory::build(CheckAttendeeStrategyFactory::Own, $this->resource_server_context)->check($attendee_id, $summit);
if (is_null($attendee)) return $this->error404();
$this->service->checkInAttendeeOnEvent($summit, $attendee, intval($event_id));
return $this->updated();
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array( $ex1->getMessage()));
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
}
catch(\HTTP401UnauthorizedException $ex3)
{
Log::warning($ex3);
return $this->error401();
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -0,0 +1,767 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Exception;
use Illuminate\Http\Request as LaravelRequest;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Validator;
use libs\utils\HTMLCleaner;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use models\oauth2\IResourceServerContext;
use models\summit\IEventFeedbackRepository;
use models\summit\ISpeakerRepository;
use models\summit\ISummitEventRepository;
use models\summit\ISummitRepository;
use ModelSerializers\SerializerRegistry;
use services\model\ISummitService;
use utils\FilterParser;
use utils\OrderParser;
use utils\PagingInfo;
/**
* Class OAuth2SummitEventsApiController
* @package App\Http\Controllers
*/
final class OAuth2SummitEventsApiController extends OAuth2ProtectedController
{
/**
* @var ISummitService
*/
private $service;
/**
* @var ISpeakerRepository
*/
private $speaker_repository;
/**
* @var ISummitEventRepository
*/
private $event_repository;
/**
* @var IEventFeedbackRepository
*/
private $event_feedback_repository;
public function __construct
(
ISummitRepository $summit_repository,
ISummitEventRepository $event_repository,
ISpeakerRepository $speaker_repository,
IEventFeedbackRepository $event_feedback_repository,
ISummitService $service,
IResourceServerContext $resource_server_context
) {
parent::__construct($resource_server_context);
$this->repository = $summit_repository;
$this->speaker_repository = $speaker_repository;
$this->event_repository = $event_repository;
$this->event_feedback_repository = $event_feedback_repository;
$this->service = $service;
}
/**
* Events endpoints
*/
/**
* @param $summit_id
* @return mixed
*/
public function getEvents($summit_id)
{
try
{
$strategy = new RetrieveAllSummitEventsBySummitStrategy($this->repository, $this->event_repository);
$response = $strategy->getEvents(['summit_id' => $summit_id]);
return $this->ok($response->toArray(Request::input('expand', '')));
}
catch (EntityNotFoundException $ex1)
{
Log::warning($ex1);
return $this->error404();
}
catch (ValidationException $ex2)
{
Log::warning($ex2);
return $this->error412($ex2->getMessages());
}
catch (Exception $ex)
{
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @return mixed
*/
public function getScheduledEvents($summit_id)
{
try
{
$strategy = new RetrievePublishedSummitEventsBySummitStrategy($this->repository, $this->event_repository);
$response = $strategy->getEvents(['summit_id' => $summit_id]);
return $this->ok($response->toArray(Request::input('expand', '')));
}
catch (EntityNotFoundException $ex1)
{
Log::warning($ex1);
return $this->error404();
}
catch (ValidationException $ex2)
{
Log::warning($ex2);
return $this->error412($ex2->getMessages());
}
catch (Exception $ex)
{
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @return mixed
*/
public function getAllEvents()
{
try
{
$strategy = new RetrieveAllSummitEventsStrategy($this->event_repository);
$response = $strategy->getEvents();
return $this->ok($response->toArray(Request::input('expand', '')));
}
catch (EntityNotFoundException $ex1)
{
Log::warning($ex1);
return $this->error404();
}
catch (ValidationException $ex2)
{
Log::warning($ex2);
return $this->error412($ex2->getMessages());
}
catch (Exception $ex)
{
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @return mixed
*/
public function getAllScheduledEvents()
{
try
{
$strategy = new RetrieveAllPublishedSummitEventsStrategy($this->event_repository);
$response = $strategy->getEvents();
return $this->ok($response->toArray(Request::input('expand', '')));
}
catch (EntityNotFoundException $ex1)
{
Log::warning($ex1);
return $this->error404();
}
catch (ValidationException $ex2)
{
Log::warning($ex2);
return $this->error412($ex2->getMessages());
}
catch (Exception $ex)
{
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $event_id
* @param string $expand
* @param string $fields
* @param string $relations
* @param bool $published
* @return array
* @throws EntityNotFoundException
*/
private function _getSummitEvent($summit_id, $event_id, $expand = '', $fields = '', $relations = '', $published = true)
{
$summit = SummitFinderStrategyFactory::build($this->repository)->find($summit_id);
if (is_null($summit)) throw new EntityNotFoundException;
$event = $published ? $summit->getScheduleEvent(intval($event_id)) : $summit->getEvent(intval($event_id));
if (is_null($event)) throw new EntityNotFoundException;
$relations = !empty($relations) ? explode(',', $relations) : array();
$fields = !empty($fields) ? explode(',', $fields) : array();
return SerializerRegistry::getInstance()->getSerializer($event)->serialize($expand, $fields, $relations);
}
/**
* @param $summit_id
* @param $event_id
* @return mixed
*/
public function getEvent($summit_id, $event_id)
{
try {
$expand = Request::input('expand', '');
$fields = Request::input('fields', '');
$relations = Request::input('relations', '');
return $this->ok($this->_getSummitEvent($summit_id, $event_id, $expand, $fields, $relations, false));
}
catch (EntityNotFoundException $ex1) {
Log::warning($ex1);
return $this->error404();
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $event_id
* @return mixed
*/
public function getScheduledEvent($summit_id, $event_id)
{
try {
$expand = Request::input('expand', '');
$fields = Request::input('fields', '');
$relations = Request::input('relations', '');
return $this->ok($this->_getSummitEvent($summit_id, $event_id, $expand, $fields, $relations, true));
}
catch (EntityNotFoundException $ex1) {
Log::warning($ex1);
return $this->error404();
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @return mixed
*/
public function addEvent($summit_id)
{
try {
$summit = SummitFinderStrategyFactory::build($this->repository)->find($summit_id);
if (is_null($summit)) return $this->error404();
if(!Request::isJson()) return $this->error403();
$data = Input::json();
$rules = array
(
'title' => 'required|string|max:300',
'description' => 'required|string',
'location_id' => 'sometimes|required|integer',
'start_date' => 'sometimes|required|date_format:U',
'end_date' => 'sometimes|required_with:start_date|date_format:U|after:start_date',
'allow_feedback' => 'sometimes|required|boolean',
'type_id' => 'required|integer',
'summit_types_id' => 'required|int_array',
'tags' => 'sometimes|required|string_array',
);
// Creates a Validator instance and validates the data.
$validation = Validator::make($data->all(), $rules);
if ($validation->fails()) {
$messages = $validation->messages()->toArray();
return $this->error412
(
$messages
);
}
$fields = array
(
'title',
'description'
);
$event = $this->service->addEvent($summit, HTMLCleaner::cleanData($data->all(), $fields));
return $this->created(SerializerRegistry::getInstance()->getSerializer($event)->serialize());
}
catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
}
catch(EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message'=> $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $event_id
* @return mixed
*/
public function updateEvent($summit_id, $event_id)
{
try {
$summit = SummitFinderStrategyFactory::build($this->repository)->find($summit_id);
if (is_null($summit)) return $this->error404();
if(!Request::isJson()) return $this->error403();
$data = Input::json();
$rules = array
(
'title' => 'sometimes|required|string|max:300',
'description' => 'sometimes|required|string',
'location_id' => 'sometimes|required|integer',
'start_date' => 'sometimes|required|date_format:U',
'end_date' => 'sometimes|required_with:start_date|date_format:U|after:start_date',
'allow_feedback' => 'sometimes|required|boolean',
'type_id' => 'sometimes|required|integer',
'summit_types_id' => 'sometimes|required|int_array',
'tags' => 'sometimes|required|string_array',
);
// Creates a Validator instance and validates the data.
$validation = Validator::make($data->all(), $rules);
if ($validation->fails()) {
$messages = $validation->messages()->toArray();
return $this->error412
(
$messages
);
}
$fields = array
(
'title',
'description'
);
$event = $this->service->updateEvent($summit, $event_id, HTMLCleaner::cleanData($data->all(), $fields));
return $this->ok(SerializerRegistry::getInstance()->getSerializer($event)->serialize());
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
}
catch(EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message'=> $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $event_id
* @return mixed
*/
public function publishEvent($summit_id, $event_id)
{
try {
$summit = SummitFinderStrategyFactory::build($this->repository)->find($summit_id);
if (is_null($summit)) return $this->error404();
if(!Request::isJson()) return $this->error403();
$data = Input::json();
$rules = array
(
'location_id' => 'sometimes|required|integer',
'start_date' => 'sometimes|required|date_format:U',
'end_date' => 'sometimes|required_with:start_date|date_format:U|after:start_date',
);
// Creates a Validator instance and validates the data.
$validation = Validator::make($data->all(), $rules);
if ($validation->fails()) {
$messages = $validation->messages()->toArray();
return $this->error412
(
$messages
);
}
$this->service->publishEvent($summit, $event_id, $data->all());
return $this->updated();
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
}
catch(EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message'=> $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $event_id
* @return mixed
*/
public function unPublishEvent($summit_id, $event_id)
{
try {
$summit = SummitFinderStrategyFactory::build($this->repository)->find($summit_id);
if (is_null($summit)) return $this->error404();
if(!Request::isJson()) return $this->error403();
$this->service->unPublishEvent($summit, $event_id);
return $this->deleted();
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
}
catch(EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message'=> $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $event_id
* @return mixed
*/
public function deleteEvent($summit_id, $event_id)
{
try {
$summit = SummitFinderStrategyFactory::build($this->repository)->find($summit_id);
if (is_null($summit)) return $this->error404();
$this->service->deleteEvent($summit, $event_id);
return $this->deleted();
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
}
catch(EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message'=> $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/** Feedback endpoints */
/**
* @param $summit_id
* @param $event_id
* @param $attendee_id
* @return mixed
*/
public function getEventFeedback($summit_id, $event_id, $attendee_id = null)
{
try {
$summit = SummitFinderStrategyFactory::build($this->repository)->find($summit_id);
if (is_null($summit)) return $this->error404();
$values = Input::all();
$rules = array
(
'page' => 'integer|min:1',
'per_page' => 'required_with:page|integer|min:5|max:100',
);
$validation = Validator::make($values, $rules);
if ($validation->fails()) {
$messages = $validation->messages()->toArray();
return $this->error412($messages);
}
$event = $summit->getScheduleEvent(intval($event_id));
if (is_null($event)) {
return $this->error404();
}
$filter = null;
if (!is_null($attendee_id)) // add filter by attendee, this case me
{
if($attendee_id !== 'me') return $this->error403();
$member_id = $this->resource_server_context->getCurrentUserExternalId();
if (is_null($member_id)) return $this->error404();
$filter = FilterParser::parse('owner_id=='.$member_id, array
(
'owner_id' => array('=='),
));
}
// default values
$page = 1;
$per_page = 5;
if (Input::has('page'))
{
$page = intval(Input::get('page'));
$per_page = intval(Input::get('per_page'));
}
$order = null;
if (Input::has('order'))
{
$order = OrderParser::parse(Input::get('order'), array
(
'created_date',
'owner_id',
'rate',
'id',
));
}
$response = $this->event_feedback_repository->getByEvent($event, new PagingInfo($page, $per_page), $filter, $order);
return $this->ok($response->toArray(Request::input('expand', '')));
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param LaravelRequest $request
* @param $summit_id
* @param $event_id
* @return mixed
*/
public function addEventFeedback(LaravelRequest $request, $summit_id, $event_id)
{
try {
if (!$request->isJson()) {
return $this->error412(array('invalid content type!'));
}
$summit = SummitFinderStrategyFactory::build($this->repository)->find($summit_id);
if (is_null($summit)) return $this->error404();
if(!Request::isJson()) return $this->error403();
$data = Input::json();
$rules = array
(
'rate' => 'required|integer|digits_between:0,10',
'note' => 'required|max:500',
'attendee_id' => 'required'
);
// Creates a Validator instance and validates the data.
$validation = Validator::make($data->all(), $rules);
if ($validation->fails()) {
$messages = $validation->messages()->toArray();
return $this->error412
(
$messages
);
}
$event = $summit->getScheduleEvent(intval($event_id));
if (is_null($event)) {
return $this->error404();
}
$data = $data->all();
$attendee_id = $data['attendee_id'];
$attendee = CheckAttendeeStrategyFactory::build
(
CheckAttendeeStrategyFactory::Own,
$this->resource_server_context
)->check($attendee_id, $summit);
if (is_null($attendee)) return $this->error404();
$data['attendee_id'] = intval($attendee->getId());
$res = $this->service->addEventFeedback
(
$summit,
$event,
$data
);
return !is_null($res) ? $this->created($res->getId()) : $this->error400();
}
catch (EntityNotFoundException $ex1) {
Log::warning($ex1);
return $this->error404();
}
catch(ValidationException $ex2)
{
Log::warning($ex2);
return $this->error412(array($ex2->getMessage()));
}
catch(\HTTP401UnauthorizedException $ex3)
{
Log::warning($ex3);
return $this->error401();
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param LaravelRequest $request
* @param $summit_id
* @param $event_id
* @return mixed
*/
public function addEventFeedbackByMember(LaravelRequest $request, $summit_id, $event_id)
{
try {
if (!$request->isJson()) {
return $this->error412(array('invalid content type!'));
}
$summit = SummitFinderStrategyFactory::build($this->repository)->find($summit_id);
if (is_null($summit)) return $this->error404();
if(!Request::isJson()) return $this->error403();
$data = Input::json();
$rules = array
(
'rate' => 'required|integer|digits_between:0,10',
'note' => 'required|max:500',
);
// Creates a Validator instance and validates the data.
$validation = Validator::make($data->all(), $rules);
if ($validation->fails()) {
$messages = $validation->messages()->toArray();
return $this->error412
(
$messages
);
}
$event = $summit->getScheduleEvent(intval($event_id));
if (is_null($event)) {
return $this->error404();
}
$data = $data->all();
$member_id = $this->resource_server_context->getCurrentUserExternalId();
if (is_null($member_id)) return $this->error403();
$data['member_id'] = intval($member_id);
$res = $this->service->addEventFeedback
(
$summit,
$event,
$data
);
return !is_null($res) ? $this->created($res->getId()) : $this->error400();
}
catch (EntityNotFoundException $ex1) {
Log::warning($ex1);
return $this->error404();
}
catch(ValidationException $ex2)
{
Log::warning($ex2);
return $this->error412(array($ex2->getMessage()));
}
catch(\HTTP401UnauthorizedException $ex3)
{
Log::warning($ex3);
return $this->error401();
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -0,0 +1,240 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Exception;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Validator;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use models\oauth2\IResourceServerContext;
use models\summit\IEventFeedbackRepository;
use models\summit\ISpeakerRepository;
use models\summit\ISummitEventRepository;
use models\summit\ISummitRepository;
use ModelSerializers\SerializerRegistry;
use services\model\ISummitService;
use utils\Filter;
use utils\FilterParser;
use utils\PagingInfo;
use utils\PagingResponse;
/**
* Class OAuth2SummitLocationsApiController
* @package App\Http\Controllers
*/
final class OAuth2SummitLocationsApiController extends OAuth2ProtectedController
{
/**
* @var ISummitService
*/
private $service;
/**
* @var ISpeakerRepository
*/
private $speaker_repository;
/**
* @var ISummitEventRepository
*/
private $event_repository;
/**
* @var IEventFeedbackRepository
*/
private $event_feedback_repository;
public function __construct
(
ISummitRepository $summit_repository,
ISummitEventRepository $event_repository,
ISpeakerRepository $speaker_repository,
IEventFeedbackRepository $event_feedback_repository,
ISummitService $service,
IResourceServerContext $resource_server_context
) {
parent::__construct($resource_server_context);
$this->repository = $summit_repository;
$this->speaker_repository = $speaker_repository;
$this->event_repository = $event_repository;
$this->event_feedback_repository = $event_feedback_repository;
$this->service = $service;
}
public function getLocations($summit_id)
{
try {
$summit = SummitFinderStrategyFactory::build($this->repository)->find($summit_id);
if (is_null($summit)) return $this->error404();
//locations
$locations = array();
foreach ($summit->getLocations() as $location)
{
$locations[] = SerializerRegistry::getInstance()->getSerializer($location)->serialize();
}
return $this->ok($locations);
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $location_id
* @return mixed
*/
public function getLocation($summit_id, $location_id)
{
try {
$summit = SummitFinderStrategyFactory::build($this->repository)->find($summit_id);
if (is_null($summit)) return $this->error404();
$location = $summit->getLocation($location_id);
if (is_null($location)) {
return $this->error404();
}
return $this->ok(SerializerRegistry::getInstance()->getSerializer($location)->serialize());
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param string $summit_id
* @param int $location_id
* @param bool $published
* @return PagingResponse
* @throws EntityNotFoundException
* @throws ValidationException
*/
private function _getLocationEvents($summit_id, $location_id, $published = true)
{
$summit = SummitFinderStrategyFactory::build($this->repository)->find($summit_id);
if (is_null($summit))
throw new EntityNotFoundException;
$location = $summit->getLocation($location_id);
if (is_null($location))
throw new EntityNotFoundException;
$values = Input::all();
$rules = array
(
'page' => 'integer|min:1',
'per_page' => 'required_with:page|integer|min:5|max:100',
);
$validation = Validator::make($values, $rules);
if ($validation->fails()) {
$ex = new ValidationException();
throw $ex->setMessages($validation->messages()->toArray());
}
// default values
$page = 1;
$per_page = 5;
if (Input::has('page')) {
$page = intval(Input::get('page'));
$per_page = intval(Input::get('per_page'));
}
$filter = null;
if (Input::has('filter')) {
$filter = FilterParser::parse(Input::get('filter'), array
(
'title' => array('=@', '=='),
'start_date' => array('>', '<', '<=', '>=', '=='),
'end_date' => array('>', '<', '<=', '>=', '=='),
'speaker' => array('=@', '=='),
'tags' => array('=@', '=='),
'summit_type_id' => array('=='),
'event_type_id' => array('=='),
'track_id' => array('=='),
));
}
if(is_null($filter)) $filter = new Filter();
$filter->addFilterCondition(FilterParser::buildFilter('location_id','==', $location_id));
if($published)
{
$filter->addFilterCondition(FilterParser::buildFilter('published','==', 1));
}
return $this->event_repository->getAllByPage(new PagingInfo($page, $per_page), $filter);
}
/**
* @param $summit_id
* @param $location_id
* @return mixed
*/
public function getLocationEvents($summit_id, $location_id)
{
try {
return $this->ok($this->_getLocationEvents($summit_id, $location_id, false)->toArray(Request::input('expand', '')));
}
catch (EntityNotFoundException $ex1) {
Log::warning($ex1);
return $this->error404();
}
catch (ValidationException $ex2) {
Log::warning($ex2);
return $this->error412($ex2->getMessages());
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $location_id
* @return mixed
*/
public function getLocationPublishedEvents($summit_id, $location_id)
{
try {
return $this->ok($this->_getLocationEvents($summit_id, $location_id, true)->toArray(Request::input('expand', '')));
}
catch (EntityNotFoundException $ex1) {
Log::warning($ex1);
return $this->error404();
}
catch (ValidationException $ex2) {
Log::warning($ex2);
return $this->error412($ex2->getMessages());
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -0,0 +1,86 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Exception;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Validator;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use Models\foundation\main\repositories\IMemberRepository;
use models\oauth2\IResourceServerContext;
use models\summit\IEventFeedbackRepository;
use models\summit\ISpeakerRepository;
use models\summit\ISummitEventRepository;
use models\summit\ISummitRepository;
use ModelSerializers\SerializerRegistry;
use services\model\ISummitService;
use utils\Filter;
use utils\FilterParser;
use utils\PagingInfo;
use utils\PagingResponse;
/**
* Class OAuth2SummitMembersApiController
* @package App\Http\Controllers
*/
final class OAuth2SummitMembersApiController extends OAuth2ProtectedController
{
/**
* @var ISummitRepository
*/
private $summit_repository;
/**
* OAuth2SummitMembersApiController constructor.
* @param IMemberRepository $member_repository
* @param ISummitRepository $summit_repository
* @param IResourceServerContext $resource_server_context
*/
public function __construct
(
IMemberRepository $member_repository,
ISummitRepository $summit_repository,
IResourceServerContext $resource_server_context
) {
parent::__construct($resource_server_context);
$this->summit_repository = $summit_repository;
$this->repository = $member_repository;
}
public function getMyMember($summit_id){
$summit = SummitFinderStrategyFactory::build($this->summit_repository)->find($summit_id);
if (is_null($summit)) return $this->error404();
$current_member_id = $this->resource_server_context->getCurrentUserExternalId();
if (is_null($current_member_id)) return $this->error403();
$current_member = $this->repository->getById($current_member_id);
if (is_null($current_member)) return $this->error404();
return $this->ok
(
SerializerRegistry::getInstance()->getSerializer($current_member)->serialize
(
Request::input('expand', ''),
[],
[],
['summit' => $summit]
)
);
}
}

View File

@ -0,0 +1,178 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Exception;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Validator;
use models\oauth2\IResourceServerContext;
use models\summit\IEventFeedbackRepository;
use models\summit\ISpeakerRepository;
use models\summit\ISummitEventRepository;
use models\summit\ISummitRepository;
use ModelSerializers\SerializerRegistry;
use services\model\ISummitService;
use utils\FilterParser;
use utils\OrderParser;
use utils\PagingInfo;
/**
* Class OAuth2SummitSpeakersApiController
* @package App\Http\Controllers
*/
final class OAuth2SummitSpeakersApiController extends OAuth2ProtectedController
{
/**
* @var ISummitService
*/
private $service;
/**
* @var ISpeakerRepository
*/
private $speaker_repository;
/**
* @var ISummitEventRepository
*/
private $event_repository;
/**
* @var IEventFeedbackRepository
*/
private $event_feedback_repository;
public function __construct
(
ISummitRepository $summit_repository,
ISummitEventRepository $event_repository,
ISpeakerRepository $speaker_repository,
IEventFeedbackRepository $event_feedback_repository,
ISummitService $service,
IResourceServerContext $resource_server_context
) {
parent::__construct($resource_server_context);
$this->repository = $summit_repository;
$this->speaker_repository = $speaker_repository;
$this->event_repository = $event_repository;
$this->event_feedback_repository = $event_feedback_repository;
$this->service = $service;
}
/**
* Speakers endpoints
*/
/**
* @param $summit_id
* @return mixed
*/
public function getSpeakers($summit_id)
{
try {
$summit = SummitFinderStrategyFactory::build($this->repository)->find($summit_id);
if (is_null($summit)) return $this->error404();
$values = Input::all();
$rules = array
(
'page' => 'integer|min:1',
'per_page' => 'required_with:page|integer|min:10|max:100',
);
$validation = Validator::make($values, $rules);
if ($validation->fails())
{
$messages = $validation->messages()->toArray();
return $this->error412($messages);
}
// default values
$page = 1;
$per_page = 10;
if (Input::has('page'))
{
$page = intval(Input::get('page'));
$per_page = intval(Input::get('per_page'));
}
$filter = null;
if (Input::has('filter'))
{
$filter = FilterParser::parse(Input::get('filter'), array
(
'first_name' => array('=@', '=='),
'last_name' => array('=@', '=='),
'email' => array('=@', '=='),
));
}
$order = null;
if (Input::has('order'))
{
$order = OrderParser::parse(Input::get('order'), array
(
'first_name',
'last_name',
));
}
$result = $this->speaker_repository->getSpeakersBySummit($summit, new PagingInfo($page, $per_page), $filter, $order);
return $this->ok
(
$result->toArray(Request::input('expand', ''),[],[],['summit_id' => $summit_id, 'published' => true])
);
}
catch (Exception $ex)
{
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $speaker_id
* @return mixed
*/
public function getSpeaker($summit_id, $speaker_id)
{
try
{
$summit = SummitFinderStrategyFactory::build($this->repository)->find($summit_id);
if (is_null($summit)) return $this->error404();
$speaker = CheckSpeakerStrategyFactory::build(CheckSpeakerStrategyFactory::Me, $this->resource_server_context)->check($speaker_id, $summit);
if (is_null($speaker)) return $this->error404();
return $this->ok(SerializerRegistry::getInstance()->getSerializer($speaker)->serialize(Request::input('expand', '')));
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -1,4 +1,4 @@
<?php
<?php namespace App\Http\Controllers;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
@ -12,7 +12,7 @@
* limitations under the License.
**/
namespace App\Http\Controllers;
use models\utils\IBaseRepository;

View File

@ -1,4 +1,4 @@
<?php
<?php namespace App\Http\Controllers;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
@ -12,8 +12,6 @@
* limitations under the License.
**/
namespace App\Http\Controllers;
use models\oauth2\IResourceServerContext;
use models\summit\PresentationSpeaker;
use models\summit\Summit;
@ -40,7 +38,7 @@ class CheckMeSpeakerStrategy implements ICheckSpeakerStrategy
}
/**
* @param mixed $speaker_id
* @param int $speaker_id
* @param Summit $summit
* @return null|PresentationSpeaker
*/
@ -49,11 +47,11 @@ class CheckMeSpeakerStrategy implements ICheckSpeakerStrategy
if (strtolower($speaker_id) === 'me') {
$member_id = $this->resource_server_context->getCurrentUserExternalId();
if (is_null($member_id)) {
return $this->error404();
return null;
}
$speaker = $summit->getSpeakerByMemberId($member_id);
} else {
$speaker = $summit->getSpeakerById(intval($speaker_id));
$speaker = $summit->getSpeaker(intval($speaker_id));
}
return $speaker;
}

View File

@ -35,7 +35,7 @@ final class CheckMyOwnAttendeeStrategy extends CheckMeAttendeeStrategy implement
{
$attendee = parent::check($attendee_id, $summit);
if(!$attendee) return null;
$attendee_member_id = intval($attendee->member()->ID);
$attendee_member_id = intval($attendee->getMember()->getId());
$member_id = $this->resource_server_context->getCurrentUserExternalId();
if(is_null($member_id) || ($attendee_member_id !== $member_id)) throw new \HTTP401UnauthorizedException;
return $attendee;

View File

@ -14,8 +14,8 @@
namespace App\Http\Controllers;
use models\summit\ISummitRepository;
use models\summit\Summit;
use repositories\summit\EloquentSummitRepository;
/**
* Class CurrentSummitFinderStrategy
@ -25,11 +25,11 @@ class CurrentSummitFinderStrategy implements ISummitFinderStrategy
{
/**
* @var EloquentSummitRepository
* @var ISummitRepository
*/
private $repository;
public function __construct(EloquentSummitRepository $repository)
public function __construct(ISummitRepository $repository)
{
$this->repository = $repository;
}

View File

@ -1,138 +0,0 @@
<?php
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
namespace App\Http\Controllers;
use models\exceptions\ValidationException;
use Request;
use utils\Filter;
use utils\PagingResponse;
use Validator;
use Input;
use Log;
use utils\FilterParser;
/**
* Class RetrieveSummitEventsStrategy
* @package App\Http\Controllers
*/
abstract class RetrieveSummitEventsStrategy
{
/**
* @param array $params
* @return PagingResponse
* @throws ValidationException
*/
public function getEvents(array $params = array())
{
$values = Input::all();
$rules = array
(
'page' => 'integer|min:1',
'per_page' => 'required_with:page|integer|min:5|max:100',
);
$validation = Validator::make($values, $rules);
if ($validation->fails()) {
$ex = new ValidationException();
throw $ex->setMessages($validation->messages()->toArray());
}
$expand = Request::input('expand', '');
// default values
$page = 1;
$per_page = 5;
if (Input::has('page')) {
$page = intval(Input::get('page'));
$per_page = intval(Input::get('per_page'));
}
$filter = null;
if (Input::has('filter')) {
$filter = FilterParser::parse(Input::get('filter'), $this->getValidFilters());
}
$events = array();
list($total, $per_page, $current_page, $last_page, $items) = $this->retrieveEventsFromSource
(
$page, $per_page, $filter
);
foreach ($items as $event) {
$data = $event->toArray();
if (!empty($expand)) {
foreach (explode(',', $expand) as $relation) {
switch (trim($relation)) {
case 'feedback': {
$feedback = array();
list($total2, $per_page2, $current_page2, $last_page2, $items2) = $event->feedback(1,
PHP_INT_MAX);
foreach ($items2 as $f) {
array_push($feedback, $f->toArray());
}
$data['feedback'] = $feedback;
}
break;
case 'location': {
$location = $event->getLocation();
if(is_null($location)) continue;
$data['location'] = $location->toArray();
unset($data['location_id']);
}
break;
}
}
}
array_push($events, $data);
}
return new PagingResponse
(
$total,
$per_page,
$current_page,
$last_page,
$events
);
}
/**
* @param $page
* @param $per_page
* @param Filter|null $filter
* @return array
*/
abstract public function retrieveEventsFromSource($page, $per_page, Filter $filter = null);
/**
* @return array
*/
protected function getValidFilters()
{
return array
(
'title' => array('=@', '=='),
'tags' => array('=@', '=='),
'start_date' => array('>', '<', '<=', '>=', '=='),
'end_date' => array('>', '<', '<=', '>=', '=='),
'summit_type_id' => array('=='),
'event_type_id' => array('=='),
);
}
}

View File

@ -1,4 +1,4 @@
<?php
<?php namespace App\Http\Controllers;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
@ -11,10 +11,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
**/
namespace App\Http\Controllers;
use utils\Filter;
use utils\FilterParser;
/**
* Class RetrieveAllPublishedSummitEventsStrategy
@ -24,13 +22,22 @@ final class RetrieveAllPublishedSummitEventsStrategy extends RetrieveAllSummitEv
{
/**
* @param $page
* @param $per_page
* @param Filter|null $filter
* @return array
* @return array
*/
public function retrieveEventsFromSource($page, $per_page, Filter $filter = null)
protected function getValidFilters()
{
return $this->event_repository->getAllPublishedByPage($page, $per_page, $filter);
$valid_filters = parent::getValidFilters();
$valid_filters['published'] = array('==');
return $valid_filters;
}
/**
* @return null|Filter
*/
protected function buildFilter()
{
$filter = parent::buildFilter();
$filter->addFilterCondition(FilterParser::buildFilter('published','==','1'));
return $filter;
}
}

View File

@ -1,4 +1,5 @@
<?php
<?php namespace App\Http\Controllers;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
@ -12,19 +13,21 @@
* limitations under the License.
**/
namespace App\Http\Controllers;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use models\summit\ISummitEventRepository;
use models\summit\ISummitRepository;
use models\summit\Summit;
use utils\Filter;
use utils\FilterParser;
use utils\PagingInfo;
use utils\PagingResponse;
/**
* Class RetrieveSummitEventsBySummitStrategy
* @package App\Http\Controllers
*/
abstract class RetrieveSummitEventsBySummitStrategy extends RetrieveSummitEventsStrategy
class RetrieveAllSummitEventsBySummitStrategy extends RetrieveSummitEventsStrategy
{
/**
* @var ISummitRepository
@ -37,11 +40,17 @@ abstract class RetrieveSummitEventsBySummitStrategy extends RetrieveSummitEvents
protected $summit;
/**
* RetrieveSummitEventsBySummitStrategy constructor.
* @param ISummitRepository $summit_repository
* @var ISummitEventRepository
*/
public function __construct(ISummitRepository $summit_repository)
protected $events_repository;
public function __construct
(
ISummitRepository $summit_repository,
ISummitEventRepository $events_repository
)
{
$this->events_repository = $events_repository;
$this->summit_repository = $summit_repository;
}
@ -53,10 +62,46 @@ abstract class RetrieveSummitEventsBySummitStrategy extends RetrieveSummitEvents
*/
public function getEvents(array $params = array())
{
$summit_id = isset($params['summit_id'])? $params['summit_id']:0;
$summit_id = isset($params['summit_id'])? $params['summit_id']:0;
$this->summit = SummitFinderStrategyFactory::build($this->summit_repository)->find($summit_id);
if (is_null($this->summit)) throw new EntityNotFoundException;
if (is_null($this->summit)) throw new EntityNotFoundException('summit not found!');
return parent::getEvents($params);
}
/**
* @return array
*/
protected function getValidFilters()
{
$valid_filters = parent::getValidFilters();
$valid_filters['summit_id'] = array('==');
return $valid_filters;
}
/**
* @return null|Filter
*/
protected function buildFilter(){
$filter = parent::buildFilter();
if(is_null($filter))
{
$filter = new Filter([]);
}
$filter->addFilterCondition(FilterParser::buildFilter('summit_id','==',$this->summit->getId()));
return $filter;
}
/**
* @param PagingInfo $paging_info
* @param Filter|null $filter
* @return PagingResponse
*/
public function retrieveEventsFromSource(PagingInfo $paging_info, Filter $filter = null)
{
return $this->events_repository->getAllByPage($paging_info, $filter);
}
}

View File

@ -16,6 +16,8 @@ namespace App\Http\Controllers;
use models\summit\ISummitEventRepository;
use utils\Filter;
use utils\PagingInfo;
use utils\PagingResponse;
/**
* Class RetrieveAllSummitEventsStrategy
@ -38,14 +40,13 @@ class RetrieveAllSummitEventsStrategy extends RetrieveSummitEventsStrategy
}
/**
* @param $page
* @param $per_page
* @param PagingInfo $paging_info
* @param Filter|null $filter
* @return array
* @return PagingResponse
*/
public function retrieveEventsFromSource($page, $per_page, Filter $filter = null)
public function retrieveEventsFromSource(PagingInfo $paging_info, Filter $filter = null)
{
return $this->event_repository->getAllByPage($page, $per_page, $filter);
return $this->event_repository->getAllByPage($paging_info, $filter);
}
/**

View File

@ -1,4 +1,4 @@
<?php
<?php namespace App\Http\Controllers;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
@ -12,25 +12,34 @@
* limitations under the License.
**/
namespace App\Http\Controllers;
use utils\Filter;
use utils\FilterParser;
/**
* Class RetrievePublishedSummitEventsBySummitStrategy
* @package App\Http\Controllers
*/
final class RetrievePublishedSummitEventsBySummitStrategy extends RetrieveSummitEventsBySummitStrategy
final class RetrievePublishedSummitEventsBySummitStrategy extends RetrieveAllSummitEventsBySummitStrategy
{
/**
* @param $page
* @param $per_page
* @param Filter|null $filter
* @return array
*/
public function retrieveEventsFromSource($page, $per_page, Filter $filter = null)
protected function getValidFilters()
{
return $this->summit->schedule($page, $per_page, $filter);
$valid_filters = parent::getValidFilters();
$valid_filters['published'] = array('==');
return $valid_filters;
}
/**
* @return null|Filter
*/
protected function buildFilter()
{
$filter = parent::buildFilter();
$filter->addFilterCondition(FilterParser::buildFilter('published','==','1'));
return $filter;
}
}

View File

@ -0,0 +1,98 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use models\exceptions\ValidationException;
use utils\Filter;
use utils\PagingResponse;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
use utils\FilterParser;
use utils\PagingInfo;
/**
* Class RetrieveSummitEventsStrategy
* @package App\Http\Controllers
*/
abstract class RetrieveSummitEventsStrategy
{
/**
* @param array $params
* @return PagingResponse
* @throws ValidationException
*/
public function getEvents(array $params = array())
{
$values = Input::all();
$rules = array
(
'page' => 'integer|min:1',
'per_page' => 'required_with:page|integer|min:5|max:100',
);
$validation = Validator::make($values, $rules);
if ($validation->fails()) {
$ex = new ValidationException();
throw $ex->setMessages($validation->messages()->toArray());
}
// default values
$page = 1;
$per_page = 5;
if (Input::has('page')) {
$page = intval(Input::get('page'));
$per_page = intval(Input::get('per_page'));
}
return $this->retrieveEventsFromSource
(
new PagingInfo($page, $per_page), $this->buildFilter()
);
}
/**
* @return null|Filter
*/
protected function buildFilter(){
$filter = null;
if (Input::has('filter')) {
$filter = FilterParser::parse(Input::get('filter'), $this->getValidFilters());
}
return $filter;
}
/**
* @param PagingInfo $paging_info
* @param Filter|null $filter
* @return PagingResponse
*/
abstract public function retrieveEventsFromSource(PagingInfo $paging_info, Filter $filter = null);
/**
* @return array
*/
protected function getValidFilters()
{
return array
(
'title' => array('=@', '=='),
'tags' => array('=@', '=='),
'start_date' => array('>', '<', '<=', '>=', '=='),
'end_date' => array('>', '<', '<=', '>=', '=='),
'summit_type_id' => array('=='),
'event_type_id' => array('=='),
);
}
}

View File

@ -1,37 +1,57 @@
<?php namespace App\Http;
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
'Illuminate\Cookie\Middleware\EncryptCookies',
'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
'Illuminate\Session\Middleware\StartSession',
'Illuminate\View\Middleware\ShareErrorsFromSession',
'App\Http\Middleware\CORSMiddleware',
'App\Http\Middleware\SecurityHTTPHeadersWriterMiddleware',
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\CORSMiddleware::class,
\App\Http\Middleware\SecurityHTTPHeadersWriterMiddleware::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
],
'api' => [
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => 'App\Http\Middleware\Authenticate',
'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
'oauth2.protected' => 'App\Http\Middleware\OAuth2BearerAccessTokenRequestValidator',
'rate.limit' => 'App\Http\Middleware\RateLimitMiddleware',
'etags' => 'App\Http\Middleware\ETagsMiddleware',
'cache' => 'App\Http\Middleware\CacheMiddleware',
'ssl' => 'App\Http\Middleware\SSLMiddleware',
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'oauth2.protected' => \App\Http\Middleware\OAuth2BearerAccessTokenRequestValidator::class,
'rate.limit' => \App\Http\Middleware\RateLimitMiddleware::class,
'etags' => \App\Http\Middleware\ETagsMiddleware::class,
'cache' => \App\Http\Middleware\CacheMiddleware::class,
'ssl' => \App\Http\Middleware\SSLMiddleware::class,
];
}
}

View File

@ -1,50 +1,30 @@
<?php namespace App\Http\Middleware;
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Support\Facades\Auth;
class Authenticate {
/**
* The Guard implementation.
*
* @var Guard
*/
protected $auth;
/**
* Create a new filter instance.
*
* @param Guard $auth
* @return void
*/
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($this->auth->guest())
{
if ($request->ajax())
{
return response('Unauthorized.', 401);
}
else
{
return redirect()->guest('auth/login');
}
}
return $next($request);
}
class Authenticate
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('login');
}
}
return $next($request);
}
}

View File

@ -16,7 +16,6 @@ use Closure;
use libs\utils\ICacheService;
use models\resource_server\IApiEndpoint;
use models\resource_server\IApiEndpointRepository;
use Illuminate\Contracts\Routing\Middleware;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\Cache;
@ -30,7 +29,7 @@ use libs\utils\RequestUtils;
* @package App\Http\Middleware\
* Implementation of http://www.w3.org/TR/cors/
*/
class CORSMiddleware implements Middleware
class CORSMiddleware
{
const CORS_IP_BLACKLIST_PREFIX = 'CORS_IP_BLACKLIST_PREFIX:';

View File

@ -1,4 +1,4 @@
<?php
<?php namespace App\Http\Middleware;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
@ -12,21 +12,18 @@
* limitations under the License.
**/
namespace App\Http\Middleware;
use Closure;
use Config;
use Illuminate\Contracts\Routing\Middleware;
use Illuminate\Support\Facades\Config;
use Illuminate\Http\JsonResponse;
use libs\utils\ICacheService;
use Log;
use Illuminate\Support\Facades\Log;
use models\oauth2\IResourceServerContext;
/**
* Class CacheMiddleware
* @package App\Http\Middleware
*/
final class CacheMiddleware implements Middleware
final class CacheMiddleware
{
/**
* @var ICacheService
@ -53,9 +50,10 @@ final class CacheMiddleware implements Middleware
*/
public function handle($request, Closure $next)
{
Log::debug('cache middleware invoked ...');
if ($request->getMethod() !== 'GET')
{
// shortcircuit
// short circuit
return $next($request);
}

View File

@ -14,17 +14,15 @@
**/
use Closure;
use Illuminate\Contracts\Routing\Middleware;
use Log;
use Illuminate\Support\Facades\Log;
/**
* Class ETagsMiddleware
* @package App\Http\Middleware
*/
final class ETagsMiddleware implements Middleware
final class ETagsMiddleware
{
/**
* Handle an incoming request.
* @param \Illuminate\Http\Request $request

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as BaseEncrypter;
class EncryptCookies extends BaseEncrypter
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array
*/
protected $except = [
//
];
}

View File

@ -14,7 +14,6 @@
**/
use Closure;
use Illuminate\Contracts\Routing\Middleware;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
@ -35,7 +34,7 @@ use URL\Normalizer;
* http://tools.ietf.org/html/rfc6749#section-7
* @package App\Http\Middleware
*/
class OAuth2BearerAccessTokenRequestValidator implements Middleware
class OAuth2BearerAccessTokenRequestValidator
{
/**

View File

@ -14,7 +14,6 @@
**/
use Closure;
use Illuminate\Contracts\Routing\Middleware;
use Illuminate\Support\Facades\Response;
use libs\utils\ICacheService;
use libs\utils\RequestUtils;
@ -24,7 +23,7 @@ use models\resource_server\IApiEndpointRepository;
* Class RateLimitMiddleware
* @package App\Http\Middleware
*/
final class RateLimitMiddleware implements Middleware
final class RateLimitMiddleware
{
/**

View File

@ -1,44 +1,26 @@
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated {
/**
* The Guard implementation.
*
* @var Guard
*/
protected $auth;
/**
* Create a new filter instance.
*
* @param Guard $auth
* @return void
*/
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($this->auth->check())
{
return new RedirectResponse(url('/home'));
}
return $next($request);
}
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/');
}
return $next($request);
}
}

View File

@ -1,4 +1,4 @@
<?php
<?php namespace App\Http\Middleware;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
@ -12,19 +12,16 @@
* limitations under the License.
**/
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Request;
use Illuminate\Contracts\Routing\Middleware;
/**
* Class SSLMiddleware
* @package App\Http\Middleware
*/
final class SSLMiddleware implements Middleware
final class SSLMiddleware
{
public function handle($request, Closure $next)
{

View File

@ -13,7 +13,6 @@
**/
use Closure;
use Illuminate\Contracts\Routing\Middleware;
/**
* Class SecurityHTTPHeadersWriterMiddleware
@ -21,7 +20,7 @@ use Illuminate\Contracts\Routing\Middleware;
*
* @package App\Http\Middleware
*/
class SecurityHTTPHeadersWriterMiddleware implements Middleware
class SecurityHTTPHeadersWriterMiddleware
{
/**
* Handle an incoming request.

View File

@ -1,20 +1,17 @@
<?php namespace App\Http\Middleware;
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier {
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return parent::handle($request, $next);
}
}
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
//
];
}

View File

@ -1,9 +1,10 @@
<?php namespace App\Http\Requests;
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
abstract class Request extends FormRequest {
//
abstract class Request extends FormRequest
{
//
}

View File

@ -0,0 +1,71 @@
<?php namespace utils;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\QueryBuilder;
/**
* Class DoctrineJoinFilterMapping
* @package utils
*/
class DoctrineJoinFilterMapping extends FilterMapping
{
/**
* @var string
*/
private $alias;
/**
* DoctrineJoinFilterMapping constructor.
* @param string $table
* @param string $alias
* @param string $where
*/
public function __construct($table, $alias, $where)
{
parent::__construct($table, $where);
$this->alias = $alias;
}
/**
* @param FilterElement $filter
* @throws \Exception
*/
public function toRawSQL(FilterElement $filter)
{
throw new \Exception;
}
/**
* @param QueryBuilder $query
* @param FilterElement $filter
* @return QueryBuilder
*/
public function apply(QueryBuilder $query, FilterElement $filter){
$where = str_replace(":value", $filter->getValue(), $this->where);
$where = str_replace(":operator", $filter->getOperator(), $where);
return $query->innerJoin($this->table, $this->alias, Join::WITH, $where);
}
/**
* @param QueryBuilder $query
* @param FilterElement $filter
* @return QueryBuilder
*/
public function applyOr(QueryBuilder $query, FilterElement $filter){
$where = str_replace(":value", $filter->getValue(), $this->where);
$where = str_replace(":operator", $filter->getOperator(), $where);
return $query->innerJoin($this->table, $this->alias, Join::WITH)->orWhere($where);
}
}

View File

@ -1,55 +0,0 @@
<?php
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
namespace utils;
/**
* Class ExistsFilterManyManyMapping
* @package utils
*/
class ExistsFilterManyManyMapping extends JoinFilterMapping
{
/**
* @var string
*/
private $pivot_table;
/**
* ExistsFilterManyManyMapping constructor.
* @param string $table
* @param string $pivot_table
* @param string $join
* @param string $where
*/
public function __construct($table, $pivot_table, $join, $where)
{
parent::__construct($table, $join, $where);
$this->pivot_table = $pivot_table;
}
/**
* @param FilterElement $filter
* @return string
*/
public function toRawSQL(FilterElement $filter)
{
$where = str_replace(":value", $filter->getValue(), $this->where);
$where = str_replace(":operator", $filter->getOperator(), $where);
$sql = <<<SQL
EXISTS ( SELECT 1 FROM {$this->table} INNER JOIN {$this->pivot_table} ON {$this->join} WHERE {$where} )
SQL;
return $sql;
}
}

View File

@ -1,47 +0,0 @@
<?php
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
namespace utils;
/**
* Class ExistsFilterManyToOneMapping
* @package utils
*/
class ExistsFilterManyToOneMapping extends FilterMapping
{
/**
* ExistsFilterManyToOneMapping constructor.
* @param string $table
* @param string $where
*/
public function __construct($table, $where)
{
parent::__construct($table, $where);
}
/**
* @param FilterElement $filter
* @return string
*/
public function toRawSQL(FilterElement $filter)
{
$where = str_replace(":value", $filter->getValue(), $this->where);
$where = str_replace(":operator", $filter->getOperator(), $where);
$sql = <<<SQL
EXISTS ( SELECT 1 FROM {$this->table} WHERE {$where} )
SQL;
return $sql;
}
}

View File

@ -1,8 +1,5 @@
<?php namespace utils;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\Relation;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
@ -15,6 +12,14 @@ use Illuminate\Database\Eloquent\Relations\Relation;
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Doctrine\Common\Collections\Criteria;
use Doctrine\ORM\QueryBuilder;
/**
* Class Filter
* @package utils
*/
final class Filter
{
/**
@ -27,11 +32,21 @@ final class Filter
*/
private $bindings = array();
public function __construct($filters)
public function __construct(array $filters = [])
{
$this->filters = $filters;
}
/**
* @param FilterElement $filter
* @return $this
*/
public function addFilterCondition(FilterElement $filter)
{
$this->filters[] = $filter;
return $this;
}
/**
* @param string $field
* @return null|FilterElement[]
@ -39,83 +54,111 @@ final class Filter
public function getFilter($field)
{
$res = array();
foreach($this->filters as $filter)
{
if($filter instanceof FilterElement && $filter->getField() === $field) {
array_push($res, $filter);
}
else if(is_array($filter))
{
foreach ($this->filters as $filter) {
if ($filter instanceof FilterElement && $filter->getField() === $field) {
$res[] = $filter;
} else if (is_array($filter)) {
// OR
$or_res = array();
foreach($filter as $e)
{
if($e instanceof FilterElement && $e->getField() === $field)
{
foreach ($filter as $e) {
if ($e instanceof FilterElement && $e->getField() === $field) {
array_push($or_res, $e);
}
}
if(count($or_res)) array_push($res, $or_res);
if (count($or_res)) array_push($res, $or_res);
}
}
return $res;
}
/**
* @param $relation
* @param Criteria $criteria
* @param array $mappings
* @return $this
* @return Criteria
*/
public function apply2Relation($relation, array $mappings)
public function apply2Criteria(Criteria $criteria, array $mappings)
{
$builder = $relation instanceof Relation ? $relation->getQuery(): $relation;
if(!$builder instanceof Builder) throw new \InvalidArgumentException;
foreach($this->filters as $filter)
{
if($filter instanceof FilterElement)
{
if(isset($mappings[$filter->getField()]))
{
foreach ($this->filters as $filter) {
if ($filter instanceof FilterElement) {
if (isset($mappings[$filter->getField()])) {
$mapping = $mappings[$filter->getField()];
if($mapping instanceof FilterMapping)
{
$builder->whereRaw($mapping->toRawSQL($filter));
if ($mapping instanceof FilterMapping) {
continue;
}
else {
$mapping = explode(':', $mapping);
$value = $filter->getValue();
if (count($mapping) > 1) {
$value = $this->convertValue($value, $mapping[1]);
}
$criteria->andWhere(Criteria::expr()->eq($mapping[0], $value));
}
} else if (is_array($filter)) {
// OR
foreach ($filter as $e) {
if ($e instanceof FilterElement && isset($mappings[$e->getField()])) {
$mapping = $mappings[$e->getField()];
if ($mapping instanceof FilterMapping) {
continue;
}
$mapping = explode(':', $mapping);
$value = $filter->getValue();
if (count($mapping) > 1) {
$value = $this->convertValue($value, $mapping[1]);
}
$builder->where($mapping[0], $filter->getOperator(), $value);
$criteria->orWhere(Criteria::expr()->eq($mapping[0], $value));
}
}
}
else if(is_array($filter))
{
}
return $criteria;
}
/**
* @param QueryBuilder $query
* @param array $mappings
* @return $this
*/
public function apply2Query(QueryBuilder $query, array $mappings)
{
foreach ($this->filters as $filter) {
if ($filter instanceof FilterElement && isset($mappings[$filter->getField()])) {
$mapping = $mappings[$filter->getField()];
if ($mapping instanceof DoctrineJoinFilterMapping) {
$query = $mapping->apply($query, $filter);
continue;
}
$mapping = explode(':', $mapping);
$value = $filter->getValue();
if (count($mapping) > 1) {
$value = $this->convertValue($value, $mapping[1]);
}
$query = $query->where($mapping[0] . ' ' . $filter->getOperator() . ' ' . $value);
}
else if (is_array($filter)) {
// OR
$builder->where(function ($query) use($filter, $mappings){
foreach($filter as $e) {
if($e instanceof FilterElement && isset($mappings[$e->getField()]))
{
$mapping = $mappings[$e->getField()];
if($mapping instanceof FilterMapping)
{
$query->orWhereRaw($mapping->toRawSQL($e));
}
else
{
$mapping = explode(':', $mapping);
$value = $filter->getValue();
if (count($mapping) > 1) {
$value = $this->convertValue($value, $mapping[1]);
}
$query->orWhere($mapping[0], $e->getOperator(), $value);
}
foreach ($filter as $e) {
if ($e instanceof FilterElement && isset($mappings[$e->getField()])) {
$mapping = $mappings[$e->getField()];
if ($mapping instanceof DoctrineJoinFilterMapping) {
$query = $mapping->applyOr($query, $e);
continue;
}
$mapping = explode(':', $mapping);
$value = $filter->getValue();
if (count($mapping) > 1) {
$value = $this->convertValue($value, $mapping[1]);
}
$query->orWhere($mapping[0], $e->getOperator(), $value);
}
});
}
}
}
return $this;
@ -128,11 +171,10 @@ final class Filter
*/
private function convertValue($value, $original_format)
{
switch($original_format)
{
switch ($original_format) {
case 'datetime_epoch':
$datetime = new \DateTime("@$value");
return $datetime->format("Y-m-d H:i:s");
return sprintf("'%s'", $datetime->format("Y-m-d H:i:s"));
break;
case 'json_int':
return intval($value);
@ -150,59 +192,51 @@ final class Filter
{
return $this->bindings;
}
/**
* @param array $mappings
* @return string
*/
public function toRawSQL(array $mappings)
{
$sql = '';
$sql = '';
$this->bindings = array();
foreach($this->filters as $filter)
{
if($filter instanceof FilterElement)
{
if(isset($mappings[$filter->getField()]))
{
foreach ($this->filters as $filter) {
if ($filter instanceof FilterElement) {
if (isset($mappings[$filter->getField()])) {
$mapping = $mappings[$filter->getField()];
$mapping = explode(':', $mapping);
$value = $filter->getValue();
$op = $filter->getOperator();
if(count($mapping) > 1)
{
$filter->setValue( $this->convertValue($value, $mapping[1]));
$value = $filter->getValue();
$op = $filter->getOperator();
if (count($mapping) > 1) {
$filter->setValue($this->convertValue($value, $mapping[1]));
}
$cond = sprintf(' %s %s :%s', $mapping[0], $op, $filter->getField());
$this->bindings[$filter->getField()] = $filter->getValue();
if(!empty($sql)) $sql .= " AND ";
$cond = sprintf(' %s %s :%s', $mapping[0], $op, $filter->getField());
$this->bindings[$filter->getField()] = $filter->getValue();
if (!empty($sql)) $sql .= " AND ";
$sql .= $cond;
}
}
else if(is_array($filter))
{
} else if (is_array($filter)) {
// OR
$sql .= " ( ";
$sql_or = '';
foreach($filter as $e)
{
if($e instanceof FilterElement && isset($mappings[$e->getField()]))
{
foreach ($filter as $e) {
if ($e instanceof FilterElement && isset($mappings[$e->getField()])) {
$mapping = $mappings[$e->getField()];
$mapping = explode(':', $mapping);
$value = $e->getValue();
$op = $e->getOperator();
if(count($mapping) > 1)
{
$e->setValue( $this->convertValue($value, $mapping[1]));
$value = $e->getValue();
$op = $e->getOperator();
if (count($mapping) > 1) {
$e->setValue($this->convertValue($value, $mapping[1]));
}
$cond = sprintf(' %s %s :%s', $mapping[0], $op, $e->getField());
$this->bindings[$e->getField()] = $e->getValue();
if(!empty($sql_or)) $sql_or .= " OR ";
$cond = sprintf(" %s %s :%s", $mapping[0], $op, $e->getField());
$this->bindings[$e->getField()] = $e->getValue();
if (!empty($sql_or)) $sql_or .= " OR ";
$sql_or .= $cond;
}
}
$sql .= $sql_or. " ) ";
$sql .= $sql_or . " ) ";
}
}
return $sql;

View File

@ -84,7 +84,7 @@ final class FilterParser
* @param string $value
* @return FilterElement|null
*/
private static function buildFilter($field, $op, $value)
public static function buildFilter($field, $op, $value)
{
switch($op)
{

View File

@ -1,4 +1,4 @@
<?php
<?php namespace utils;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
@ -12,9 +12,8 @@
* limitations under the License.
**/
namespace utils;
use Illuminate\Database\Eloquent\Relations\Relation;
use Doctrine\Common\Collections\Criteria;
use Doctrine\ORM\QueryBuilder;
/**
* Class Order
@ -32,20 +31,47 @@ final class Order
$this->ordering = $ordering;
}
public function apply2Relation(Relation $relation, array $mappings)
/**
* @param QueryBuilder $query
* @param array $mappings
* @return $this
*/
public function apply2Query(QueryBuilder $query, array $mappings)
{
foreach ($this->ordering as $order) {
if ($order instanceof OrderElement) {
if (isset($mappings[$order->getField()])) {
$mapping = $mappings[$order->getField()];
$relation->getQuery()->orderBy($mapping, $order->getDirection());
$orders[$mapping] = $order->getDirection();
$query->addOrderBy($mapping, $order->getDirection());
}
}
}
return $this;
}
/**
* @param Criteria $criteria
* @param array $mappings
* @return $this
*/
public function apply2Criteria(Criteria $criteria, array $mappings)
{
$orders = [];
foreach ($this->ordering as $order) {
if ($order instanceof OrderElement) {
if (isset($mappings[$order->getField()])) {
$mapping = $mappings[$order->getField()];
$orders[$mapping] = $order->getDirection();
}
}
}
if(count($orders) > 0)
$criteria->orderBy($orders);
return $this;
}
/**
* @param array $mappings
* @return string

View File

@ -56,4 +56,12 @@ class PagingInfo
{
return ($this->page - 1) * $this->per_page;
}
/**
* @param int $count
* @return int
*/
public function getLastPage($count){
return intval(ceil($count/$this->per_page));
}
}

View File

@ -12,6 +12,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use models\utils\IEntity;
use ModelSerializers\SerializerRegistry;
use Request;
/**
* Class PagingResponse
* @package utils
*/
final class PagingResponse
{
/**
@ -89,17 +97,31 @@ final class PagingResponse
}
/**
* @param null $expand
* @param array $fields
* @param array $relations
* @param array $params
* @return array
*/
public function toArray()
public function toArray($expand = null, array $fields = array(), array $relations = array(), array $params = array() )
{
$items = [];
foreach($this->items as $i)
{
if($i instanceof IEntity)
{
$i = SerializerRegistry::getInstance()->getSerializer($i)->serialize($expand, $fields, $relations, $params);
}
$items[] = $i;
}
return array
(
'total' => $this->total,
'per_page' => $this->per_page,
'current_page' => $this->page,
'last_page' => $this->last_page,
'data' => $this->items,
'data' => $items,
);
}
}

View File

@ -10,15 +10,17 @@
| and give it the controller to call when that URI is requested.
|
*/
//OAuth2 Protected API
Route::group(array(
'namespace' => 'App\Http\Controllers',
'prefix' => 'api/v1',
'before' => [],
'after' => [],
'middleware' => ['ssl', 'oauth2.protected', 'rate.limit','etags']
), function () {
Route::group(array('prefix' => 'marketplace'), function () {
Route::group(array('prefix' => 'marketplace'), function () {
Route::group(array('prefix' => 'public-clouds'), function () {
Route::get('', 'OAuth2PublicCloudApiController@getClouds');
@ -42,6 +44,7 @@ Route::group(array(
// summits
Route::group(array('prefix' => 'summits'), function () {
Route::get('', 'OAuth2SummitApiController@getSummits');
Route::group(array('prefix' => 'events'), function () {
Route::get('', 'OAuth2SummitApiController@getAllEvents');
@ -49,26 +52,28 @@ Route::group(array(
});
Route::group(array('prefix' => '{id}'), function () {
Route::get('', [ 'middleware' => 'cache', 'uses' => 'OAuth2SummitApiController@getSummit'])->where('id', 'current|[0-9]+');
Route::get('entity-events', 'OAuth2SummitApiController@getSummitEntityEvents');
// attendees
Route::group(array('prefix' => 'attendees'), function () {
//Route::get('', 'OAuth2SummitApiController@getAttendees');
//Route::get('', 'OAuth2SummitAttendeesApiController@getAttendees');
Route::group(array('prefix' => '{attendee_id}'), function () {
Route::get('', 'OAuth2SummitApiController@getAttendee')->where('attendee_id', 'me|[0-9]+');
Route::get('', 'OAuth2SummitAttendeesApiController@getAttendee')->where('attendee_id', 'me|[0-9]+');
Route::group(array('prefix' => 'schedule'), function ()
{
Route::get('', 'OAuth2SummitApiController@getAttendeeSchedule')->where('attendee_id', 'me|[0-9]+');
Route::get('', 'OAuth2SummitAttendeesApiController@getAttendeeSchedule')->where('attendee_id', 'me|[0-9]+');
Route::group(array('prefix' => '{event_id}'), function (){
Route::post('', 'OAuth2SummitApiController@addEventToAttendeeSchedule')->where('attendee_id', 'me|[0-9]+');
Route::delete('', 'OAuth2SummitApiController@removeEventFromAttendeeSchedule')->where('attendee_id', 'me|[0-9]+');
Route::put('/check-in', 'OAuth2SummitApiController@checkingAttendeeOnEvent')->where('attendee_id', 'me|[0-9]+');
Route::post('', 'OAuth2SummitAttendeesApiController@addEventToAttendeeSchedule')->where('attendee_id', 'me|[0-9]+');
Route::delete('', 'OAuth2SummitAttendeesApiController@removeEventFromAttendeeSchedule')->where('attendee_id', 'me|[0-9]+');
Route::put('/check-in', 'OAuth2SummitAttendeesApiController@checkingAttendeeOnEvent')->where('attendee_id', 'me|[0-9]+');
});
});
});
@ -77,41 +82,53 @@ Route::group(array(
// speakers
Route::group(array('prefix' => 'speakers'), function () {
Route::get('', 'OAuth2SummitApiController@getSpeakers');
Route::get('', 'OAuth2SummitSpeakersApiController@getSpeakers');
Route::group(array('prefix' => '{speaker_id}'), function () {
Route::get('', 'OAuth2SummitApiController@getSpeaker')->where('speaker_id', 'me|[0-9]+');
Route::get('', 'OAuth2SummitSpeakersApiController@getSpeaker')->where('speaker_id', 'me|[0-9]+');
});
});
// events
Route::group(array('prefix' => 'events'), function () {
Route::get('', 'OAuth2SummitApiController@getEvents');
Route::get('/published', 'OAuth2SummitApiController@getScheduledEvents');
Route::post('', 'OAuth2SummitApiController@addEvent');
Route::get('', 'OAuth2SummitEventsApiController@getEvents');
Route::get('/published', 'OAuth2SummitEventsApiController@getScheduledEvents');
Route::post('', 'OAuth2SummitEventsApiController@addEvent');
Route::group(array('prefix' => '{event_id}'), function () {
Route::get('', 'OAuth2SummitApiController@getEvent');
Route::get('/published', 'OAuth2SummitApiController@getScheduledEvent');
Route::put('', 'OAuth2SummitApiController@updateEvent');
Route::delete('', 'OAuth2SummitApiController@deleteEvent');
Route::put('/publish', 'OAuth2SummitApiController@publishEvent');
Route::delete('/publish', 'OAuth2SummitApiController@unPublishEvent');
Route::post('/feedback', 'OAuth2SummitApiController@addEventFeedback');
Route::get('/feedback/{attendee_id?}', 'OAuth2SummitApiController@getEventFeedback')->where('attendee_id', 'me|[0-9]+');
Route::get('', 'OAuth2SummitEventsApiController@getEvent');
Route::get('/published', 'OAuth2SummitEventsApiController@getScheduledEvent');
Route::put('', 'OAuth2SummitEventsApiController@updateEvent');
Route::delete('', 'OAuth2SummitEventsApiController@deleteEvent');
Route::put('/publish', 'OAuth2SummitEventsApiController@publishEvent');
Route::delete('/publish', 'OAuth2SummitEventsApiController@unPublishEvent');
Route::post('/feedback', 'OAuth2SummitEventsApiController@addEventFeedback');
Route::get('/feedback/{attendee_id?}', 'OAuth2SummitEventsApiController@getEventFeedback')->where('attendee_id', 'me|[0-9]+');
});
});
// presentations
Route::group(array('prefix' => 'presentations'), function () {
Route::group(array('prefix' => '{presentation_id}'), function () {
Route::group(array('prefix' => 'videos'), function () {
Route::get('', 'OAuth2PresentationApiController@getPresentationVideos');
Route::get('{video_id}', 'OAuth2PresentationApiController@getPresentationVideo');
Route::post('', 'OAuth2PresentationApiController@addVideo');
});
});
});
// locations
Route::group(array('prefix' => 'locations'), function () {
Route::get('', 'OAuth2SummitApiController@getLocations');
Route::get('', 'OAuth2SummitLocationsApiController@getLocations');
Route::group(array('prefix' => '{location_id}'), function () {
Route::get('', 'OAuth2SummitApiController@getLocation');
Route::get('/events/published','OAuth2SummitApiController@getLocationEvents');
Route::get('/events','OAuth2SummitApiController@getLocationPublishedEvents');
Route::get('', 'OAuth2SummitLocationsApiController@getLocation');
Route::get('/events/published','OAuth2SummitLocationsApiController@getLocationEvents');
Route::get('/events','OAuth2SummitLocationsApiController@getLocationPublishedEvents');
});
});
@ -131,6 +148,40 @@ Route::group(array(
Route::post('{external_order_id}/external-attendees/{external_attendee_id}/confirm', 'OAuth2SummitApiController@confirmExternalOrderAttendee');
});
// member
Route::group(array('prefix' => 'members'), function () {
Route::group(array('prefix' => 'me'), function () {
Route::get('', 'OAuth2SummitMembersApiController@getMyMember');
});
});
});
});
});
//OAuth2 Protected API V2
Route::group(array(
'namespace' => 'App\Http\Controllers',
'prefix' => 'api/v2',
'before' => [],
'after' => [],
'middleware' => ['ssl', 'oauth2.protected', 'rate.limit','etags']
), function () {
// summits
Route::group(array('prefix' => 'summits'), function () {
Route::group(array('prefix' => '{id}'), function () {
// events
Route::group(array('prefix' => 'events'), function () {
Route::group(array('prefix' => '{event_id}'), function () {
Route::post('/feedback', 'OAuth2SummitEventsApiController@addEventFeedbackByMember');
});
});
});
});
});

21
app/Jobs/Job.php Normal file
View File

@ -0,0 +1,21 @@
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
abstract class Job
{
/*
|--------------------------------------------------------------------------
| Queueable Jobs
|--------------------------------------------------------------------------
|
| This job base class provides a central location to place any logic that
| is shared across all of your jobs. The trait included with the class
| provides access to the "onQueue" and "delay" queue helper methods.
|
*/
use Queueable;
}

View File

@ -1,9 +1,6 @@
<?php namespace models\main;
use models\utils\SilverstripeBaseModel;
<?php namespace ModelSerializers;
/**
* Copyright 2015 OpenStack Foundation
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -14,14 +11,16 @@ use models\utils\SilverstripeBaseModel;
* See the License for the specific language governing permissions and
* limitations under the License.
**/
class Company extends SilverstripeBaseModel
{
protected $table = 'Company';
protected $array_mappings = array
/**
* Class CompanySerializer
* @package ModelSerializers
*/
final class CompanySerializer extends SilverStripeSerializer
{
protected static $array_mappings = array
(
'ID' => 'id:json_int',
'Name' => 'name:json_string',
);
}

View File

@ -1,6 +1,6 @@
<?php
<?php namespace ModelSerializers\Locations;
/**
* Copyright 2015 OpenStack Foundation
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -11,24 +11,20 @@
* See the License for the specific language governing permissions and
* limitations under the License.
**/
namespace models\summit;
use ModelSerializers\SilverStripeSerializer;
/**
* Class SummitVenueRoom
* @package models\summit
* Class SummitAbstractLocationSerializer
* @package ModelSerializers\Locations
*/
class SummitVenueRoom extends SummitAbstractLocation
class SummitAbstractLocationSerializer extends SilverStripeSerializer
{
protected $mtiClassType = 'concrete';
protected $array_mappings = array
protected static $array_mappings = array
(
'ID' => 'id:json_int',
'VenueID' => 'venue_id:json_int',
'ClassName' => 'class_name',
'Name' => 'name:json_string',
'Description' => 'description:json_string',
'Capacity' => 'Capacity:json_int',
);
'LocationType' => 'location_type',
'Order' => 'order:json_int',
'ClassName' => 'class_name:json_string',
);
}

View File

@ -0,0 +1,24 @@
<?php namespace ModelSerializers\Locations;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class SummitAirportSerializer
* @package ModelSerializers\Locations
*/
final class SummitAirportSerializer extends SummitExternalLocationSerializer
{
protected static $array_mappings = array
(
'AirportType' => 'airport_type:json_string',
);
}

View File

@ -0,0 +1,25 @@
<?php namespace ModelSerializers\Locations;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class SummitExternalLocationSerializer
* @package ModelSerializers\Locations
*/
class SummitExternalLocationSerializer extends SummitGeoLocatedLocationSerializer
{
protected static $array_mappings = array
(
'Capacity' => 'capacity:json_int',
);
}

View File

@ -0,0 +1,62 @@
<?php namespace ModelSerializers\Locations;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use ModelSerializers\SerializerRegistry;
/**
* Class SummitGeoLocatedLocationSerializer
* @package ModelSerializers\Locations
*/
class SummitGeoLocatedLocationSerializer extends SummitAbstractLocationSerializer
{
protected static $array_mappings = array
(
'Address1' => 'address_1:json_string',
'Address2' => 'address_2:json_string',
'ZipCode' => 'zip_code',
'City' => 'city:json_string',
'State' => 'state:json_string',
'Country' => 'country:json_string',
'Lng' => 'lng',
'Lat' => 'lat',
);
/**
* @param null $expand
* @param array $fields
* @param array $relations
* @param array $params
* @return array
*/
public function serialize($expand = null, array $fields = array(), array $relations = array(), array $params = array() )
{
$values = parent::serialize($expand, $fields, $relations);
$location = $this->object;
$maps = array();
foreach($location->getMaps() as $m)
{
$maps[] = SerializerRegistry::getInstance()->getSerializer($m)->serialize();
}
$values['maps'] = $maps;
$images = array();
foreach($location->getImages() as $i)
{
$images[] = SerializerRegistry::getInstance()->getSerializer($i)->serialize();
}
$values['images'] = $images;
return $values;
}
}

View File

@ -0,0 +1,28 @@
<?php namespace ModelSerializers\Locations;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class SummitHotelSerializer
* @package ModelSerializers\Locations
*/
final class SummitHotelSerializer extends SummitExternalLocationSerializer
{
protected static $array_mappings = array
(
'BookingLink' => 'booking_link:json_string',
'HotelType' => 'hotel_type:json_string',
'SoldOut' => 'sold_out:json_boolean',
);
}

View File

@ -1,6 +1,6 @@
<?php
<?php namespace ModelSerializers\Locations;
/**
* Copyright 2015 OpenStack Foundation
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -11,29 +11,17 @@
* See the License for the specific language governing permissions and
* limitations under the License.
**/
namespace models\summit;
use models\main\Image;
use models\utils\SilverstripeBaseModel;
use Config;
use Illuminate\Support\Facades\Config;
use ModelSerializers\SilverStripeSerializer;
/**
* Class SummitLocationMap
* @package models\summit
* Class SummitLocationImageSerializer
* @package ModelSerializers\Locations
*/
class SummitLocationMap extends SummitLocationImage
class SummitLocationImageSerializer extends SilverStripeSerializer
{
protected $stiBaseClass = 'models\summit\SummitLocationMap';
protected $table = 'SummitLocationImage';
protected $mtiClassType = 'concrete';
protected $array_mappings = array
protected static $array_mappings = array
(
'ID' => 'id:json_int',
'LocationID' => 'location_id:json_int',
'Name' => 'name:json_text',
'Description' => 'description:json_text',
'ClassName' => 'class_name:json_text',
@ -41,20 +29,20 @@ class SummitLocationMap extends SummitLocationImage
);
/**
* @return Image
* @param null $expand
* @param array $fields
* @param array $relations
* @param array $params
* @return array
*/
public function map()
public function serialize($expand = null, array $fields = array(), array $relations = array(), array $params = array() )
{
return $this->hasOne('models\main\Image', 'ID', 'PictureID')->first();
}
$values = parent::serialize($expand, $fields, $relations, $params);
public function toArray()
{
$values = parent::toArray();
$map = $this->map();
if(!is_null($map))
if($this->object->hasPicture())
{
$values['image_url'] = Config::get("server.assets_base_url", 'https://www.openstack.org/'). $map->Filename;
$picture = $this->object->getPicture();
$values['image_url'] = Config::get("server.assets_base_url", 'https://www.openstack.org/'). $picture->getFilename();
}
return $values;
}

View File

@ -0,0 +1,64 @@
<?php namespace ModelSerializers\Locations;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use ModelSerializers\SerializerRegistry;
use ModelSerializers\SilverStripeSerializer;
use Illuminate\Support\Facades\Config;
/**
* Class SummitVenueFloorSerializer
* @package ModelSerializers\Locations
*/
final class SummitVenueFloorSerializer extends SilverStripeSerializer
{
protected static $array_mappings = array
(
'Name' => 'name:json_string',
'Description' => 'description:json_string',
'Number' => 'number:json_int',
'VenueId' => 'venue_id:json_int',
);
/**
* @param null $expand
* @param array $fields
* @param array $relations
* @param array $params
* @return array
*/
public function serialize($expand = null, array $fields = array(), array $relations = array(), array $params = array() )
{
$values = parent::serialize($expand, $fields, $relations, $params);
$floor = $this->object;
// floor image
$values['image'] = ($floor->getImage() !== null) ?
Config::get("server.assets_base_url", 'https://www.openstack.org/').$floor->getImage()->getFilename()
: null;
// rooms
$rooms = array();
foreach($floor->getRooms() as $room)
{
$rooms[] = strstr('rooms',$expand) === false ? intval($room->getId()) :
SerializerRegistry::getInstance()->getSerializer($room)->serialize($expand, $fields, $relations, $params);
}
if(count($rooms) > 0)
$values['rooms'] = $rooms;
return $values;
}
}

View File

@ -0,0 +1,58 @@
<?php namespace ModelSerializers\Locations;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use ModelSerializers\SerializerRegistry;
/**
* Class SummitVenueRoomSerializer
* @package ModelSerializers\Locations
*/
final class SummitVenueRoomSerializer extends SummitAbstractLocationSerializer
{
protected static $array_mappings = array
(
'VenueId' => 'venue_id:json_int',
'FloorId' => 'floor_id:json_int',
'Capacity' => 'capacity:json_int',
);
public function serialize($expand = null, array $fields = array(), array $relations = array(), array $params = array() )
{
$room = $this->object;
$values = parent::serialize($expand, $fields, $relations, $params);
if (!empty($expand)) {
$exp_expand = explode(',', $expand);
foreach ($exp_expand as $relation) {
switch (trim($relation)) {
case 'floor': {
if($room->hasFloor()) {
unset($values['floor_id']);
$values['floor'] = SerializerRegistry::getInstance()->getSerializer($room->getFloor())->serialize();
}
}
break;
case 'venue': {
if($room->hasVenue()) {
unset($values['venue_id']);
$values['venue'] = SerializerRegistry::getInstance()->getSerializer($room->getVenue())->serialize();
}
}
break;
}
}
}
return $values;
}
}

View File

@ -0,0 +1,60 @@
<?php namespace ModelSerializers\Locations;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use ModelSerializers\SerializerRegistry;
/**
* Class SummitVenueSerializer
* @package ModelSerializers\Locations
*/
final class SummitVenueSerializer extends SummitGeoLocatedLocationSerializer
{
protected static $array_mappings = array
(
'IsMain' => 'is_main::json_boolean',
);
/**
* @param null $expand
* @param array $fields
* @param array $relations
* @param array $params
* @return array
*/
public function serialize($expand = null, array $fields = array(), array $relations = array(), array $params = array() )
{
$values = parent::serialize($expand, $fields, $relations, $params);
$venue = $this->object;
// rooms
$rooms = array();
foreach($venue->getRooms() as $room)
{
$rooms[] = SerializerRegistry::getInstance()->getSerializer($room)->serialize($expand, $fields, $relations, $params);
}
if(count($rooms) > 0)
$values['rooms'] = $rooms;
// floors
$floors = array();
foreach($venue->getFloors() as $floor)
{
$floors[] = SerializerRegistry::getInstance()->getSerializer($floor)->serialize($expand, $fields, $relations, $params);
}
if(count($floors) > 0)
$values['floors'] = $floors;
return $values;
}
}

View File

@ -0,0 +1,92 @@
<?php namespace ModelSerializers;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Support\Facades\Config;
/**
* Class MemberSerializer
* @package ModelSerializers
*/
final class MemberSerializer extends SilverStripeSerializer
{
protected static $array_mappings = array
(
'FirstName' => 'first_name:json_string',
'LastName' => 'last_name:json_string',
'Gender' => 'gender:json_string',
'Bio' => 'bio:json_string',
'LinkedInProfile' => 'linked_in:json_string',
'IrcHandle' => 'irc:json_string',
'TwitterHandle' => 'twitter:json_string',
);
/**
* @param null $expand
* @param array $fields
* @param array $relations
* @param array $params
* @return array
*/
public function serialize($expand = null, array $fields = array(), array $relations = array(), array $params = array())
{
$member = $this->object;
$values = parent::serialize($expand, $fields, $relations, $params);
$values['pic'] = Config::get("server.assets_base_url", 'https://www.openstack.org/'). 'profile_images/members/'. $member->getId();
$summit = isset($params['summit'])? $params['summit'] :null;
$speaker = !is_null($summit)? $summit->getSpeakerByMember($member): null;
$attendee = !is_null($summit)? $summit->getAttendeeByMember($member): null;
if(!is_null($speaker))
$values['speaker_id'] = $speaker->getId();
if(!is_null($attendee))
$values['attendee_id'] = $attendee->getId();
if (!empty($expand)) {
$exp_expand = explode(',', $expand);
foreach ($exp_expand as $relation) {
switch (trim($relation)) {
case 'attendee': {
if (!is_null($attendee))
{
unset($values['attendee_id']);
$values['attendee'] = SerializerRegistry::getInstance()->getSerializer($attendee)->serialize(null,[],['none']);
}
}
break;
case 'speaker': {
if (!is_null($speaker))
{
unset($values['speaker_id']);
$values['speaker'] = SerializerRegistry::getInstance()->getSerializer($speaker)->serialize(null,[],['none']);
}
}
break;
case 'feedback': {
$feedback = array();
foreach ($member->getFeedbackBySummit($summit) as $f) {
array_push($feedback, SerializerRegistry::getInstance()->getSerializer($f)->serialize());
}
$values['feedback'] = $feedback;
}
break;
}
}
}
return $values;
}
}

View File

@ -1,6 +1,6 @@
<?php
<?php namespace ModelSerializers;
/**
* Copyright 2015 OpenStack Foundation
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -12,43 +12,31 @@
* limitations under the License.
**/
namespace models\summit;
use models\utils\SilverstripeBaseModel;
/**
* Class PresentationCategoryGroup
* @package models\summit
* Class PresentationCategoryGroupSerializer
* @package ModelSerializers
*/
class PresentationCategoryGroup extends SilverstripeBaseModel
final class PresentationCategoryGroupSerializer extends SilverStripeSerializer
{
protected $table = 'PresentationCategoryGroup';
protected $array_mappings = array
protected static $array_mappings = array
(
'ID' => 'id:json_int',
'Name' => 'name:json_string',
'Color' => 'color:json_string',
'Description' => 'description:json_string',
);
/**
* @return PresentationCategory[]
*/
public function categories()
{
return $this->belongsToMany('models\summit\PresentationCategory','PresentationCategoryGroup_Categories','PresentationCategoryGroupID','PresentationCategoryID')->get();
}
/**
* @param null $expand
* @param array $fields
* @param array $relations
* @param array $params
* @return array
*/
public function toArray()
public function serialize($expand = null, array $fields = array(), array $relations = array(), array $params = array() )
{
$values = parent::toArray();
$values = parent::serialize($expand, $fields, $relations, $params);
$group = $this->object;
$color = isset($values['color']) ? $values['color']:'';
if(empty($color))
$color = 'f0f0ee';
@ -56,11 +44,18 @@ class PresentationCategoryGroup extends SilverstripeBaseModel
$color = '#'.$color;
}
$values['color'] = $color;
$categories = array();
foreach($this->categories() as $c)
$categories = array();
foreach($group->getCategories() as $c)
{
array_push($categories, intval($c->ID));
if(!is_null($expand) && in_array('tracks', explode(',',$expand))){
$categories[] = SerializerRegistry::getInstance()->getSerializer($c)->serialize();
}
else
$categories[] = intval($c->getId());
}
$values['tracks'] = $categories;
return $values;
}

View File

@ -0,0 +1,47 @@
<?php namespace ModelSerializers;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class PresentationCategorySerializer
* @package ModelSerializers
*/
final class PresentationCategorySerializer extends SilverStripeSerializer
{
protected static $array_mappings = array
(
'Title' => 'name:json_string',
'Description' => 'description:json_string',
'Code' => 'code:json_string',
);
/**
* @param null $expand
* @param array $fields
* @param array $relations
* @param array $params
* @return array
*/
public function serialize($expand = null, array $fields = array(), array $relations = array(), array $params = array() )
{
$category = $this->object;
$values = parent::serialize($expand, $fields, $relations, $params);
$groups = array();
foreach($category->getGroups() as $group){
$groups[] = intval($group->getId());
}
$values['track_groups'] = $groups;
return $values;
}
}

View File

@ -0,0 +1,26 @@
<?php namespace ModelSerializers;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class PresentationLinkSerializer
* @package ModelSerializers
*/
final class PresentationLinkSerializer extends PresentationMaterialSerializer
{
protected static $array_mappings = array
(
'Link' => 'link:json_text',
);
}

View File

@ -1,6 +1,6 @@
<?php
<?php namespace ModelSerializers;
/**
* Copyright 2015 OpenStack Foundation
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -12,27 +12,21 @@
* limitations under the License.
**/
namespace models\summit;
/**
* Class PresentationVideo
* @package models\summit
* Class PresentationMaterialSerializer
* @package ModelSerializers
*/
class PresentationVideo extends PresentationMaterial
class PresentationMaterialSerializer extends SilverStripeSerializer
{
protected $table = 'PresentationVideo';
protected $mtiClassType = 'concrete';
protected $array_mappings = array
protected static $array_mappings = array
(
'ID' => 'id:json_int',
'Name' => 'name:json_text',
'Description' => 'description:json_text',
'DisplayOnSite' => 'display_on_site:json_boolean',
'Featured' => 'featured:json_boolean',
'PresentationID' => 'presentation_id:json_int',
'YouTubeID' => 'youtube_id:json_text',
'Order' => 'order:json_int',
'PresentationId' => 'presentation_id:json_int',
);
}

View File

@ -0,0 +1,114 @@
<?php namespace ModelSerializers;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class PresentationSerializer
* @package ModelSerializers
*/
class PresentationSerializer extends SummitEventSerializer
{
protected static $array_mappings = array
(
'Level' => 'level',
'CategoryId' => 'track_id:json_int',
'ModeratorId' => 'moderator_speaker_id:json_int',
'ProblemAddressed' => 'problem_addressed:json_string',
'AttendeesExpectedLearnt' => 'attendees_expected_learnt:json_string',
);
protected static $allowed_fields = array
(
'track_id',
'moderator_speaker_id',
'level',
'problem_addressed',
'attendees_expected_learnt',
);
protected static $allowed_relations = array
(
'slides',
'videos',
'speakers',
'links',
);
/**
* @param null $expand
* @param array $fields
* @param array $relations
* @param array $params
* @return array
*/
public function serialize($expand = null, array $fields = array(), array $relations = array(), array $params = array() )
{
if(!count($relations)) $relations = $this->getAllowedRelations();
$values = parent::serialize($expand, $fields, $relations, $params);
$presentation = $this->object;
if(in_array('speakers', $relations)) {
$values['speakers'] = $presentation->getSpeakerIds();
}
if(in_array('slides', $relations))
{
$slides = array();
foreach ($presentation->getSlides() as $slide) {
$slide_values = SerializerRegistry::getInstance()->getSerializer($slide)->serialize();
if(empty($slide_values['link'])) continue;
$slides[] = $slide_values;
}
$values['slides'] = $slides;
}
if(in_array('links', $relations))
{
$links = array();
foreach ($presentation->getLinks() as $link) {
$link_values = SerializerRegistry::getInstance()->getSerializer($link)->serialize();
if(empty($link_values['link'])) continue;
$links[] = $link_values;
}
$values['links'] = $links;
}
if(in_array('videos', $relations))
{
$videos = array();
foreach ($presentation->getVideos() as $video) {
$video_values = SerializerRegistry::getInstance()->getSerializer($video)->serialize();
if(empty($video_values['youtube_id'])) continue;
$videos[] = $video_values;
}
$values['videos'] = $videos;
}
if (!empty($expand)) {
foreach (explode(',', $expand) as $relation) {
switch (trim($relation)) {
case 'speakers': {
$speakers = array();
foreach ($presentation->getSpeakers() as $s) {
$speakers[] = SerializerRegistry::getInstance()->getSerializer($s)->serialize();
}
$values['speakers'] = $speakers;
}
break;
}
}
}
return $values;
}
}

Some files were not shown because too many files have changed in this diff Show More