zend framework rest controller question - php

I have a rest controller example im trying to run that is giving me a headache.
My url im trying to access is localhost/books/edit/1
For some weird reason this route seems to call the getAction with the Controller instead of the editAction. And it throws errors saying that the object doesnt exist.
The controller is,
class BooksController extends Zend_Rest_Controller {
private $_booksTable;
private $_form;
public function init() {
$bootstrap = $this->getInvokeArg ( 'bootstrap' );
$db = $bootstrap->getResource ( 'db' );
$options = $bootstrap->getOption ( 'resources' );
$dbFile = $options ['db'] ['params'] ['dbname'];
if (! file_exists ( $dbFile )) {
$createTable = "CREATE TABLE IF NOT EXISTS books (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
name VARCHAR(32) NOT NULL,
price DECIMAL(5,2) NOT NULL
)";
$db->query ( $createTable );
$insert1 = "INSERT INTO books (name, price) VALUES ('jQuery in Action', 39.99)";
$insert2 = "INSERT INTO books (name, price) VALUES ('PHP in Action', 45.99)";
$db->query ( $insert1 );
$db->query ( $insert2 );
}
$this->_booksTable = new Zend_Db_Table ( 'books' );
$this->_form = new Default_Form_Book ();
}
/**
* The index action handles index/list requests; it should respond with a
* list of the requested resources.
*/
public function indexAction() {
$this->view->books = $this->_booksTable->fetchAll ();
}
/**
* The list action is the default for the rest controller
* Forward to index
*/
public function listAction() {
$this->_forward ( 'index' );
}
/**
* The get action handles GET requests and receives an 'id' parameter; it
* should respond with the server resource state of the resource identified
* by the 'id' value.
*/
public function getAction() {
$this->view->book = $this->_booksTable->find ( $this->_getParam ( 'id' ) )->current ();
}
/**
* Show the new book form
*/
public function newAction() {
$this->view->form = $this->_form;
}
/**
* The post action handles POST requests; it should accept and digest a
* POSTed resource representation and persist the resource state.
*/
public function postAction() {
if ($this->_form->isValid ( $this->_request->getParams () )) {
$this->_booksTable->createRow ( $this->_form->getValues () )->save ();
$this->_redirect ( 'books' );
} else {
$this->view->form = $this->_form;
$this->render ( 'new' );
}
}
/**
* Show the edit book form. Url format: /books/edit/2
*/
public function editAction() {
var_dump ($this->getRequest()->getParam ( 'edit' ));
$book = $this->_booksTable->find ( $this->getRequest()->getParam ( 'id' ) )->current ();
var_dump ($book->toArray ());
$this->_form->populate ( $book->toArray () );
$this->view->form = $this->_form;
$this->view->book = $book;
}
/**
* The put action handles PUT requests and receives an 'id' parameter; it
* should update the server resource state of the resource identified by
* the 'id' value.
*/
public function putAction() {
$book = $this->_booksTable->find ( $this->_getParam ( 'id' ) )->current ();
if ($this->_form->isValid ( $this->_request->getParams () )) {
$book->setFromArray ( $this->_form->getValues () )->save ();
$this->_redirect ( 'books' );
} else {
$this->view->book = $book;
$this->view->form = $this->_form;
$this->render ( 'edit' );
}
}
/**
* The delete action handles DELETE requests and receives an 'id'
* parameter; it should update the server resource state of the resource
* identified by the 'id' value.
*/
public function deleteAction() {
$book = $this->_booksTable->find ( $this->_getParam ( 'id' ) )->current ();
$book->delete ();
$this->_redirect ( 'books' );
}
}
The bootstrap is,
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap {
protected function _initAutoload() {
$autoloader = new Zend_Application_Module_Autoloader ( array (
'namespace' => 'Default_',
'basePath' => dirname ( __FILE__ )
) );
return $autoloader;
}
protected function _initRestRoute() {
$this->bootstrap ( 'Request' );
$front = $this->getResource ( 'FrontController' );
$restRoute = new Zend_Rest_Route ( $front, array (), array (
'default' => array ('books' )
) );
$front->getRouter ()->addRoute ( 'rest', $restRoute );
}
protected function _initRequest() {
$this->bootstrap ( 'FrontController' );
$front = $this->getResource ( 'FrontController' );
$request = $front->getRequest ();
if (null === $front->getRequest ()) {
$request = new Zend_Controller_Request_Http ();
$front->setRequest ( $request );
}
return $request;
}
}
Can anyone see what might be causing the getAction to be called when browsing to that link ???

edit should follow the identifier, so the correct edit URL is http://localhost/books/1/edit

Related

Wordpress - Testing custom API endpoint with class dependency

Sorry I feel like really stuck here.
I have a plugin introducing a new Rest API controller (WP_REST_Controller) with basically a single endpoint which uses a separate class as a client to fetch some data. Let's say:
#my_plugin.php
function register_items_routes() {
if ( ! class_exists( 'WP_REST_My_Controller' ) ) {
require_once __DIR__ . '/class-wp-my-controller.php';
}
$controller = new WP_REST_My_Controller();
$controller->register_routes();
}
add_action( 'rest_api_init', 'register_items_routes' );
_
#class-wp-my-controller.php
class WP_REST_My_Controller extends WP_REST_Controller {
/**
* Registers the routes.
*/
public function register_routes() {
$namespace = 'my/namespace';
$path = 'get-items';
register_rest_route( $namespace, '/' . $path, [
array(
'methods' => 'GET',
'callback' => array( $this, 'get_items' ),
'permission_callback' => array( $this, 'get_items_permissions_check' )
),
] );
}
public function get_items_permissions_check( $request ) {
return true;
}
/**
* Get items from My_Class and return them.
*
* #param WP_REST_Request $request The incoming HTTP request.
*
* #return WP_REST_Response|WP_Error The response containing the items in JSON, WP_Error in case of error.
*/
public function get_items( $request ) {
$client = new My_Class();
try {
$items = $client->fetch_some_items();
} catch ( Exception $e ) {
return new WP_Error(
'some-client-error',
$e->getMessage()
);
// Code to be tested. - Do some stuff with items and return.
return new WP_REST_Response( $items );
}
How am I supposed to stub the My_Class dependency from PhpUnit in order to return a predefined set of items which I could test with?
public function test_get_items() {
$request = new WP_REST_Request( 'GET', '/my/namespace/get-items' );
$data = rest_get_server()->dispatch( $request );
$expected_items = [
'some_key1' => 'some_value1',
'some_key2' => 'some_value2',
];
$this->assertTrue( count($data['items']) == count($expected_items) );
}

How to exclude private events in laravel 5.5?

I have this piece of legacy code to return all events to the front end:
/**
* #param $request
*
* #return mixed
*/
public function index( EventsFilterRequest $request ) {
$keys = $request->all();
if ( \count( $keys ) === 0 ) {
return $this->eventsQueryBuilder()->isVisibleFor( authUser()->id )->ofOrder( 'starts_at', 'ASC' )->ofCountry( runtime()->country()->id )->ofStatus( 'future' );
}
$events = $this->eventsQueryBuilder()->isVisibleFor( authUser()->id )->ofOrder( 'starts_at', 'ASC' )->ofStatus( 'future' )->ofCountry( runtime()->country()->id );
foreach ( $keys as $key => $value ) {
if ( array_key_exists( $key, $this->_methods ) ) {
$events = $this->_methods[$key]( $events, $request, $this );
}
}
return $events;
}
In the events table there's a column called privacy that contains public or private. How can I exclude private events from being returned ?
I am new to laravel but you can use where clause in your query. Something like
$events = DB::table('events')->where('privacy', 'public')->get();
For more check this link LARAVEL QUERY

Middleware causing getArguments() to be null

Here is the middleware flow:
# Post edit
$this->get( '/edit/{id}/{slug}', \Rib\Src\Apps\Post\PostControllers\EditController::class . ':index' )
->add( new EnforceEditDelay() )
->add( new RequireOwner( 'posts' ) )
->add( new RejectBanned() )
->add( new RequireAuth() );
The ->add( new RejectBanned() ) cause the next middleware in the chain to break with:
'Call to a member function getArguments() on null'
RequireAuth():
class RequireAuth
{
# Variable used to disable redirect to '/user/set-username' from itelf. That would cause infinite redirection loop.
# This is passed to the middleWare from the list of routes. Of course only true for '/user/set-username' pages.
private $disableUserNameValidationCheck;
function __construct( $disableUserNameValidationCheck = false )
{
$this->disableUserNameValidationCheck = $disableUserNameValidationCheck;
}
public function __invoke( Request $request, Response $response, $next )
{
$session = $_SESSION;
# User is not authenticated: we ensure this by checking his id which is necessarily set when he is logged in.
if ( ! isset( $session[ 'id' ] ) ) {
FlashMessages::flashIt( 'message', "The page you tried to access requires that you are logged in the site." );
return $response->withRedirect( '/user/login' );
}
# In case user has logged in from a social network and has not set a user name and password. Username is 'temporary-.....'
# We really want the user to set his username. So on designated page we force redirect to page to setup username and email.
if ( ! $this->disableUserNameValidationCheck and isset( $session[ 'username' ] ) and strpos( $session[ 'username' ], 'temporary' ) !== false ) {
FlashMessages::flashIt( 'message',
"This part of the site requires that you complete your profile with a definitive username and email. Thank you for your understanding." );
return $response->withRedirect( '/user/set-username' );
}
$request = $request->withAttribute( 'session', $session );
# Process regular flow if not interrupted by the middleWare.
return $next( $request, $response );
}
}
RejectBanned():
class RejectBanned
{
/**
* Reject banned user
* #param Request $request
* #param Response $response
* #param $next
* #return Response
*/
public function __invoke( Request $request, Response $response, $next )
{
$session = $request->getAttribute( 'session' ) ?? null;
# Get usergroup from db
$user = ( new DbSql() )->db()->table( 'users' )->find( $session['id'] );
$userGroup = $user->user_group;
# Store it in session
$session['user_group'] = $userGroup;
# Redirect user if usergroup = banned
if ( $userGroup === 'banned' ) {
FlashMessages::flashIt( 'message', 'You are not allowed anymore to access this resource.' );
return $response->withRedirect( '/message' );
}
# Store info for the next middleware or controller
$request = $request->withAttributes( [ 'session' => $session ] );
# User is not banned, pursue
return $next( $request, $response );
}
}
RequireOwner() (this is where it breaks, I added a comment where it breaks):
class RequireOwner
{
private $table;
function __construct( $tableName )
{
$this->table = $tableName;
}
public function __invoke( Request $request, Response $response, $next )
{
$session = $request->getAttribute( 'session' ) ?? null;
// BREAKS HERE:
$recordId = $request->getAttribute( 'route' )->getArguments()[ 'id' ] ?? null; // BREAKS HERE
$currentUserGroup = $session[ 'user_group' ] ?? null;
$currentUserId = $session[ 'id' ] ?? null;
$recordInstance = ( new DbSql() )->db()->table( $this->table )->find( $recordId );
# If any info is missing, interrupt
if ( ! $recordInstance or ! $session or ! $recordId or ! $currentUserGroup or ! $currentUserId ) {
throw new Exception( 'Missing information to determine the owner of record' );
}
# Store info for the next middleware or controller
$request = $request->withAttributes( [ 'session' => $session, 'recordInstance' => $recordInstance ] );
# User is an Admin, he can edit any post
if ( $currentUserGroup === 'admin' ) {
return $next( $request, $response );
}
# User is not owner of post
if ( $currentUserId != $recordInstance->author_id ) {
FlashMessages::flashIt( 'message', 'You must be the author of this content to be able to edit it.' );
return $response->withRedirect( '/message' );
}
# User is not admin but is owner of content
return $next( $request, $response );
}
}
So why does the ->add( new RejectBanned() )causes the null value in the next middleware ?
In RejectBanned():
Changed
$request = $request->withAttributes( [ 'session' => $session ] );
to
$request = $request->withAttribute( 'session', $session );
And it fixed the issue.

wp-async-task don't fire run_action method

I have to work with the techcrunch wp-async-task to run a synchronization task in background in my wordpress plugin.
So to test, at the bottom of the main file I have :
//top of the php file
require_once(dirname(__FILE__) . '/lib/WP_Async_Task.php');
require_once(dirname(__FILE__) . '/class/my_api_status.class.php');
define('API_URL', '...');
/* ... */
// At the bottom of the file
function my_api_status($api_url)
{
sleep(5);
$r = wp_safe_remote_get($api_url);
if (!is_wp_error($r)) {
$body = json_decode(wp_remote_retrieve_body($r));
if (isset($body->success)) {
return;
}
}
}
add_action('wp_async_api_status', 'my_api_status');
function my_init_api_status()
{
new ApiStatusTask();
do_action('api_status', constant('API_URL'));
}
add_action('plugins_loaded', 'my_init_api_status');
And api status task class
class ApiStatusTask extends WP_Async_Task {
protected $action = 'api_status';
/**
* Prepare data for the asynchronous request
* #throws Exception If for any reason the request should not happen
* #param array $data An array of data sent to the hook
* #return array
*/
protected function prepare_data( $data ) {
return array(
'api_url' => $data[0]
);
}
/**
* Run the async task action
*/
protected function run_action() {
if(isset($_POST['api_url'])){
do_action("wp_async_$this->action", $_POST['api_url']);
}
}
}
The function prepare_data is correctly called by launchand after that launch_on_shutdown is also correctly called and finally wp_remote_post is called at the end of launch_on_shutdown with admin-post.php.
But the function run_action is never called ... and so the my_api_status in the main file.
What it possibly go wrong ?
I will put a complete example of a plugin here soon. But for now, I found my problem :
// In the `launch_on_shutdown` method of `WP_Async_Task` class
public function launch_on_shutdown() {
GcLogger::getLogger()->debug('WP_Async_Task::launch_on_shutdown');
if ( ! empty( $this->_body_data ) ) {
$cookies = array();
foreach ( $_COOKIE as $name => $value ) {
$cookies[] = "$name=" . urlencode( is_array( $value ) ? serialize( $value ) : $value );
}
$request_args = array(
'timeout' => 0.01,
'blocking' => false,
'sslverify' => false, //apply_filters( 'https_local_ssl_verify', true ),
'body' => $this->_body_data,
'headers' => array(
'cookie' => implode( '; ', $cookies ),
),
);
$url = admin_url( 'admin-post.php' );
GcLogger::getLogger()->debug('WP_Async_Task::launch_on_shutdown wp_remote_post');
wp_remote_post( $url, $request_args );
}
}
The sslverify option failed in my local environment. I just had to put it on false if we are not in production.
With this option set, the run_action is correctly trigger.

CodeIgniter redirect loop in post controller hook

Here is my Controller:
<?php
class Check_Login {
var $CI;
var $class;
var $allowed_klasses = array('user', 'testing', 'home', 'lesson_assets', 's3_handler', 'ajax', 'api', 'pages', 'invite', 'mail', 'partner', 'renew', 'store', 'news', 'breathe','popup','subscription', 'lessons');
public function __construct() {
$this->CI =& get_instance();
if(!isset($this->CI->session)) {
$this->CI->load->library('session');
}
if(!nash_logged_in()) {
$this->CI->session->sess_destroy();
redirect('/');
}
$this->_set_accessed_klass();
}
public function auth_check() {
if($this->CI->session->userdata('id')) {
$query = $CI->db->query("SELECT authentication_token FROM users WHERE id = ".$this->CI->session->userdata('id')." AND authentication_token IS NOT NULL");
if(!in_array($this->class, $this->allowed_klasses)) {
if($query->num_rows() == 0){
redirect('/user/logout');
}
}else{
return;
}
}else{
return;
}
}
private function _set_accessed_klass() {
$this->class = $this->CI->router->fetch_class();
}
}
The lines that I am referring too are:
if(!nash_logged_in()) {
$this->CI->session->sess_destroy();
redirect('/');
}
Essentially, the app uses the nash_logged_in() method to check against our OAuth system to see if the user is truly "logged in". When this happens a redirect loop happens.
The nash_logged_in method simply returns a JSON key of either TRUE or FALSE. Any reason why I would be running into this redirect loop?
nash_logged_in method:
if(!function_exists('nash_logged_in')) {
function nash_logged_in(){
$url = NASH_OAUTH_URL . '/api/v1/loggedin.json';
$json = file_get_contents($url);
$data = json_decode($json);
return $data->loggedin;
}
}
If nash_logged_in() does not return a boolean false or integer 0 or null, then the statement is evaluated as true therefore your redirect.
Post nash_logged_in() here to see what's going on there.
You wont need to use hooks for this method
post controller hook
You could just extend CI_Controller and run the Authentication library in the __constructor of the child classes that need to be authenticated.
You current controller is a little messy and it looks like a library to me, not a controller, you don't need to re-instantiate the super object if your doing it all in your controller!
However, my suggestion is to move everything to a library(as there are a number of controllers/classes that depend on it).
Some elements of your code don't make sense to me, possibly because I can't see the bigger picture from the code you have posted.
This might give you some food for though(or not) regardless this is how I would approach it.
application/libraries/authentication.php
class Authentication
{
protected $allowedClasses = array ( ) ;
protected $userId = null ;
protected $nashURL ;
const NASH_OAUTH_URL = '' ;
public function __construct ()
{
$this->nashURL = static::NASH_OAUTH_URL . '/api/v1/loggedin.json' ;
//check for a user id in session
//this may not be set yet!!
$this->userId = (isset ( $this->session->userdata ( 'id' ) ))
? $this->session->userdata ( 'id' )
: null ;
/** Load dependancies * */
$this->load->model ( 'Authentication_Model' ) ;
$this->load->library ( 'Session' ) ;
}
/**
* nashCheckLoginViaCurl
* #return boolean
*/
protected function nashCheckLoginViaCurl ()
{
if ( function_exists ( 'curl_init' ) )
{
return show_error ( "Enabled CURL please!" , 500 ) ;
}
$curl = curl_init () ;
curl_setopt_array ( $curl ,
array (
CURLOPT_URL => $this->nashURL ,
/** CHECK CURL DOCS FOR FULL LIST OF OPTIONS - FILL THE REST YOURSELF * */
) ) ;
if ( curl_errno ( $curl ) )
{
return false ;
}
$info = curl_getinfo ( $curl ) ;
$responce = curl_exec ( $curl ) ;
curl_close ( $curl ) ;
//Check and make sure responce is a BOOLEAN and not a STRING
//we will typecast below just incase
$responce = json_decode ( $responce ) ;
return ($info[ 'http_code' ] == '200' and ( bool ) $responce->loggedin === true)
? true
: false ;
}
/**
* verifyAccess
* #param CI_Controller $class (Dependancy Injection)
* #return Mixed
*
*/
public function verifyAccess ( CI_Controller $class )
{
//Is there a userId in the session
//ie: is user logged In
if ( is_null ( $this->userId ) or ! ( int ) $this->userId )
{
return false ;
}
//grab list of allowed classes
$this->allowedClasses = $this->listAllowedClasses () ;
//check to see if $class is in list of allowed classes
if ( ! in_array ( $class , $this->allowedClasses ) )
{
return false ;
}
//check to see if nashCheckLoginViaCurl returned true
if ( ! $this->nashCheckLoginViaCurl () )
{
$this->logout () ;
return false ;
}
//return boolean or $authentication_token based on DB query
return $this->Authentication_Model->isUserIdRegistered ( $this->userId ) ;
}
/**
* logout
* #return void
*/
public function logout ()
{
$this->session->unset_userdata ( array ( 'id' => 0 ) ) ;
$this->session->sess_destroy () ;
$this->session->sess_start () ;
return redirect ( '/' ) ;
}
/**
* listAllowedClasses
* MAYBE USE A CONFIG FILE FOR THIS?
* #return array
*/
protected function listAllowedClasses ()
{
return array (
'user' , 'testing' , 'home' , 'lesson_assets' , 's3_handler' , 'ajax' ,
'api' ,
'pages' , 'invite' , 'mail' , 'partner' , 'renew' , 'store' , 'news' ,
'breathe' ,
'popup' , 'subscription' , 'lessons'
) ;
}
/**
* Load CI Super object object
*
* #param string $object
* #return object
*/
public function __get ( $object )
{
return get_instance ()->$object ;
}
}
application/models/authentication_model.php
class Authentication_Model extends CI_Model
{
public function isUserIdRegistered ( $uid )
{
$this->db->select ( 'authentication_token' )
->from ( 'users' )
->where ( 'id' , $uid )
->where ( 'authentication_token IS NOT' , 'NULL' )
->limit ( 1 ) ;
$query = $this->db->get () ;
return ( $query->num_rows () > 0 )
? $query->result ()
: FALSE ;
}
}
application/core/MY_Controller.php
class MY_Controller extends CI_Controller
{
protected $authentication_token ;
public function __construct ()
{
parent::__construct () ;
$this->load->library ( 'authentication' ) ;
}
protected function _verifyAccess ( $class )
{
$authorized = $this->authentication->verifyAccess ( strtolower ( $class ) ) ;
if ( ! $authorized )
{
//kill further script execution by returning
//redirect url
return redirect ( 'login' ) ;
}
else
{
$this->authentication_token = $authorized ;
}
return ; //return control back to the controller who called me
}
}
*Testing Different Controllers - simulate post controller hook *
class Some_Controller extends MY_Controller
{
public function __construct ()
{
parent::__construct () ;
$this->_verifyAccess ( __CLASS__ ) ;
}
}
-
class Another_Controller extends MY_Controller
{
public function __construct ()
{
parent::__construct () ;
$this->_verifyAccess ( __CLASS__ ) ;
}
}

Categories