Laravel 4.1 - calling View Composers class - ReflectionException class does not exist - laravel

I keep getting this error when trying to call a View Composer class: Class MyApp/Composers/HeaderComposer does not exist
/app/MyApp/Composers/HeaderComposer.php:
<?php namespace MyApp\Composers;
class HeaderComposer {
public function compose($view) {
$view->with('foo', 'foobar');
}
}
composer.json:
"psr-4": {
"MyApp\\" : "app/MyApp/"
}
routes.php:
View::composer('layouts.default', 'MyApp/Composers/HeaderComposer');
vendor/composer/autoload_psr4.php
<?php
// autoload_psr4.php #generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'MyApp\\' => array($baseDir . '/app/MyApp'),
'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'),
);
What else could I be missing?
Thanks,
Ham

Change forward slashes in
View::composer('layouts.default', 'MyApp/Composers/HeaderComposer');
to back slashes
View::composer('layouts.default', 'MyApp\Composers\HeaderComposer');
and it will work

Related

Why custom Exception was not catch by expectException method?

Making tests on laravel 9 site I try to catch custom Exception and looking at this
Undefind withoutExceptionHandling()
example I do in my tests
<?php
namespace Tests\Feature;
//use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Artisan;
use Tests\TestCase;
use Carbon\Carbon;
use App\Models\Article;
use App\Models\User;
use Illuminate\Support\Str;
class ArticlesCrudTest extends TestCase
{
use InteractsWithExceptionHandling;
public function testNegativeArticleGotFailureWithInactiveUserToBeAdded()
{
$loggedUser = clone(self::$loggedUser);
$this->withoutExceptionHandling();
$loggedUser->status = 'I' ; // Inactive
$newArticleObject = \App\Models\Article::factory(Article::class)->make();
$response = $this->actingAs($loggedUser, 'api')->post(route('articles.store'),
$newArticleObject->toArray());
$this->expectException(\App\Exceptions\UserAccountManagerAccessException::class);
$response->assertStatus(400);
}
But I got error message :
here was 1 error:
1) Tests\Feature\ArticlesCrudTest::testNegativeArticleGotFailureWithInactiveUserToBeAdded
App\Exceptions\UserAccountManagerAccessException: Your account must be active in "store" !
/ProjectPath/app/Library/Services/LocalUserAccountManager.php:59
/ProjectPath/app/Repositories/ArticleCrudRepository.php:191
/ProjectPath/app/Http/Controllers/ArticleController.php:86
/ProjectPath/vendor/laravel/framework/src/Illuminate/Routing/Controller.php:54
/ProjectPath/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php:43
/ProjectPath/vendor/laravel/framework/src/Illuminate/Routing/Route.php:260
/ProjectPath/vendor/laravel/framework/src/Illuminate/Routing/Route.php:205
/ProjectPath/vendor/laravel/framework/src/Illuminate/Routing/Router.php:725
/ProjectPath/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:141
/ProjectPath/vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php:50
/ProjectPath/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:180
/ProjectPath/vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequests.php:126
/ProjectPath/vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequests.php:102
/ProjectPath/vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequests.php:54
/ProjectPath/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:180
/ProjectPath/vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php:44
/ProjectPath/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:180
/ProjectPath/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:116
/ProjectPath/vendor/laravel/framework/src/Illuminate/Routing/Router.php:726
/ProjectPath/vendor/laravel/framework/src/Illuminate/Routing/Router.php:703
/ProjectPath/vendor/laravel/framework/src/Illuminate/Routing/Router.php:667
/ProjectPath/vendor/laravel/framework/src/Illuminate/Routing/Router.php:656
/ProjectPath/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php:190
/ProjectPath/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:141
/ProjectPath/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php:21
/ProjectPath/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ConvertEmptyStringsToNull.php:31
/ProjectPath/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:180
/ProjectPath/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php:21
/ProjectPath/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TrimStrings.php:40
/ProjectPath/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:180
/ProjectPath/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php:27
/ProjectPath/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:180
/ProjectPath/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/PreventRequestsDuringMaintenance.php:86
/ProjectPath/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:180
/ProjectPath/vendor/laravel/framework/src/Illuminate/Http/Middleware/HandleCors.php:62
/ProjectPath/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:180
/ProjectPath/vendor/laravel/framework/src/Illuminate/Http/Middleware/TrustProxies.php:39
/ProjectPath/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:180
/ProjectPath/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:116
/ProjectPath/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php:165
/ProjectPath/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php:134
/ProjectPath/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php:545
/ProjectPath/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php:340
/ProjectPath/tests/Feature/ArticlesCrudTest.php:108
ERRORS!
Tests: 1, Assertions: 0, Errors: 1.
Yes, valid exception UserAccountManagerAccessException was raised, but why methods expectException and $response->assertStatus did not work and my
test did not passed with sucess?
TOPIC DETAILS:
In routes/api.php :
Route::middleware('auth:api') ->group(function () {
Route::apiResource('articles', ArticleController::class);
in app/Http/Controllers/ArticleController.php Repository method is called:
public function store(Request $request)
{
return $this->articleCrudRepository->store(data: $request->only('title', 'text', 'text_shortly',
'creator_id', 'published'), makeValidation: true);
}
and in app/Repositories/ArticleCrudRepository.php Repository :
<?php
namespace App\Repositories;
...
class ArticleCrudRepository
{
public function store(array $data, bool $makeValidation = false): JsonResponse|MessageBag
{
...
$this->userAccountManager->checkPermissions( [ ], "store");
// UserAccountManagerAccessException is raised in method above, BEFORE try block with transaction...
DB::beginTransaction();
try {
$article = Article::create([
'title' => $data['title'],
'text' => $data['text'],
'text_shortly' => $data['text_shortly'],
'creator_id' => $data['creator_id'],
'published' => $data['published'],
]);
DB::Commit();
$article->load('creator');
return response()->json(['article' => (new ArticleResource($article))], 201);
} catch (\Exception $e) {
$errorMessage = $e->getMessage();
\Log::info($errorMessage);
DB::rollback();
return sendErrorResponse($e->getMessage(), 500);
}
}
"guzzlehttp/guzzle": "^7.2",
"laravel/framework": "^9.19",
"laravel/passport": "^11.3",
Thanks in advance!
I need to set such order:
$this->expectException(\App\Exceptions\UserAccountManagerAccessException::class);
And after that :
$response = $this->actingAs($loggedUser, 'api')->post(route('articles.store')
That works!

Error Laravel\Socialite\Two\InvalidStateException In the callback method from the Google side

I want use Socialite package but receive in Error !
controller codes :
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\User;
use Laravel\Socialite\Facades\Socialite;
class GoogleAuthController extends Controller
{
public function redirect()
{
return Socialite::driver('google')->redirect();
}
public function callback()
{
// when i dd() here i see in the answer in the browser.
$googleUser = Socialite::driver('google')->user();
// but dd in here isn't working!
$user = User::where('email', $googleUser->email)->first;
if ($user) {
auth()->loginUsingId($user->id);
} else {
$newUser = User::create([
'name' => $googleUser->name,
'email' => $googleUser->email,
'password' => bcrypt(\Str::random(16)),
]);
auth()->loginUsingId($newUser->id);
}
return $this->redirect('/');
}
}
in web.php :
Route::get('auth/google', 'Auth\GoogleAuthController#redirect')->name('auth.google');
Route::get('auth/google/callback', 'Auth\GoogleAuthController#callback');
laravel version : 6.20.26
php version : 7.2.5
please help me. tnks
===============================================================
I try this (https://stackoverflow.com/a/37849202/20355717) :
Socialite::driver('google')->stateless()->user()
but in did't work for me and give error ! :
GuzzleHttp\Exception\RequestException
cURL error 77: error setting certificate verify locations: CAfile: /path/to
/downloaded/cacert.pem CApath: none (see https://curl.haxx.se/libcurl
/c/libcurl-errors.html) for https://www.googleapis.com/oauth2/v4/token
http://localhost:8000/auth/google/callback?authuser=0&code=4%2F0AfgeXvucuWTlboWqaMwf2bkBe0AHjbPEJd-
2e7cQdlSN345_3imguhVT_1PQ8fa3ISoHSA&prompt=consent&
scope=email%20profile%20openid%20https%3A%2F
%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile%20https%3A%2F
%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&
state=axIlfjFkns6vWNJIX2uJMuMKNiYFfy7cKiE8Xr8W
1- change :
Socialite::driver('google')->user()
to in :
Socialite::driver('google')->stateless()->user()
2- download cacert.pem add this code in php.ini file.
curl.cainfo = "D:\wamp64\bin\php\php7.4.26\cacert.pem
like this https://stackoverflow.com/a/40861755/20355717
3- change
return $this->redirect('/');
in controller to
return view('welcome'); //or an any other view.
4- finish! hope helpful for you!

PSR-4 autoloader Fatal error: Class not found

I have my project structure like so:
src/
├─ Model/
└─ User.php
My User.php file looks like this:
<?php
namespace Bix\Model;
class User {
And my composer.json autoloader is this:
"autoload": {
"psr-4": {
"Bix\\": "src/"
}
}
Finally my bootstrap.php is this:
use Bix\Model\User;
// PSR-4 Autoloader.
require_once "vendor/autoload.php";
However if I try and create a new User(), I get the error Fatal error: Class 'User' not found in /var/www/public/api/v1/index.php on line 8
Looking at the composer autoload_psr4.php file it looks ok:
// autoload_psr4.php #generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname(dirname($vendorDir));
return array(
'XdgBaseDir\\' => array($vendorDir . '/dnoegel/php-xdg-base-dir/src'),
'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'),
'KeenIO\\' => array($vendorDir . '/keen-io/keen-io/src'),
'Bix\\' => array($baseDir . '/src'),
);
Can anybody point out where I am going wrong with the above?
First of all, Linux (I'm not sure which PC you use) is case-sensitive. In your autoloading, you defined src/bix, while it is src/Bix.
But more importantly, with PSR-4, the specified namespace prefix is not included in the directory structure (to avoid directories containing just one directory). In your case, if you configure "Bix\\": "src/", a class Bix\Model\User should be located in src/Model/User.php.
EDIT: You're misunderstanding PHP namespaces. In PHP, you're not saying "import everything from Bix\Model into the global namespace for this file" with use Bix\Model;. Instead, it means: "Alias Model in this file to Bix\Model".
So you should either do:
require_once "vendor/autoload.php";
use Bix\Model;
$user = new Model\User();
or:
require_once "vendor/autoload.php";
use Bix\Model\User;
$user = new User();

codeigniter config form_validation with subfolders not working

I have using a lot config form_validation file. It's working good!
But now I'm trying to get it work with controller in subfolder
/controllers/panel/users.php
My form_validation config file looks like
$config = array(
'panel/users/edit/' => array(
array('field' => 'login', 'label' => 'Логин', 'rules' => "trim|required|valid_email")
)
And my Users controller is
public function edit($user_id = FALSE)
{
if ($this->input->post('save'))
{
$this->load->library('form_validation');
if ($this->form_validation->run())
{
// Do some
}
}
}
But $this->form_validation->run() is always return FALSE
It isn't designed to work this way, there was a relevant change to ruri_string() #122 which would have fixed this but it had other repercussions and needs to be rethought.
You can call your validation rule group explicitly (drop the trailing slash from your rule group name)
if ($this->form_validation->run('panel/users/edit'))
or, if appropriate in your situation, workaround this by prepending uri->segment(1) to the auto-detected rule group.
application/libraries/MY_Form_validation.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation {
function run($group = '')
{
// Prepend URI to match subfolder controller validation rules
$uri = ($group == '') ? $this->CI->uri->segment(1) . $this->CI->uri->ruri_string() : $group;
return parent::run($uri);
}
}

Intergrating Zend Framework 2 and Propel

I've searched far and wide on how to intergrate propel and Zend Framework 2 however I haven't been able to come up with a solution yet.
Here is what I have so far.
Installed ZF2 Skeleton Directory
Inserted Sample Album Table Data from ZF site
My Folder Structure looks like this
--Vendor
----Propel
------album
--------autoload_classmap.php
--------models
----------map
----------om
----------Album.php
----------AlbumPeer.php
----------AlbumQuery.php
------config
--------module.config.php
------Module.php
------autoload_classmap.php
The album/autoload_classmap.php looks like this
//vendor/Propel/album/autoload_classmap.php
<?php
// Generated by ZF2's ./bin/classmap_generator.php
return array(
'AlbumTableMap' => __DIR__ . '/models/map/AlbumTableMap.php',
'BaseAlbumPeer' => __DIR__ . '/models/om/BaseAlbumPeer.php',
'BaseAlbumQuery' => __DIR__ . '/models/om/BaseAlbumQuery.php',
'BaseAlbum' => __DIR__ . '/models/om/BaseAlbum.php',
'Album' => __DIR__ . '/models/Album.php',
'AlbumPeer' => __DIR__ . '/models/AlbumPeer.php',
'AlbumQuery' => __DIR__ . '/models/AlbumQuery.php',
);
Here is the module.config.php
//vendor/Propel/config/module.config.php
<?php
return array();
Here is the Propel/autoload_classmap.php
//vendor/Propel/autoload_classmap.php
<?php
// Generated by ZF2's ./bin/classmap_generator.php
return array(
'Propel' => __DIR__ . '/runtime/lib/Propel.php',
);
and finally the Model.php file
//vendor/Propel/Module.php
<?php
namespace Propel;
class Module
{
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
__DIR__ . '/album/autoload_classmap.php'
)
);
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
}
For the sake of simplicity in this example I put the following code into my Controller.
//module/Application/src/Application/Controller/IndexController.php
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class IndexController extends AbstractActionController
{
public function indexAction()
{
$q = new \Propel\Album();
$q->setArtist('The Who');
$q->setTitle('Tommy');
$q->save();
return new ViewModel();
}
}
The error I get is
Class 'Propel\\Album' not found
The sources I used to get to this point were
https://groups.google.com/forum/?fromgroups=#!searchin/propel-users/zend/propel-users/lsHs-jjxp68/LDrQjzik6gAJ
https://docs.google.com/viewer?a=v&pid=forums&srcid=MDU2NDIxODQyNDc0MDMyNjQ3NzUBMDY3ODcxMTYzMzg0MDA4OTU0MzgBeFpDZUM1WTZqMThKATQBAXYy
Adding Vendor Specific Module To Zend Framework 2.0
If you didn't set namespace in your XML schema, your classes should be accessible in the root namespace, so as \Album for example. If you want to have some other namespace, you shoud define it in database tag of your XML schema. And you should not use Propel namespace anyway as it is reserved for Propel itself. Your generated classes should be long to the namespace of your project.
\Propel\Album is not being found because the class map specifies Album as the class name.
I'm guessing if you added the line: namespace Propel; to each of those Propel related files the classmap generator would put the correct class names. Of course then you would need update an class names in the code that are affected.

Resources