Got an error in `php artisan migrate` in Laravel - mysql

I always use Laravel project since Laravel 4 up to 7. But this is my first time encountering and error when I migrate my database in freshly download Laravel. This is the error when I migrate:
$e = $event->getThrowable();
if (!$event->hasResponse()) {
$this->finishRequest($request, $type);
throw $e;
}
$response = $event->getResponse();
// the developer asked for a specific status code
if (!$event->isAllowingCustomResponseCode() && !$response->isClientError() && !$response->isServerError() && !$response->isRedirect()) {
// ensure that we actually have an error response
if ($e instanceof HttpExceptionInterface) {
// keep the HTTP status code and headers
$response->setStatusCode($e->getStatusCode());
$response->headers->add($e->getHeaders());
} else {
$response->setStatusCode(500);
}
}
try {
return $this->filterResponse($response, $request, $type);
} catch (\Exception $e) {
return $response;
}
}
/**
* Returns a human-readable string for the specified variable.
*/
private function varToString($var): string
{
if (\is_object($var)) {
return sprintf('an object of type %s', \get_class($var));
}
if (\is_array($var)) {
$a = [];
foreach ($var as $k => $v) {
$a[] = sprintf('%s => ...', $k);
}
return sprintf('an array ([%s])', mb_substr(implode(', ', $a), 0, 255));
}
if (\is_resource($var)) {
return sprintf('a resource (%s)', get_resource_type($var));
}
if (null === $var) {
return 'null';
}
if (false === $var) {
return 'a boolean value (false)';
}
if (true === $var) {
return 'a boolean value (true)';
}
if (\is_string($var)) {
return sprintf('a string ("%s%s")', mb_substr($var, 0, 255), mb_strlen($var) > 255 ? '...' : '');
}
if (is_numeric($var)) {
return sprintf('a number (%s)', (string) $var);
}
return (string) $var;
}
}
Error
Stack trace:
#0 D:\Supporting Enterprises\Projects\Laravel Projects\SuperpagesAPI\artisan(18): require()
#1 {main}
thrown in D:\Supporting Enterprises\Projects\Laravel Projects\SuperpagesAPI\vendor\autoload.php on line 7
Fatal error: Uncaught Error: Class 'ComposerAutoloaderInitbe984857c53a573c5f216d0eb36fe0e7' not found in D:\Supporting Enterprises\Projects\Laravel Projects\SuperpagesAPI\vendor\autoload.php:7
Stack trace:
#0 D:\Supporting Enterprises\Projects\Laravel Projects\SuperpagesAPI\artisan(18): require()
#1 {main}
thrown in D:\Supporting Enterprises\Projects\Laravel Projects\SuperpagesAPI\vendor\autoload.php on line 7
Before this happen I start IIS from the IIS Manager. I don't know if this will effect. I turn it on because I run a C# web application on my end.

It looks like this is composer problem. Just try to run this bash script:
composer dump-autoload

Related

Return JsonResponse when i use an AuthTokenAuthenticator (symfony 3)

I specify that I start with Symfony. I want to create an API (without FOSRestBundle) with a token as a means of authentication.
I followed different tutorials for this set up. What I would like is when there is an error that is picked up by the class "AuthTokenAuthenticator", it is returned a json and not a html view.
Here are my script:
AuthTokenAuthenticator
namespace AppBundle\Security;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Http\Authentication\SimplePreAuthenticatorInterface;
use Symfony\Component\Security\Http\HttpUtils;
use Symfony\Component\HttpFoundation\JsonResponse;
class AuthTokenAuthenticator implements
SimplePreAuthenticatorInterface, AuthenticationFailureHandlerInterface
{
const TOKEN_VALIDITY_DURATION = 12 * 3600;
protected $httpUtils;
public function __construct(HttpUtils $httpUtils)
{
$this->httpUtils = $httpUtils;
}
public function createToken(Request $request, $providerKey)
{
//$targetUrlToken = '/auth-tokens'; // login
//$targetUrlUser = '/users/create'; // create account
/*if ($request->getMethod() === "POST" && $this->httpUtils->checkRequestPath($request, $targetUrlUser) || $request->getMethod() === "POST" && $this->httpUtils->checkRequestPath($request, $targetUrlToken) ) {
return;
}*/
$authTokenHeader = $request->headers->get('X-Auth-Token');
if (!$authTokenHeader) {
//return new JsonResponse(array("error" => 1, "desc" => "INVALID_TOKEN", "message" => "X-Auth-Token header is required"));
throw new BadCredentialsException('X-Auth-Token header is required');
}
return new PreAuthenticatedToken(
'anon.',
$authTokenHeader,
$providerKey
);
}
public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
{
if (!$userProvider instanceof AuthTokenUserProvider) {
throw new \InvalidArgumentException(
sprintf(
'The user provider must be an instance of AuthTokenUserProvider (%s was given).',
get_class($userProvider)
)
);
}
$authTokenHeader = $token->getCredentials();
$authToken = $userProvider->getAuthToken($authTokenHeader);
if (!$authToken || !$this->isTokenValid($authToken)) {
throw new BadCredentialsException('Invalid authentication token');
}
$user = $authToken->getUser();
$pre = new PreAuthenticatedToken(
$user,
$authTokenHeader,
$providerKey,
$user->getRoles()
);
$pre->setAuthenticated(true);
return $pre;
}
public function supportsToken(TokenInterface $token, $providerKey)
{
return $token instanceof PreAuthenticatedToken && $token->getProviderKey() === $providerKey;
}
/**
* Vérifie la validité du token
*/
private function isTokenValid($authToken)
{
return (time() - $authToken->getCreatedAt()->getTimestamp()) < self::TOKEN_VALIDITY_DURATION;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
throw $exception;
}
}
Here is the error return that I have when I do not inform the token:
<!DOCTYPE html>
<html>
<head>
<title> X-Auth-Token header is required (500 Internal Server Error)
How can i do to get a return json response ?
If i try to do a return new JsonResponse(array("test" => "KO")) (simple example), i get this error:
<title> Type error: Argument 1 passed to Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager::authenticate() must be an instance of Symfony\Component\Security\Core\Authentication\Token\TokenInterface, instance of Symfony\Component\HttpFoundation\JsonResponse given, called in /Users/mickaelmercier/Desktop/workspace/api_monblocrecettes/vendor/symfony/symfony/src/Symfony/Component/Security/Http/Firewall/SimplePreAuthenticationListener.php on line 101 (500 Internal Server Error)
You can create your own Error Handler. It's a event listener or subscriber that listens to kernel.exception, when it adds a response to the event, the event propagation is stopped, so the default error handler will not be triggered.
It could look something like this:
<?php declare(strict_types = 1);
namespace App\EventSubsbscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\KernelEvents;
final class ExceptionToJsonResponseSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [
KernelEvents::EXCEPTION => 'onKernelException',
];
}
public function onKernelException(GetResponseForExceptionEvent $event): void
{
// Skip if request is not an API-request
$request = $event->getRequest();
if (strpos($request->getPathInfo(), '/api/') !== 0) {
return;
}
$exception = $event->getException();
$error = [
'type' => $this->getErrorTypeFromException($exception),
// Warning! Passing the exception message without checks is insecure.
// This will potentially leak sensitive information.
// Do not use this in production!
'message' => $exception->getMessage(),
];
$response = new JsonResponse($error, $this->getStatusCodeFromException($exception));
$event->setResponse($response);
}
private function getStatusCodeFromException(\Throwable $exception): int
{
if ($exception instanceof HttpException) {
return $exception->getStatusCode();
}
return 500;
}
private function getErrorTypeFromException(\Throwable $exception): string
{
$parts = explode('\\', get_class($exception));
return end($parts);
}
}
ApiPlatform provides its own exception listener like this, that is more advanced, that you could look into if you need "better" exception responses.

PHP Fatal error Uncaught Error: Call to a member function getMetaTitle() on null in

I'm getting the following error but it says it in Magento core. I was wondering how to debug this because I'm sure there is nothing wrong in Magentos core.
Here is the error:
30-Apr-2018 18:05:23 UTC] PHP Fatal error: Uncaught Error: Call to a member function getMetaTitle() on null in /home/example/public_html/app/code/core/Mage/Catalog/Block/Product/View.php:18
Stack trace:
#0 /home/example/public_html/app/code/core/Mage/Core/Block/Abstract.php(139): Mage_Catalog_Block_Product_View->_prepareLayout()
#1 /home/example/public_html/app/code/core/Mage/Core/Model/Layout.php(322): Mage_Core_Block_Abstract->setLayout(Object(Inchoo_PHP7_Model_Layout))
#2 /home/example/public_html/app/code/core/Mage/Core/Model/Layout.php(332): Mage_Core_Model_Layout->createBlock('review/product_...', 'product.info')
#3 /home/example/public_html/app/code/core/Mage/Core/Model/Layout.php(147): Mage_Core_Model_Layout->addBlock('review/product_...', 'product.info')
#4 /home/example/public_html/app/code/core/Mage/Core/Model/Layout.php(119): Mage_Core_Model_Layout->_generateBlock(Object(Mage_Core_Model_Layout_Element), Object(Mage_Core_Model_Layout_Element))
#5 /home/example/public_html/app/co in /home/example/public_html/app/code/core/Mage/Catalog/Block/Product/View.php on line 18
Here is /home/angelsforeveryon/public_html/app/code/core/Mage/Catalog/Block/Product/View.php:18
protected function _prepareLayout()
{
$this->getLayout()->createBlock('catalog/breadcrumbs');
$headBlock = $this->getLayout()->getBlock('head');
if ($headBlock) {
$product = $this->getProduct();
line 18 here --> $title = $product->getMetaTitle();
if ($title) {
$headBlock->setTitle($title);
}
$keyword = $product->getMetaKeyword();
$currentCategory = Mage::registry('current_category');
if ($keyword) {
$headBlock->setKeywords($keyword);
} elseif ($currentCategory) {
$headBlock->setKeywords($product->getName());
}
$description = $product->getMetaDescription();
if ($description) {
$headBlock->setDescription( ($description) );
} else {
$headBlock->setDescription(Mage::helper('core/string')->substr($product->getDescription(), 0, 255));
}
if ($this->helper('catalog/product')->canUseCanonicalTag()) {
$params = array('_ignore_category' => true);
$headBlock->addLinkRel('canonical', $product->getUrlModel()->getUrl($product, $params));
}
}
return parent::_prepareLayout();
}
Thanks
it looks like your product is null, you need make sure this function work well
$product = $this->getProduct();

PHP Fatal Error – yii\base\ErrorException

I have uploaded my site to fpt and I can't fix that error. Please help me.
The error is:
PHP Fatal Error – yii\base\ErrorException
Call to undefined function yii\web\json_encode()
Error is on the line $hash = md5(json_encode($this->rules));
The code is:
public function init()
{
parent::init();
if (!$this->enablePrettyUrl || empty($this->rules)) {
return;
}
if (is_string($this->cache)) {
$this->cache = Yii::$app->get($this->cache, false);
}
if ($this->cache instanceof Cache) {
$cacheKey = $this->cacheKey;
$hash = md5(json_encode($this->rules));
if (($data = $this->cache->get($cacheKey)) !== false && isset($data[1]) && $data[1] === $hash) {
$this->rules = $data[0];
} else {
$this->rules = $this->buildRules($this->rules);
$this->cache->set($cacheKey, [$this->rules, $hash]);
}
} else {
$this->rules = $this->buildRules($this->rules);
}
}

Yii2 show error when exception occurs

I have this code in my controller:
...
if (Model::validateMultiple($ttepk)) {
$transaction = \Yii::$app->db->beginTransaction();
try {
foreach ($ttepk as $ttep) {
$ttep->save(false);
if (!$ttep->assignPs()) {
throw new UserException('assignPs failed');
}
}
$transaction->commit();
return $this->redirect(['index']);
} catch (Exception $ex) {
$transaction->rollBack();
throw $ex;
}
}
...
in model:
...
public function assignPs() {
foreach (...) {
$ttepetk[...] = new Ttepet;
$ttepetk[...]->ttepId = $this->id;
... // set other attributes
}
}
if (Model::validateMultiple($ttepetk)) {
foreach ($ttepetk as $ttepet) {
$ttepet->save(false);
}
return true;
} else {
return false;
}
}
...
Everything is working fine (no inserts are happening if any of the models fail validation), except that I would like to see the exact error, exactly by which Ttep (each Ttep is a model) and by which Ttepet (Ttep:Ttepet = 1:N) has the error happened, and what was that. Now I see the Exeption page only, and I don't know how to make the errors visible. Please point me to the right direction. Thanks!
You could iterate on each single model validating one by one and getting the errors when occurs ...
if (Model::validateMultiple($ttepetk)) {
foreach ($ttepetk as $ttepet) {
$ttepet->save(false);
}
return true;
} else {
foreach($ttepetk as $model){
if ($model->validate()) {
// all inputs are valid
} else {
// validation failed: $errors is an array containing error messages
$errors = $model->errors;
}
}
return $errors;
}
you can get the errors this way
$myErrorResult = $ttep->assignPs();
if (!$myErrorResult) {
......

Silex: error handlers for specific exception types

It it possible in Silex to use an error handler based on what exception is thrown?
I know this is possible with a single exception handler and a switch statement on the classname of the thrown exception but to me it seems the "Silex way" is cleaner, yet doesn't work.
This is how I would expect it to work
<?php
// Handle access denied errors
$app->error(function (\App\Rest\Exception\AccessDenied $e) {
$message = $e->getMessage() ?: 'Access denied!';
return new Response($message, 403);
});
// Handle Resource not found errors
$app->error(function (\App\Rest\Exception\ResourceNotFound $e) {
$message = $e->getMessage() ?: 'Resource not found!';
return new Response($message, 404);
});
// Handle other exception as 500 errors
$app->error(function (\Exception $e, $code) {
return new Response($e->getMessage(), $code);
});
Problem is that when I throw a ResourceNotFound exception in my controller, the errorhandler tied to AccessDenied is executed
Catchable fatal error: Argument 1 passed to {closure}() must be an instance of App\Rest\Exception\AccessDenied, instance of App\Rest\Exception\ResourceNotFound given
Is this achievable in another way or should I just stuff everything in the handler that works with generic Exceptions and switch on the type of exception thrown?
PS: i'm aware of the $app->abort() method but prefer working with exceptions
EDIT: This feature has now made it into Silex core!
This is currently not possible. Right now you'd have to either have a single handler with a switch statement, or many handlers with an if ($e instanceof MyException) each.
I do like the idea though, and it should be possible to implement it by using reflection. It would be awesome if you could create a new ticket on the tracker, or even work on a patch, if you're interested.
Cheers!
Another solution that I use in my projects:
class ProcessCallbackException extends Exception
{
public function __construct(\Closure $callback, $message = "", Exception $previous = null)
{
parent::__construct($message, 0, $previous);
$this->callback = $callback;
}
public $callback;
}
class AccessDeniedException extends ProcessCallbackException
{
public function __construct($message = null)
{
$f = function() {
return app()->redirect('/login');
};
parent::__construct($f, $message);
}
}
# Handle your special errors
$app->error(function (\Exception $e, $code) {
if ($e instanceof ProcessCallbackException)
{
/** #var ProcessCallbackException $callbackException */
$callbackException = $e;
return call_user_func($callbackException->callback);
}
else
return null;
});