Lumen 5.4.
class AfterMiddleware
{
public function handle($request, Closure $next)
{
try {
return $next($request);
} catch (IpValidationException $e) {
return response()->json($e->getMessage(), 422);
} catch (RemoteException $e) {
return response()->json($e->getMessage(), 503);
} catch (BaseException $e) {
return response()->json($e->getMessage(), 400);
} catch (\Exception $e) {
return response()->json($e->getMessage(), $e->getCode());
}
}
}
After the exception is raised, the $next($request) goes to the following function in Laravel\Lumen\Routing:
/**
* Get the initial slice to begin the stack call.
*
* #param \Closure $destination
* #return \Closure
*/
protected function prepareDestination(BaseClosure $destination)
{
return function ($passable) use ($destination) {
try {
return call_user_func($destination, $passable);
} catch (Exception $e) {
return $this->handleException($passable, $e);
} catch (Throwable $e) {
return $this->handleException($passable, new FatalThrowableError($e));
}
};
}
And it's catched there, so I my AfterMiddleware is useless. Any ideas how to circumvent it? I've found a solution and moved all the exceptions to render() in my Handler class, but it is much more convienient to use middleware.
I haven't tried this, but from Lumen's code, I think it is possible.
The handleException function invoked from prepareDestination checks if the ExceptionHanlder is bound to the container or not. If it is not, it is throwing the exception.
protected function handleException($passable, Exception $e)
{
if (! $this->container->bound(ExceptionHandler::class) || ! $passable instanceof Request) {
throw $e;
}
$handler = $this->container->make(ExceptionHandler::class);
$handler->report($e);
return $handler->render($passable, $e);
}
So, try by removing the below ExceptionHandler binding from bootstrap/app.php
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
This is how I handle mine, its working on Lumen 5.5.* and php 7.1.
Late answer, but hopefully it will helps someone else. š
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Response;
use Illuminate\Validation\ValidationException;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Illuminate\Http\Exception\HttpResponseException;
use Symfony\Component\Debug\Exception\FatalThrowableError;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* #var array
*/
protected $dontReport = [
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
* #return void
*/
public function report(Exception $e)
{
parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* #param \Illuminate\Http\Request $request
* #param \Exception $e
* #return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
// if (env('APP_DEBUG')) {
// return parent::render($request, $e);
// }
$response = [
'success' => false
];
$response['status'] = null;
if ($e instanceof HttpResponseException) {
$response['status'] = Response::HTTP_INTERNAL_SERVER_ERROR;
} elseif ($e instanceof MethodNotAllowedHttpException) {
$response['status'] = Response::HTTP_METHOD_NOT_ALLOWED;
} elseif ($e instanceof NotFoundHttpException) {
$response['status'] = Response::HTTP_NOT_FOUND;
} elseif ($e instanceof AuthorizationException) {
$response['status'] = Response::HTTP_FORBIDDEN;
$e = new AuthorizationException('HTTP_FORBIDDEN', $response['status']);
} elseif ($e instanceof ValidationException && $e->getResponse()) {
$response['status'] = Response::HTTP_BAD_REQUEST;
$e = new ValidationException('HTTP_BAD_REQUEST', $response['status'], $e);
} elseif ($e instanceof ValidationException) {
$response['status'] = 422;
$response['errors'] = $e->validator->errors();
} elseif ($e instanceof ModelNotFoundException) {
$response['status'] = 404;
} elseif ($e instanceof UnableToExecuteRequestException) {
$response['status'] = $e->getCode();
} elseif ($e instanceof FatalThrowableError) {
$response['status'] = Response::HTTP_INTERNAL_SERVER_ERROR;
} elseif ($e) {
$response['status'] = Response::HTTP_INTERNAL_SERVER_ERROR;
$response['unhandled'] = 'exception-lumen-ksoft';
}
if ($response['status']) {
$response['message'] = $e->getMessage();
$response['error_code'] = $e->getCode() ?? '';
// $response['exception'] = $e->getTraceAsString() ?? '';
if (app()->environment() == 'local'){
$response['file'] = $e->getFile() ?? '';
$response['line'] = $e->getLine() ?? '';
}
return response()->json($response, $response['status']);
} else {
return parent::render($request, $e);
}
}
}
Related
I've taken over the code from another developer, and I'm quite confused and stuck: one controller I can call the class method CLASSS::method perfectly OK. the other Controller has a copy of the orginal code and modified. On the second one, I get the "non-static method" error.
Call Chain:
Controller->Class->filtered results->Controller response
1A) (Working) Conttroller
<?php
namespace App\Http\Controllers\V1;
use App\Site as SiteClass;
use Facades\App\Site;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;
use App\{
Http\Controllers\Controller,
Http\Requests\SiteRequest,
Helper\ResourceTrait,
Assets,
Alerts,
Licensee,
Permits,
LandOwner,
Utility
};
use Illuminate\Support\Collection;
class SiteController extends Controller
{
private $obj;
public function __construct()
{
$this->obj = new SiteClass();
}
public function index(Request $request)
{
try
{
$data = Site::filter(
($request->has('sort')? $request->input('sort') : ''),
($request->has('filter')? $request->input('filter') : '')
);
...removed some extra code that's not relevant ...
return response($data);
}
catch(\Exception $e)
{
Log::info('Create exception from here?' . $e);
return response(array('error'=>$e->getMessage()),422);
}
} // index
....
}
1B) (Working) Class
<?php
namespace App;
use Illuminate\Support\Facades\Config;
use \App\BaseModel;
class Site extends BaseModel
{
protected $table = 'sites';
protected $fillable = [
"status","structureType","siteId","name","coverage","address","postCode", "subdistrict", "district", "region", "state", "country", "localCouncil", "latitude", "longitude", "dimensions",
"siteHandover", "startBilling", "utilityBillAcct", "utilityBillingAddress", "renewalTerm",
"capex", "opex", "siteManager", "siteManagerPhone", "siteManagerEmail", "siteOwnerManager", "siteOwnerManagerPhone", "siteOwnerManagerEmail"
];
...
// Working Static method call.
public function filter($sort = null, $search = null)
{
$data = $this;
// check if search variable not empty
if ($search != null)
{
$data = $data->where(function ($query) use ($search){
return $query->where($this->table.'.name','like','%'.$search.'%')
->orWhere($this->table.'.status','=',$search)
->orWhere($this->table.'.siteId','like','%'.$search.'%')
->orWhere($this->table.'.address','like','%'.$search.'%')
->orWhere($this->table.'.subdistrict','like','%'.$search.'%')
->orWhere($this->table.'.district','like','%'.$search.'%')
->orWhere($this->table.'.region','like','%'.$search.'%')
->orWhere($this->table.'.state','like','%'.$search.'%')
->orWhere($this->table.'.country','like','%'.$search.'%')
->orWhere($this->table.'.localCouncil','like','%'.$search.'%')
;
});
if ($sort != null)
{
$sorts = explode('|', $sort);
$data = $data->orderBy($sorts[0],$sorts[1]);
}
}
// check if sort variable not empty
if ($sort != null)
{
$sorts = explode('|', $sort);
$data = $data->orderBy($sorts[0],$sorts[1]);
}
else
{
$data = $data->orderBy('siteId','desc');
}
// return data
return $data->paginate(Config::get('api.records'));
}
}
2A) (Failing) Controller
<?php
namespace App\Http\Controllers\V1;
use App\{
Http\Controllers\Controller,
Helper\ResourceTrait,
Http\Requests\OrganisationRequest,
Organisation
};
use Illuminate\{
Http\Request,
Support\Facades\Config,
Support\Facades\Log
};
class OrganisationController extends Controller
{
private $org;
public function __construct()
{
$this->org = new Organisation();
}
public function index(Request $request)
{
try
{
//WORKAROUND: $this->org->... works
$data = Organisation::filter(
($request->has('sort')? $request->input('sort') : ''),
($request->has('filter')? $request->input('filter') : '')
); // FAILS with non-static method call error
return response($data);
}
catch(\Exception $e)
{
return response(array('error'=>$e->getMessage()),422);
}
} // index
}
...
2B) Failing Class
<?php
namespace App;
use Illuminate\Support\Facades\Config;
use \App\BaseModel;
class Organisation extends BaseModel
{
protected $table = 'organisation';
public function filter($sort = null, $search = null)
{
$data = $this;
// check if search variable not empty
if ($search != null)
{
$data = $data->where(function ($query) use ($search){
return $query->where($this->table.'.name','like','%'.$search.'%')
;
});
if ($sort != null)
{
$sorts = explode('|', $sort);
$data = $data->orderBy($sorts[0],$sorts[1]);
}
}
// check if sort variable not empty
if ($sort != null)
{
$sorts = explode('|', $sort);
$data = $data->orderBy($sorts[0],$sorts[1]);
}
else
{
$data = $data->orderBy('name');
}
// return data
return $data->paginate(Config::get('api.records'));
}
}
To my untutored eye, they look identical, yet one works and the other doesn't. Apologies in advance for the volume of code, but I don't know which parts are affecting what. I suspect it's somethng to do with an imported class, but I'm lost frankly :-D
Site has a Facade while Organisation does not.
Facades (from the docs) provide a "static" interface to classes that are available in the application's service container.
I want simply initialise the \AsyncMysqlConnectionResult $connec; object
<?hh
namespace Connection;
require_once("ini.php");
/**
* Class for execute and fetch query
*/
class MyQuery
{
/**
* if connection isn't valid recreate pool
*/
private ?\AsyncMysqlConnectionPool $pool;
/**
* \AsyncMysqlConnection object, store $conn
*/
private \AsyncMysqlConnection $connec;
/**
* \AsyncMysqlQueryReturn object, store return query
*/
private \AsyncMysqlQueryResult $result;
/**
* check if $conn object isValid(), if not release
* connection
*/
public function __construct(\AsyncMysqlConnection $conn)
{
if ($conn->isValid() == false)
{
$this->pool = new MyPool();
$this->connec = $this->pool->connect();
}
else
$this->connec = $conn;
$this->result = object;
}
/**
* escape query and execute it
*/
public async function query(string $query): Awaitable<\AsyncMysqlQueryResult>
{
$query = $this->connec->escapeString($query);
echo "Query escape\n";
/* Try to execute the query, if fail display error */
try
{
$this->result = await $this->connec->query($query);
//log request with ini
}
catch (Exception $e)
{
echo "Couldn't execute the request, error with message :<br>";
var_dump($e->getMessage());
//log request with fail
}
echo "Query done succefully\n";
return $this->result;
}
/**
* escape Map array and execute the request
*/
public async function queryf(HH\FormatString<HH\SQLFormatter> $query, array<string> $params): Awaitable<\AsyncMysqlQueryResult>
{
$i = 0;
while ($params[$i++])
$params[$i] = $this->connec->escapeString($params[$i]);
/* Try to execute the query, if fail display error */
try
{
$result = await $this->connec->queryf($query, implode(', ', $params));
//log request with ini
}
catch (Exception $e)
{
echo "Couldn't execute the request, error with message :<br>";
var_dump($e->getMessage());
//log request with fail
}
echo "Query done succefully\n";
return $this->result;
}
}
newtype AsyncMysqlConnectionResult = object;
newtype FormatString<T> = string;
async function simple_query(\AsyncMysqlConnection $conn): Awaitable<Vector>
{
$connec = new MyQuery($conn);
$ret = await $connec->query('SELECT * FROM users');
return $ret->vectorRows();
}
function run_query(\AsyncMysqlConnection $conn): void
{
$r = \HH\Asio\join(simple_query($conn));
var_dump($r);
}
run_query($conn);
For having this object I use https://docs.hhvm.com/hack/reference/class/AsyncMysqlConnectionPool/connect/ class and connect() method to have this : \AsyncMysqlConnectionResult $connec object.
I can't find a way to initialise this variable type, I've try to
create newtype AsyncMysqlConnectionResult = object but the filechecker return me :
Unbound name: Connection\object (an object type)
Instead of storing the result on the class, why doesn't your query methods simply return the result. For example:
public async function query(string $query): Awaitable<\AsyncMysqlQueryResult>
{
$query = $this->connec->escapeString($query);
return await $this->connec->query($query);
}
or if you really want the result to be stored on the class, make it nullable. This will allow you to not set it in the constructor, and only set it after a query has been made.
private ?\AsyncMysqlQueryResult $result;
This is the only way a find to rewrite queryf() method.
public async function queryf($query, array<int, string> $params): Awaitable<\AsyncMysqlQueryResult>
{
$result = "";
/* Try to execute the query, if fail display error */
try // execute query
{
$result = await $this->connec->queryf($query, implode(', ', $params));
// If log_request === TRUE log request with ini
if ($this->log_request === TRUE)
await $this->logRequest($query, 0);
}
catch (Exception $e) // If the query can't be execute display error
{
echo "\nCouldn't execute the request, error with message :<br>\n";
var_dump($e->getMessage());
//log request with fail
await $this->logRequest((string)$query, -1);
}
return (object)$result;
}
I have no error and everything work fine.
If someone have a better and solution I'm here.
I finished transitioning to PDO and am modifying my system according to fatal errors that pop up.
ERR: Call to a member function execute() on a non-object in /home/a1933806/public_html/globals/server-bin/php/core.php
LINE: 43
This is my setup with affected line in bold:
class netCore {
private $armor;
private $boot;
private $dbHost = "*****.*******.com";
private $dbNAME = "********";
private $dbPASS = "********";
private $dbUSR = "********";
private $err;
private $state;
public function __construct() {
$bootloadr = "mysql:host=".$this->dbHost.";dbname=".$this->dbNAME.";charset=UTF8";
$opt = array(PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
try {
$this->boot = new PDO($bootloadr, $this->dbUSR, $this->dbPASS, $opt);
} catch(PDOException $e) {
$this->err = "<b>LebensbornĀ® netCoreā¢ Error:</b> An exception has been raised during Network-to-Database procedures.<br /><b>Message:</b> ".$e->getMessage().".";
}
}
public function bind($param, $value, $type = null) {
if(is_null($type)) {
switch(true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->state->bindValue($param, $value, $type);
}
public function exe() {
return $this->state->execute();
}
public function count() {
return $this->state->rowCount();
}
public function q($q) {
try {
$this->armor = $this->boot->prepare($q);
$this->state = $armor;
} catch(PDOException $e) {
$this->err = "<b>LebensbornĀ® netCoreā¢ Error:</b> An exception has been raised during Network-to-Database procedures.<br /><b>Message:</b> ".$e->getMessage().".";
}
}
public function set() {
$this->exe();
return $this->state->fetchAll(PDO::FETCH_ASSOC);
}
public function single() {
$this->exe();
return $this->state->fetch(PDO::FETCH_ASSOC);
}
public function transBegin() {
return $this->boot->beginTransaction();
}
public function transCancel() {
return $this->boot->rollBack();
}
public function transEnd() {
return $this->boot->commit();
}
}
I seem to be losing my post data when passing it from my Controller to my Mapper to insert into my DB. I'm new to this and using the Guestbook template but modified it to be adding a "deal". This is what I have:
Controller
public function newAction()
{
$request = $this->getRequest();
$form = new Application_Form_Deal();
if ($this->getRequest()->isPost()) {
if ($form->isValid($request->getPost())) {
$posts = $form->getValues();
//print_r($posts);
$newdeal = new Application_Model_Deal($posts);
$mapper = new Application_Model_DealMapper();
$mapper->save($newdeal);
return $this->_helper->redirector('index');
}
}
$this->view->form = $form;
}
This is my Mapper
public function save(Application_Model_Deal $deal)
{
$data = array(
'dealname' => $deal->getDealName(),
'dealclient' => $deal->getDealClient(),
'dealtelephone' => $deal->getDealTelephone(),
'dealvalue' => $deal->getDealValue(),
'dealdescription' => $deal->getDealDescription(),
'dealcreated' => date('Y-m-d H:i:s'),
'dealmodified' => date('Y-m-d H:i:s'),
);
/*echo "<pre>";
print_r($data);
echo "</pre>";
exit();*/
if (null === ($dealid = $deal->getDealId())) {
unset($data['dealid']);
$this->getDbTable()->insert($data);
} else {
$this->getDbTable()->update($data, array('dealid = ?' => $dealid));
}
}
protected $_dealmodified;
protected $_dealcreated;
protected $_dealdescription;
protected $_dealvalue;
protected $_dealtelephone;
protected $_dealclient;
protected $_dealname;
protected $_dealid;
public function __construct(array $options = null)
{
if (is_array($options)) {
$this->setOptions($options);
}
}
public function __set($name, $value)
{
$method = 'set' . $name;
if (('mapper' == $name) || !method_exists($this, $method)) {
throw new Exception('Invalid deal property');
}
$this->$method($value);
}
public function __get($name)
{
$method = 'get' . $name;
if (('mapper' == $name) || !method_exists($this, $method)) {
throw new Exception('Invalid deal property');
}
return $this->$method($value);
}
public function setOptions(array $options)
{
$methods = get_class_methods($this);
foreach ($options as $key => $value) {
$method = 'set' . ucfirst($key);
if (in_array($method, $methods)) {
$this->$method($value);
}
}
return $this;
}
public function setDealModified($ts)
{
$this->_dealmodified = $ts;
return $this;
}
public function getDealModified()
{
return $this->_dealmodified;
}
public function setDealCreated($ts)
{
$this->_dealcreated = $ts;
return $this;
}
public function getDealCreated()
{
return $this->_dealcreated;
}
public function setDealDescription($text)
{
$this->_dealdescription = (string) $text;
return $this;
}
public function getDealDescription()
{
return $this->_dealdescription;
}
public function setDealValue( $text)
{
$this->_dealvalue = $text;
return $this;
}
public function getDealValue()
{
return $this->_dealvalue;
}
public function setDealTelephone($text)
{
$this->_dealtelephone = $text;
return $this;
}
public function getDealTelephone()
{
return $this->_dealtelephone;
}
public function setDealClient($text)
{
$this->_dealclient = $text;
return $this;
}
public function getDealClient()
{
return $this->_dealclient;
}
public function setDealName($text)
{
$this->_dealname = $text;
return $this;
}
public function getDealName()
{
return $this->_dealname;
}
public function setDealId($dealid)
{
$this->_dealid = (int) $dealid;
return $this;
}
public function getDealId()
{
// $this->_dealid = (int) $value;
return $this->_dealid;
}
I am a complete loss as to why, when I print_r my $data var in the Mapper everything is gone.
Please help!
This looks odd $mapper->save($newdeal, $posts);
your api is save(Application_Model_Deal $deal)
so it should read $mapper->save($newdeal);.
if you really want to get a handle on mappers and models, these three links helped me alot:
http://survivethedeepend.com/
http://phpmaster.com/building-a-domain-model/
http://phpmaster.com/integrating-the-data-mappers/
You are after a specific work flow :
present form
collect from data (the $post)
validate $post data (if(isValid())
get valid and filtered form values ($form->getValues())
instantiate your deal object ($newdeal = new Application_Model_Deal($posts);)
save/update your deal with your mapper
on success redirect
once your deal object is created the $post data has no further value and the deal object is the important thing to think about. Hope this helps a bit.
Ok I think I found it:
your problem revolves around this $method = 'set' . ucfirst($key); this line will try and call $this->setProperty(); your getters and setters are set up camel case so they won't work. The easiest way to fix this is to rename your getters and setters to:
public function setDealmodified($ts)//not camel cased only first letter is capped.
{
$this->_dealmodified = $ts;
return $this;
}
or you have to camel case your array keys.
Your save() method in the mapper does not have a second argument which you used as your $post parameter.
Refactor:
public function save(Application_Model_Deal $deal, array $post)...
Hello I get the following messages at my site www.csvc.nl
Fatal error: Call to a member function getPermissionKeyByHandle() on a non-object in /var/www/vhosts/csvc.nl/httpdocs/cms/updates/concrete5.6.0/concrete/core/models/permission/response.php on line 53
The PHP code is:
<?php
defined('C5_EXECUTE') or die("Access Denied.");
class Concrete5_Model_PermissionResponse {
protected $object;
protected $allowedPermissions = array();
protected $customClassObjects = array();
protected $category;
static $cache = array();
public function setPermissionObject($object) {
$this->object = $object;
}
public function getPermissionObject() {
return $this->object;
}
public function setPermissionCategoryObject($category) {
$this->category = $category;
}
public function testForErrors() { }
public static function getResponse($object) {
$r = PermissionCache::getResponse($object);
if (is_object($r)) {
return $r;
}
$category = PermissionKeyCategory::getByHandle(Loader::helper('text')- >uncamelcase(get_class($object)));
if (!is_object($category) && $object instanceof Page) {
$category = PermissionKeyCategory::getByHandle('page');
}
$txt = Loader::helper('text');
$c1 = get_class($object) . 'PermissionResponse';
if (!class_exists($c1)) {
$c1 = 'PagePermissionResponse';
}
$pr = new $c1();
$pr->setPermissionObject($object);
$pr->setPermissionCategoryObject($category);
PermissionCache::addResponse($object, $pr);
return $pr;
}
public function validate($permission, $args = array()) {
$u = new User();
if ($u->isSuperUser()) {
return true;
}
$pk = $this->category->getPermissionKeyByHandle($permission);
if (!$pk) {
print t('Unable to get permission key for %s', $permission);
exit;
}
$pk->setPermissionObject($this->object);
return call_user_func_array(array($pk, 'validate'), $args);
}
public function __call($f, $a) {
$permission = substr($f, 3);
$permission = Loader::helper('text')->uncamelcase($permission);
return $this->validate($permission, $a);
}
}
Does anybody knows what the problem is?
I had a similar issue on an incomplete 5.6.0 upgrade.
Concrete 5 has a core upgrade troubleshooting guide
For me, I just had to do this on my site: http://example.com/index.php/tools/required/upgrade and use the upgrade button.
FYI, this added entries to PermissionKeyCategories and other tables (which existed, but were empty).